@exercism/codemirror-lang-prolog 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (C) 2026 by Johannes Schuster <johannes.c.schuster@proton.me>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,42 @@
1
+ lang-prolog is licensed under the MIT licence in LICENSE.
2
+
3
+ The operator and built-in predicate tables (spec/prolog/ops.json,
4
+ spec/prolog/builtins.json and the generated src/tables.ts of codemirror-lang-swipl)
5
+ are read from SWI-Prolog by gen/tables.mjs; spec/prolog/SOURCE records the version.
6
+ SWI-Prolog is covered by the Simplified BSD licence:
7
+
8
+ Copyright (c) 1985-2025, University of Amsterdam
9
+ VU University Amsterdam
10
+ CWI, Amsterdam
11
+ SWI-Prolog Solutions b.v.
12
+ All rights reserved.
13
+
14
+ Redistribution and use in source and binary forms, with or without
15
+ modification, are permitted provided that the following conditions
16
+ are met:
17
+
18
+ 1. Redistributions of source code must retain the above copyright
19
+ notice, this list of conditions and the following disclaimer.
20
+
21
+ 2. Redistributions in binary form must reproduce the above copyright
22
+ notice, this list of conditions and the following disclaimer in
23
+ the documentation and/or other materials provided with the
24
+ distribution.
25
+
26
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
29
+ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
30
+ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
31
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
32
+ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
34
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36
+ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37
+ POSSIBILITY OF SUCH DAMAGE.
38
+
39
+ -- https://github.com/SWI-Prolog/swipl/blob/V10.0.2/LICENSE
40
+
41
+ The tests read SWI-Prolog's own library as a corpus at test time; it is not part of
42
+ this repository or the package.
package/README.md CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # @exercism/codemirror-lang-prolog
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [SWI-Prolog](https://www.swi-prolog.org) language support for
4
+ [CodeMirror 6](https://codemirror.net/): a Lezer parser for SWI-Prolog 7+ syntax, with
5
+ highlighting, indentation, folding and completion. Exercism uses it in the Prolog editor on
6
+ [exercism.org](https://exercism.org).
7
+
8
+ ```sh
9
+ npm install @exercism/codemirror-lang-prolog
10
+ ```
11
+
12
+ ```js
13
+ import {EditorView, basicSetup} from "codemirror"
14
+ import {prolog} from "@exercism/codemirror-lang-prolog"
15
+
16
+ new EditorView({extensions: [basicSetup, prolog()], parent: document.body})
17
+ ```
18
+
19
+ `prolog()` returns the `LanguageSupport`; `prologLanguage` is the `LRLanguage`.
20
+
21
+ ## Completion
22
+
23
+ `prolog()` adds `prologCompletion` as the language's completion source. It offers:
24
+
25
+ - the variables of the current clause, when the word starts with an uppercase letter or `_`.
26
+ - the predicates defined in the file, as `name/N`, and DCG nonterminals as `name//N`.
27
+ - SWI-Prolog's built-in predicates, the most used library predicates (from `lists`,
28
+ `apply`, `aggregate`, `pairs`, `clpfd` and others) with their arity, and the
29
+ alphanumeric operators such as `is` and `mod`.
30
+ - snippets for a rule, a fact, a DCG rule and directives where a new clause starts, and
31
+ snippets for if-then-else, `findall`, `forall`, `format`, `maplist` and `catch` inside
32
+ a clause.
33
+
34
+ It offers nothing inside comments, strings or quoted atoms. `clauseSnippets`,
35
+ `goalSnippets` and `globalOptions` are exported for use in other completion sources.
36
+
37
+ ## What it parses
38
+
39
+ The operator and built-in tables come from SWI-Prolog 10.0.2 (see `spec/prolog/SOURCE`
40
+ in the repository).
41
+
42
+ **Operators are not parsed.** Prolog programs change the operator table at run time with
43
+ `op/3`, so no fixed grammar can build the right term for every program. This parser
44
+ reads tokens and the structure that does not depend on operators: clauses and their
45
+ end, the neck (`:-`, `-->`), compound terms, lists, curly terms, dicts and parentheses.
46
+ Between those, terms are flat sequences: `X is A + B` is `Variable Operator Variable
47
+ SymbolAtom Variable`. Operators declared in the edited file still tokenise; they are
48
+ just not highlighted as operators.
49
+
50
+ Each clause is a `Directive`, `Rule` or `Fact` ending in `End`. The name of a clause's
51
+ head is in `HeadFunctor` (after an optional `Module:`), the name of every other compound
52
+ in `Functor`, followed by `ArgList`. Names are told apart by the tables: `Operator`
53
+ (alphanumeric operators such as `is`, `mod`), `Control` (`->`, `\+`, `call`, `true`,
54
+ ...), `DirectiveName` (`dynamic`, `use_module`, ...), `Builtin` (other built-in
55
+ predicates, by name only), and plain `Atom`. `f(` is a compound and `t{` a dict, `f (`
56
+ and `t {` are not, as in SWI-Prolog. Block comments nest, as in SWI-Prolog.
57
+
58
+ The parser is more lenient than SWI-Prolog: it accepts some input that SWI-Prolog
59
+ rejects (`X(a)`, digits out of range for their radix, unknown escapes). It only
60
+ recognises ASCII digits in numbers, and a digit group split by a comment
61
+ (`1_000_/*c*/000`) is not one number to it.
62
+
63
+ The tests check every token class and clause kind, and parse the `.pl` files of
64
+ SWI-Prolog's own library: each file that SWI-Prolog's reader accepts must parse without
65
+ error nodes and into as many clauses as SWI-Prolog reads terms. Exceptions are listed in
66
+ `test/KNOWN.md`.
67
+
68
+ ## Building and testing
69
+
70
+ From the root of the repository, run `pnpm install` (which also builds the package into
71
+ `dist/`), then `pnpm -r run build` to rebuild it and `pnpm -r test` to run the tests.
72
+
73
+ ## Files
74
+
75
+ Generated by `pnpm generate` (`gen/tables.mjs` in the repository) from a run of the
76
+ pinned `swipl`: `src/tables.ts`, and in the repository `spec/prolog/ops.json`,
77
+ `spec/prolog/builtins.json` and `spec/prolog/SOURCE`.
78
+
79
+ Hand-written: `src/prolog.grammar`, `src/tokens.js` (the tokenizer for names, symbol
80
+ characters, clause ends, nested comments and quasi-quotations), `src/highlight.ts`,
81
+ `src/index.ts`, the tests, and in the repository `spec/prolog/control.json` (the control
82
+ constructs and directive names, which `pnpm generate` checks against the generated
83
+ tables) and `tools/`.
@@ -0,0 +1,5 @@
1
+ import { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete";
2
+ export declare const clauseSnippets: readonly Completion[];
3
+ export declare const goalSnippets: readonly Completion[];
4
+ export declare const globalOptions: readonly Completion[];
5
+ export declare function prologCompletion(context: CompletionContext): CompletionResult | null;
@@ -0,0 +1,2 @@
1
+ import type { NodePropSource } from "@lezer/common";
2
+ export declare const prologHighlighting: NodePropSource;
package/dist/index.cjs ADDED
@@ -0,0 +1,447 @@
1
+ 'use strict';
2
+
3
+ var lr = require('@lezer/lr');
4
+ var highlight = require('@lezer/highlight');
5
+ var language = require('@codemirror/language');
6
+ var autocomplete = require('@codemirror/autocomplete');
7
+
8
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
9
+ const BlockComment = 1,
10
+ End = 2,
11
+ Neck = 3,
12
+ Colon = 4,
13
+ Control = 5,
14
+ SymbolAtom = 6,
15
+ Atom = 7,
16
+ Operator = 8,
17
+ DirectiveName = 9,
18
+ Builtin = 10,
19
+ Variable = 11,
20
+ Anonymous = 12,
21
+ QuasiQuotation = 13,
22
+ CallOpen = 14,
23
+ DictOpen = 15;
24
+
25
+ // Generated by gen/tables.mjs from spec/prolog/*.json (SWI-Prolog version 10.0.2). Do not edit.
26
+ const operators = ["as", "discontiguous", "div", "dynamic", "initialization", "is", "meta_predicate", "mod", "module_transparent", "multifile", "public", "rdiv", "rem", "table", "thread_initialization", "thread_local", "volatile", "xor"];
27
+ const control = ["!", ",", ";", "->", "*->", "\\+", "call", "catch", "throw", "true", "fail", "false"];
28
+ const directives = ["discontiguous", "dynamic", "ensure_loaded", "initialization", "license", "meta_predicate", "module", "module_transparent", "multifile", "op", "public", "reexport", "set_prolog_flag", "table", "thread_local", "use_foreign_library", "use_module", "volatile"];
29
+ const builtins = [["!", 0], ["*->", 2], [",", 2], ["->", 2], [".", 3], [":<", 2], [";", 2], ["<", 2], ["<meta-call>", 1], ["=", 2], ["=..", 2], ["=:=", 2], ["=<", 2], ["==", 2], ["=@=", 2], ["=\\=", 2], [">", 2], [">:<", 2], [">=", 2], ["?=", 2], ["@", 2], ["@<", 2], ["@=<", 2], ["@>", 2], ["@>=", 2], ["[|]", 2], ["\\+", 1], ["\\=", 2], ["\\==", 2], ["\\=@=", 2], ["abolish", 1], ["abolish", 2], ["abolish_all_tables", 0], ["abolish_module_tables", 1], ["abolish_monotonic_tables", 0], ["abolish_nonincremental_tables", 0], ["abolish_nonincremental_tables", 1], ["abolish_private_tables", 0], ["abolish_shared_tables", 0], ["abolish_table_subgoals", 1], ["abort", 0], ["absolute_file_name", 2], ["absolute_file_name", 3], ["access_file", 2], ["acyclic_term", 1], ["add_import_module", 3], ["answer_count_restraint", 0], ["append", 1], ["apply", 2], ["arg", 3], ["assert", 1], ["assert", 2], ["asserta", 1], ["asserta", 2], ["assertz", 1], ["assertz", 2], ["at_end_of_stream", 0], ["at_end_of_stream", 1], ["at_halt", 1], ["atom", 1], ["atom_chars", 2], ["atom_codes", 2], ["atom_concat", 3], ["atom_length", 2], ["atom_number", 2], ["atom_prefix", 2], ["atom_string", 2], ["atom_to_term", 3], ["atomic", 1], ["atomic_concat", 3], ["atomic_list_concat", 2], ["atomic_list_concat", 3], ["atomics_to_string", 2], ["atomics_to_string", 3], ["attach_packs", 0], ["attach_packs", 1], ["attach_packs", 2], ["attvar", 1], ["autoload", 1], ["autoload", 2], ["autoload_call", 1], ["autoload_path", 1], ["b_getval", 2], ["b_set_dict", 3], ["b_setval", 2], ["bagof", 3], ["between", 3], ["blob", 2], ["bounded_number", 3], ["break", 0], ["byte_count", 2], ["call", 1], ["call", 2], ["call", 3], ["call", 4], ["call", 5], ["call", 6], ["call", 7], ["call", 8], ["call_cleanup", 2], ["call_continuation", 1], ["call_dcg", 3], ["call_residue_vars", 2], ["call_shared_object_function", 2], ["call_with_depth_limit", 3], ["call_with_inference_limit", 3], ["callable", 1], ["cancel_halt", 1], ["catch", 3], ["catch_with_backtrace", 3], ["char_code", 2], ["char_conversion", 2], ["char_type", 2], ["character_count", 2], ["clause", 2], ["clause", 3], ["clause_property", 2], ["close", 1], ["close", 2], ["close_shared_object", 1], ["code_type", 2], ["collation_key", 2], ["compare", 3], ["compile_aux_clauses", 1], ["compile_predicates", 1], ["compiling", 0], ["compound", 1], ["compound_name_arguments", 3], ["compound_name_arity", 3], ["consult", 1], ["context_module", 1], ["copy_predicate_clauses", 2], ["copy_stream_data", 2], ["copy_stream_data", 3], ["copy_term", 2], ["copy_term", 3], ["copy_term", 4], ["copy_term_nat", 2], ["copy_term_nat", 4], ["create_prolog_flag", 3], ["current_arithmetic_function", 1], ["current_atom", 1], ["current_blob", 2], ["current_char_conversion", 2], ["current_engine", 1], ["current_flag", 1], ["current_format_predicate", 2], ["current_functor", 2], ["current_input", 1], ["current_key", 1], ["current_locale", 1], ["current_module", 1], ["current_op", 3], ["current_output", 1], ["current_predicate", 1], ["current_predicate", 2], ["current_prolog_flag", 2], ["current_resource", 2], ["current_signal", 3], ["current_table", 2], ["current_transaction", 1], ["current_trie", 1], ["cyclic_term", 1], ["date_time_stamp", 2], ["dcg_translate_rule", 2], ["dcg_translate_rule", 4], ["debug_reset_from_class", 0], ["default_module", 2], ["del_attr", 2], ["del_attrs", 1], ["del_dict", 4], ["delete_directory", 1], ["delete_file", 1], ["delete_import_module", 2], ["det", 1], ["deterministic", 1], ["dict_create", 3], ["dict_pairs", 3], ["dict_same_keys", 2], ["directory_files", 2], ["discontiguous", 1], ["divmod", 4], ["downcase_atom", 2], ["duplicate_term", 2], ["dwim_match", 2], ["dwim_match", 3], ["dwim_predicate", 2], ["dynamic", 1], ["dynamic", 2], ["engine_create", 3], ["engine_create", 4], ["engine_destroy", 1], ["engine_fetch", 1], ["engine_next", 2], ["engine_next_reified", 2], ["engine_post", 2], ["engine_post", 3], ["engine_self", 1], ["engine_yield", 1], ["ensure_loaded", 1], ["erase", 1], ["exists_directory", 1], ["exists_file", 1], ["exists_source", 1], ["exists_source", 2], ["expand_file_name", 2], ["expand_file_search_path", 2], ["expand_goal", 2], ["expand_goal", 4], ["expand_term", 2], ["expand_term", 4], ["export", 1], ["fail", 0], ["false", 0], ["fast_read", 2], ["fast_term_serialized", 2], ["fast_write", 2], ["file_base_name", 2], ["file_directory_name", 2], ["file_name_extension", 3], ["fill_buffer", 1], ["findall", 3], ["findall", 4], ["findnsols", 4], ["findnsols", 5], ["flag", 3], ["float", 1], ["float_class", 2], ["float_parts", 4], ["flush_output", 0], ["flush_output", 1], ["forall", 2], ["format", 1], ["format", 2], ["format", 3], ["format_predicate", 2], ["format_time", 3], ["format_time", 4], ["freeze", 2], ["frozen", 2], ["functor", 3], ["functor", 4], ["garbage_collect", 0], ["garbage_collect_atoms", 0], ["garbage_collect_clauses", 0], ["gc_file_search_cache", 1], ["get", 1], ["get", 2], ["get0", 1], ["get0", 2], ["get_attr", 3], ["get_attrs", 2], ["get_byte", 1], ["get_byte", 2], ["get_char", 1], ["get_char", 2], ["get_code", 1], ["get_code", 2], ["get_dict", 3], ["get_dict", 5], ["get_flag", 2], ["get_single_char", 1], ["get_string_code", 3], ["get_time", 1], ["getenv", 2], ["ground", 1], ["halt", 0], ["halt", 1], ["ignore", 1], ["import", 1], ["import_module", 2], ["initialization", 1], ["initialization", 2], ["initialize", 0], ["instance", 2], ["integer", 1], ["is", 2], ["is_absolute_file_name", 1], ["is_dict", 1], ["is_dict", 2], ["is_engine", 1], ["is_list", 1], ["is_message_queue", 1], ["is_most_general_term", 1], ["is_stream", 1], ["is_thread", 1], ["is_trie", 1], ["keysort", 2], ["known_licenses", 0], ["leash", 1], ["length", 2], ["license", 0], ["license", 1], ["license", 2], ["line_count", 2], ["line_position", 2], ["load_files", 1], ["load_files", 2], ["locale_create", 3], ["locale_destroy", 1], ["locale_property", 2], ["make_directory", 1], ["make_library_index", 1], ["make_library_index", 2], ["malloc_property", 1], ["memberchk", 2], ["message_queue_create", 1], ["message_queue_create", 2], ["message_queue_destroy", 1], ["message_queue_property", 2], ["message_queue_set", 2], ["message_to_string", 2], ["meta_predicate", 1], ["mode", 1], ["module", 1], ["module_property", 2], ["module_transparent", 1], ["msort", 2], ["multifile", 1], ["mutex_create", 1], ["mutex_create", 2], ["mutex_destroy", 1], ["mutex_lock", 1], ["mutex_property", 2], ["mutex_statistics", 0], ["mutex_trylock", 1], ["mutex_unlock", 1], ["mutex_unlock_all", 0], ["name", 2], ["nb_current", 2], ["nb_delete", 1], ["nb_getval", 2], ["nb_link_dict", 3], ["nb_linkarg", 3], ["nb_linkval", 2], ["nb_set_dict", 3], ["nb_setarg", 3], ["nb_setval", 2], ["nl", 0], ["nl", 1], ["non_terminal", 1], ["nonground", 2], ["nonvar", 1], ["noprofile", 1], ["noprotocol", 0], ["normalize_space", 2], ["not", 1], ["not_exists", 1], ["notrace", 0], ["notrace", 1], ["nth_clause", 3], ["nth_integer_root_and_remainder", 4], ["number", 1], ["number_chars", 2], ["number_codes", 2], ["number_string", 2], ["numbervars", 3], ["numbervars", 4], ["on_signal", 3], ["once", 1], ["op", 3], ["open", 3], ["open", 4], ["open_null_stream", 1], ["open_resource", 2], ["open_resource", 3], ["open_shared_object", 2], ["open_shared_object", 3], ["open_string", 2], ["pack_attach", 2], ["peek_byte", 1], ["peek_byte", 2], ["peek_char", 1], ["peek_char", 2], ["peek_code", 1], ["peek_code", 2], ["peek_string", 3], ["phrase", 2], ["phrase", 3], ["plus", 3], ["predicate_property", 2], ["print", 1], ["print", 2], ["print_message", 2], ["print_message_lines", 3], ["print_toplevel_variables", 0], ["profiler", 2], ["prolog", 0], ["prolog_alert_signal", 2], ["prolog_choice_attribute", 3], ["prolog_current_choice", 1], ["prolog_current_frame", 1], ["prolog_cut_to", 1], ["prolog_debug", 1], ["prolog_frame_attribute", 3], ["prolog_interrupt", 0], ["prolog_listen", 2], ["prolog_listen", 3], ["prolog_load_context", 2], ["prolog_nodebug", 1], ["prolog_skip_level", 2], ["prolog_stack_property", 2], ["prolog_to_os_filename", 2], ["prolog_unlisten", 2], ["prompt", 2], ["prompt1", 1], ["protocol", 1], ["protocola", 1], ["protocolling", 1], ["public", 1], ["put", 1], ["put", 2], ["put_attr", 3], ["put_attrs", 2], ["put_byte", 1], ["put_byte", 2], ["put_char", 1], ["put_char", 2], ["put_code", 1], ["put_code", 2], ["put_dict", 3], ["put_dict", 4], ["qcompile", 1], ["qcompile", 2], ["radial_restraint", 0], ["random_property", 1], ["rational", 1], ["rational", 3], ["read", 1], ["read", 2], ["read_clause", 3], ["read_link", 3], ["read_pending_chars", 3], ["read_pending_codes", 3], ["read_string", 3], ["read_string", 5], ["read_term", 2], ["read_term", 3], ["read_term_from_atom", 3], ["read_term_with_history", 2], ["recorda", 2], ["recorda", 3], ["recorded", 2], ["recorded", 3], ["recordz", 2], ["recordz", 3], ["redefine_system_predicate", 1], ["reexport", 1], ["reexport", 2], ["register_iri_scheme", 3], ["reload_library_index", 0], ["rename_file", 2], ["repeat", 0], ["require", 1], ["reset", 3], ["reset_profiler", 0], ["residual_goals", 1], ["retract", 1], ["retractall", 1], ["rule", 2], ["rule", 3], ["same_file", 2], ["same_term", 2], ["see", 1], ["seeing", 1], ["seek", 4], ["seen", 0], ["select_dict", 3], ["set_end_of_stream", 1], ["set_flag", 2], ["set_input", 1], ["set_locale", 1], ["set_malloc", 1], ["set_module", 1], ["set_output", 1], ["set_prolog_IO", 3], ["set_prolog_flag", 2], ["set_prolog_gc_thread", 1], ["set_prolog_stack", 2], ["set_random", 1], ["set_stream", 2], ["set_stream_position", 2], ["set_system_IO", 3], ["set_thread", 2], ["setarg", 3], ["setenv", 2], ["setlocale", 3], ["setof", 3], ["setup_call_catcher_cleanup", 4], ["setup_call_cleanup", 3], ["shell", 1], ["shell", 2], ["shift", 1], ["shift_for_copy", 1], ["sig_atomic", 1], ["sig_block", 1], ["sig_pending", 1], ["sig_remove", 2], ["sig_unblock", 1], ["size_abstract_term", 3], ["size_file", 2], ["skip", 1], ["skip", 2], ["sleep", 1], ["snapshot", 1], ["sort", 2], ["sort", 4], ["source_file", 1], ["source_file", 2], ["source_file_property", 2], ["source_location", 2], ["split_string", 4], ["stamp_date_time", 3], ["start_abstract_tabling", 3], ["start_moded_tabling", 5], ["start_subsumptive_tabling", 3], ["start_tabling", 3], ["statistics", 2], ["stream_pair", 3], ["stream_position_data", 3], ["stream_property", 2], ["string", 1], ["string_bytes", 3], ["string_chars", 2], ["string_code", 3], ["string_codes", 2], ["string_concat", 3], ["string_length", 2], ["string_lower", 2], ["string_upper", 2], ["strip_module", 3], ["style_check", 1], ["sub_atom", 5], ["sub_atom_icasechk", 3], ["sub_string", 5], ["subsumes_term", 2], ["succ", 2], ["tab", 1], ["tab", 2], ["table", 1], ["tabled_call", 1], ["tell", 1], ["telling", 1], ["term_attvars", 2], ["term_expansion", 2], ["term_hash", 2], ["term_hash", 4], ["term_singletons", 2], ["term_string", 2], ["term_string", 3], ["term_to_atom", 2], ["term_variables", 2], ["term_variables", 3], ["text_to_string", 2], ["thread_affinity", 3], ["thread_create", 2], ["thread_create", 3], ["thread_detach", 1], ["thread_exit", 1], ["thread_get_message", 1], ["thread_get_message", 2], ["thread_get_message", 3], ["thread_idle", 2], ["thread_initialization", 1], ["thread_join", 1], ["thread_join", 2], ["thread_local", 1], ["thread_peek_message", 1], ["thread_peek_message", 2], ["thread_property", 2], ["thread_self", 1], ["thread_send_message", 2], ["thread_send_message", 3], ["thread_setconcurrency", 2], ["thread_signal", 2], ["thread_statistics", 3], ["thread_update", 2], ["thread_wait", 2], ["throw", 1], ["time_file", 2], ["tmp_file", 2], ["tmp_file_stream", 3], ["tnot", 1], ["told", 0], ["trace", 0], ["tracing", 0], ["transaction", 1], ["transaction", 2], ["transaction", 3], ["transaction_updates", 1], ["trie_delete", 3], ["trie_destroy", 1], ["trie_gen", 2], ["trie_gen", 3], ["trie_insert", 2], ["trie_insert", 3], ["trie_insert", 4], ["trie_lookup", 3], ["trie_new", 1], ["trie_property", 2], ["trie_term", 2], ["trie_update", 3], ["trim_heap", 0], ["trim_stacks", 0], ["true", 0], ["tty_get_capability", 3], ["tty_goto", 2], ["tty_put", 2], ["tty_size", 2], ["ttyflush", 0], ["undefined", 0], ["undo", 1], ["unifiable", 3], ["unify_with_occurs_check", 2], ["unload_file", 1], ["unsetenv", 1], ["untable", 1], ["unwrap_predicate", 2], ["upcase_atom", 2], ["use_foreign_library", 1], ["use_foreign_library", 2], ["use_module", 1], ["use_module", 2], ["var", 1], ["var_number", 2], ["var_property", 2], ["variant_hash", 2], ["variant_sha1", 2], ["verbose_expansion", 1], ["version", 0], ["version", 1], ["visible", 1], ["volatile", 1], ["wait_for_input", 3], ["wildcard_match", 2], ["wildcard_match", 3], ["win_rename_file", 2], ["with_mutex", 2], ["with_output_to", 2], ["with_tty_raw", 1], ["working_directory", 2], ["write", 1], ["write", 2], ["write_canonical", 1], ["write_canonical", 2], ["write_length", 3], ["write_term", 2], ["write_term", 3], ["writeln", 1], ["writeln", 2], ["writeq", 1], ["writeq", 2], ["zip_clone", 2], ["zip_close_", 2], ["zip_file_info_", 3], ["zip_lock", 1], ["zip_open_stream", 3], ["zip_unlock", 1], ["zipper_goto", 2], ["zipper_open_current", 3], ["zipper_open_new_file_in_zip", 4]];
30
+
31
+ const controlNames = new Set(control);
32
+ const directiveNames = new Set(directives);
33
+ const operatorNames = new Set(operators);
34
+ const builtinNames = new Set(builtins.map(([name]) => name));
35
+ const necks = new Set([":-", "-->", "?-"]);
36
+
37
+ // The character classes of SWI-Prolog's reader (manual section "Unicode Prolog source"):
38
+ // identifiers are ID_Start ID_Continue*, variables start with an uppercase letter or `_`,
39
+ // non-ASCII symbols and punctuation glue like the ASCII symbol characters.
40
+ const symbolChar = /^(?:[#$&*+\-./:<=>?@^~\\]|(?![\0-\x7f])[\p{S}\p{P}])$/u;
41
+ const nameStart = /^[\p{ID_Start}_]$/u;
42
+ const nameChar = /^\p{ID_Continue}$/u;
43
+ const variableStart = /^[\p{Lu}\p{Lt}_]$/u;
44
+ const layout = /^\s$/u;
45
+
46
+ const chr = (input, offset) => {
47
+ const code = input.peek(offset);
48
+ if (code < 0) return ""
49
+ if (code >= 0xd800 && code < 0xdc00) {
50
+ const low = input.peek(offset + 1);
51
+ if (low >= 0xdc00 && low < 0xe000) return String.fromCharCode(code, low)
52
+ }
53
+ return String.fromCharCode(code)
54
+ };
55
+
56
+ // The character before `(` or `{`: `f(` is a compound and `t{` a dict, `f (` and `t {`
57
+ // are not.
58
+ const before = input => String.fromCharCode(input.peek(-1));
59
+ const endsTag = c => c == "'" || nameChar.test(c);
60
+
61
+ function scan(input, text, test) {
62
+ let c;
63
+ while ((c = chr(input, text.length)) && test.test(c)) text += c;
64
+ return text
65
+ }
66
+
67
+ function nameKind(text) {
68
+ if (controlNames.has(text)) return Control
69
+ if (directiveNames.has(text)) return DirectiveName
70
+ if (operatorNames.has(text)) return Operator
71
+ if (builtinNames.has(text)) return Builtin
72
+ return Atom
73
+ }
74
+
75
+ function symbolKind(text) {
76
+ if (necks.has(text)) return Neck
77
+ if (text == ":") return Colon
78
+ if (controlNames.has(text)) return Control
79
+ return SymbolAtom
80
+ }
81
+
82
+ // SWI-Prolog nests block comments.
83
+ function blockComment(input) {
84
+ let depth = 0;
85
+ for (let i = 0; ; i++) {
86
+ const c = input.peek(i);
87
+ if (c < 0) return input.acceptToken(BlockComment, i)
88
+ if (c == 47 /* / */ && input.peek(i + 1) == 42 /* * */) { depth++; i++; }
89
+ else if (c == 42 && input.peek(i + 1) == 47) {
90
+ i++;
91
+ if (--depth == 0) return input.acceptToken(BlockComment, i + 1)
92
+ }
93
+ }
94
+ }
95
+
96
+ function quasiQuotation(input) {
97
+ for (let i = 2; ; i++) {
98
+ const c = input.peek(i);
99
+ if (c < 0) return input.acceptToken(QuasiQuotation, i)
100
+ if (c == 124 /* | */ && input.peek(i + 1) == 125 /* } */) return input.acceptToken(QuasiQuotation, i + 2)
101
+ }
102
+ }
103
+
104
+ const prologTokens = new lr.ExternalTokenizer((input, stack) => {
105
+ const next = input.next;
106
+ if (next == 47 && input.peek(1) == 42) return blockComment(input)
107
+ if (next == 40 /* ( */) {
108
+ const c = before(input);
109
+ if ((endsTag(c) || symbolChar.test(c)) && stack.canShift(CallOpen)) input.acceptToken(CallOpen, 1);
110
+ return
111
+ }
112
+ if (next == 123 /* { */) {
113
+ if (input.peek(1) == 124) return quasiQuotation(input)
114
+ if (endsTag(before(input)) && stack.canShift(DictOpen)) input.acceptToken(DictOpen, 1);
115
+ return
116
+ }
117
+ const first = chr(input, 0);
118
+ if (symbolChar.test(first)) {
119
+ const text = scan(input, "", symbolChar);
120
+ if (text == ".") {
121
+ const after = chr(input, 1);
122
+ if (!after || after == "%" || layout.test(after)) return input.acceptToken(End, 1)
123
+ }
124
+ return input.acceptToken(symbolKind(text), text.length)
125
+ }
126
+ if (nameStart.test(first)) {
127
+ const text = scan(input, first, nameChar);
128
+ if (text == "_") return input.acceptToken(Anonymous, 1)
129
+ return input.acceptToken(variableStart.test(first) ? Variable : nameKind(text), text.length)
130
+ }
131
+ }, {contextual: true});
132
+
133
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
134
+ const parser = lr.LRParser.deserialize({
135
+ version: 14,
136
+ states: "(|Q]QROOOOQP'#Da'#DaO!sQRO'#DbOOQP'#Db'#DbO&QQRO'#CzO&XQRO'#C}O&`QRO'#DPO(TQRO'#DVOOQP'#Dc'#DcO([QRO'#CnOOQP'#De'#DeO(cQRO'#DdO(fQRO'#DdO(pQRO'#DWOOQP'#D_'#D_OOQP'#DX'#DXQ]QROOO(xQRO,59lO)PQRO'#CqOOQP'#DZ'#DZO*yQRO,59fO+QQRO'#CpOOQP,59f,59fOOQP'#D`'#D`O+VQRO,59iOOQP,59i,59iO+^QRO,59kOOQP,59k,59kO`QRO,5:OOOQP'#DY'#DYO+eQRO,59YOOQP,59Y,59YO+lQRO'#CsO+sQRO,5:OO+sQRO,5:OO+}QRO,59pOOQP,59r,59rOOQP-E7V-E7VO,UQRO1G/WOOQP1G/W1G/WOOQP-E7X-E7XOOQP1G/Q1G/QOOQP,59[,59[OOQP1G/T1G/TOOQP1G/V1G/VO,]QRO'#DVO,dQRO1G/jO,gQRO1G/jOOQP-E7W-E7WOOQP1G.t1G.tO,qQRO,59_OOQP,59_,59_O,gQRO1G/jO,xQRO1G/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!VsS!Y!O!PR!^!ZQdSQhTQjUQvaYxdhjv!SR!SpT_O`dcSTUadhjpv!SmmXZ[nqrs!O!P!U!V!Y!Z!^SVO`!QbSTUXZ[adhjnpqrsv!O!P!S!U!V!Y!Z!^R}lT]O`S[O`R!Pl",
139
+ nodeNames: "⚠ BlockComment End Neck Colon Control SymbolAtom Atom Operator DirectiveName Builtin Variable Anonymous QuasiQuotation CallOpen DictOpen LineComment Program Directive QuotedAtom Compound Functor ) ArgList Number String BackquoteString ! ] [ List } { Curly ( Parenthesized Dict , ; | Rule HeadFunctor Fact",
140
+ maxTerm: 55,
141
+ nodeProps: [
142
+ ["closedBy", -2,14,34,")",-2,15,32,"}",29,"]"],
143
+ ["openedBy", 22,"(",28,"[",31,"{"]
144
+ ],
145
+ skippedNodes: [0,1,16],
146
+ repeatNodeCount: 3,
147
+ tokenData: ";P~RqXY#YYZ#Y[]#Y]^#Ypq#Yqr$Zrs$`uv&Pwx&hxy(Xyz(^|}(c!Q!R(h!R!S5P!S!T7a!T!U8O!U![5k!]!^8p!}#O8u#P#Q8z#S#T9P#j#k#Y#o#p:p#p#q:u#q#r:z$f$g#Y#BY#BZ#Y$IS$I_#Y$I|$I}#Y$I}$JO#Y$JT$JU#Y$KV$KW#Y&FU&FV#Y~#_^!Q~XY#YYZ#Y[]#Y]^#Ypq#Y#j#k#Y$f$g#Y#BY#BZ#Y$IS$I_#Y$I|$I}#Y$I}$JO#Y$JT$JU#Y$KV$KW#Y&FU&FV#Y~$`Ok~~$cVOr$`rs$xs#O$`#O#P%Q#P;'S$`;'S;=`%y<%lO$`~$}Pi~rs$`~%TRO;'S$`;'S;=`%^;=`O$`~%aWOr$`rs$xs#O$`#O#P%Q#P;'S$`;'S;=`%y;=`<%l$`<%lO$`~%|P;=`<%l$`~&US`~OY&PZ;'S&P;'S;=`&b<%lO&P~&eP;=`<%l&P~&kVOw&hwx'Qx#O&h#O#P'Y#P;'S&h;'S;=`(R<%lO&h~'VPc~wx&h~']RO;'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]^3fpq3f!Q!Y3Z~3{R!Q![4U!c!i4U#T#Z4U~4ZSh~!Q![4U!c!i4U#R#S4g#T#Z4U~4jVXY4gYZ4g]^4gpq4g!Q![4U!c!i4U#T#Z4U~5UVh~pq)`!O!P*Q!Q![5k!g!h*l#R#S+u#X#Y*l#f#g,X~5pWh~pq)`wx6Y!O!P*Q!Q![)f!g!h*l#R#S+u#X#Y*l#f#g,X~6]R!Q![6f!c!}6f#T#o6f~6kSh~!Q![6f!c!}6f#R#S6w#T#o6f~6zVXY6wYZ6w]^6wpq6w!Q![6f!c!}6f#T#o6f~7fWh~pq)`wx6Y!O!P*Q!Q![5k!g!h*l#R#S+u#X#Y*l#f#g,X~8TXh~pq)`wx6Y!O!P*Q!Q!X5k!X![)f!g!h*l#R#S+u#X#Y*l#f#g,X~8uOv~~8zOm~~9POl~~9SVO#O9P#O#P9i#P#S9P#S#T:b#T;'S9P;'S;=`:j<%lO9P~9lRO;'S9P;'S;=`9u;=`O9P~9xWO#O9P#O#P9i#P#S9P#S#T:b#T;'S9P;'S;=`:j;=`<%l9P<%lO9P~:gPj~#S#T9P~:mP;=`<%l9P~:uOp~~:zOw~~;POo~",
148
+ tokenizers: [prologTokens, 0],
149
+ topRules: {"Program":[0,17]},
150
+ tokenPrec: 0
151
+ });
152
+
153
+ const prologHighlighting = highlight.styleTags({
154
+ Variable: highlight.tags.variableName,
155
+ Anonymous: highlight.tags.special(highlight.tags.variableName),
156
+ "Atom QuotedAtom": highlight.tags.atom,
157
+ Number: highlight.tags.number,
158
+ String: highlight.tags.string,
159
+ "BackquoteString QuasiQuotation": highlight.tags.special(highlight.tags.string),
160
+ LineComment: highlight.tags.lineComment,
161
+ BlockComment: highlight.tags.blockComment,
162
+ Neck: highlight.tags.definitionOperator,
163
+ End: highlight.tags.punctuation,
164
+ Operator: highlight.tags.operatorKeyword,
165
+ SymbolAtom: highlight.tags.operator,
166
+ 'Control "!" ";"': highlight.tags.controlKeyword,
167
+ DirectiveName: highlight.tags.definitionKeyword,
168
+ Builtin: highlight.tags.standard(highlight.tags.variableName),
169
+ "HeadFunctor/Atom HeadFunctor/QuotedAtom HeadFunctor/Operator HeadFunctor/Control HeadFunctor/DirectiveName HeadFunctor/Builtin HeadFunctor/SymbolAtom": highlight.tags.definition(highlight.tags.function(highlight.tags.variableName)),
170
+ "Functor/Atom Functor/QuotedAtom Functor/SymbolAtom": highlight.tags.function(highlight.tags.variableName),
171
+ "Functor/Builtin": highlight.tags.standard(highlight.tags.function(highlight.tags.variableName)),
172
+ '"(" ")" CallOpen': highlight.tags.paren,
173
+ '"[" "]"': highlight.tags.squareBracket,
174
+ '"{" "}" DictOpen': highlight.tags.brace,
175
+ '"," "|" Colon': highlight.tags.separator,
176
+ });
177
+
178
+ // The library predicates that programs use most, as [library, name, arities].
179
+ // `tables.ts` only has SWI-Prolog's system predicates. Most of these load on first use;
180
+ // clpfd, dcg/basics, readutil and plunit need a `use_module`. Completion offers them, and the
181
+ // tokenizer still reads them as plain atoms.
182
+ const library = [
183
+ ["lists", "append", [2, 3]],
184
+ ["lists", "member", [2]],
185
+ ["lists", "memberchk", [2]],
186
+ ["lists", "delete", [3]],
187
+ ["lists", "exclude", [3]],
188
+ ["lists", "flatten", [2]],
189
+ ["lists", "intersection", [3]],
190
+ ["lists", "last", [2]],
191
+ ["lists", "list_to_set", [2]],
192
+ ["lists", "max_list", [2]],
193
+ ["lists", "max_member", [2, 3]],
194
+ ["lists", "min_list", [2]],
195
+ ["lists", "min_member", [2, 3]],
196
+ ["lists", "nextto", [3]],
197
+ ["lists", "nth0", [3, 4]],
198
+ ["lists", "nth1", [3, 4]],
199
+ ["lists", "numlist", [3]],
200
+ ["lists", "permutation", [2]],
201
+ ["lists", "proper_length", [2]],
202
+ ["lists", "reverse", [2]],
203
+ ["lists", "same_length", [2]],
204
+ ["lists", "select", [3, 4]],
205
+ ["lists", "selectchk", [3]],
206
+ ["lists", "subtract", [3]],
207
+ ["lists", "sum_list", [2]],
208
+ ["lists", "sumlist", [2]],
209
+ ["lists", "union", [3]],
210
+ ["pairs", "pairs_keys_values", [3]],
211
+ ["lists", "clumped", [2]],
212
+ ["lists", "subseq", [3]],
213
+ ["lists", "predsort", [3]],
214
+ ["apply", "maplist", [2, 3, 4, 5, 6, 7]],
215
+ ["apply", "foldl", [4, 5, 6, 7]],
216
+ ["apply", "include", [3]],
217
+ ["apply", "partition", [4, 6]],
218
+ ["apply", "convlist", [3]],
219
+ ["aggregate", "aggregate_all", [3, 4]],
220
+ ["aggregate", "aggregate", [3, 4]],
221
+ ["aggregate", "foreach", [2]],
222
+ ["pairs", "pairs_keys", [2]],
223
+ ["pairs", "pairs_values", [2]],
224
+ ["pairs", "transpose_pairs", [2]],
225
+ ["pairs", "map_list_to_pairs", [3]],
226
+ ["error", "must_be", [2]],
227
+ ["error", "is_of_type", [2]],
228
+ ["error", "domain_error", [2]],
229
+ ["error", "type_error", [2]],
230
+ ["error", "instantiation_error", [1]],
231
+ ["error", "existence_error", [2]],
232
+ ["dcg/basics", "digits", [3]],
233
+ ["dcg/basics", "digit", [3]],
234
+ ["dcg/basics", "integer", [3]],
235
+ ["dcg/basics", "blanks", [2]],
236
+ ["dcg/basics", "string_without", [4]],
237
+ ["dcg/basics", "whites", [2]],
238
+ ["clpfd", "label", [1]],
239
+ ["clpfd", "labeling", [2]],
240
+ ["clpfd", "all_different", [1]],
241
+ ["clpfd", "all_distinct", [1]],
242
+ ["clpfd", "sum", [3]],
243
+ ["clpfd", "tuples_in", [2]],
244
+ ["clpfd", "transpose", [2]],
245
+ ["readutil", "read_term_from_atom", [3]],
246
+ ["readutil", "read_line_to_string", [2]],
247
+ ["readutil", "read_line_to_codes", [2]],
248
+ ["option", "option", [2, 3]],
249
+ ["random", "random_between", [3]],
250
+ ["random", "random_member", [2]],
251
+ ["random", "random_permutation", [2]],
252
+ ["random", "random", [1]],
253
+ ["ordsets", "list_to_ord_set", [2]],
254
+ ["ordsets", "ord_union", [3]],
255
+ ["ordsets", "ord_subtract", [3]],
256
+ ["ordsets", "ord_memberchk", [2]],
257
+ ["ordsets", "ord_insert", [3]],
258
+ ["assoc", "list_to_assoc", [2]],
259
+ ["assoc", "put_assoc", [4]],
260
+ ["assoc", "get_assoc", [3]],
261
+ ["assoc", "empty_assoc", [1]],
262
+ ["assoc", "assoc_to_list", [2]],
263
+ ["assoc", "assoc_to_keys", [2]],
264
+ ["assoc", "assoc_to_values", [2]],
265
+ ["plunit", "begin_tests", [1, 2]],
266
+ ["plunit", "end_tests", [1]],
267
+ ["plunit", "run_tests", [0, 1]],
268
+ ];
269
+
270
+ const clauses$1 = new Set(["Directive", "Rule", "Fact"]);
271
+ const dontComplete = new Set([
272
+ "LineComment", "BlockComment", "QuotedAtom", "String", "BackquoteString", "QuasiQuotation", "Number",
273
+ ]);
274
+ /// Snippets for whole clauses, offered where a new clause starts.
275
+ const clauseSnippets = [
276
+ autocomplete.snippetCompletion("${name}(${Args}) :-\n\t${body}.", { label: "rule", detail: "Head :- Body.", type: "keyword" }),
277
+ autocomplete.snippetCompletion("${name}(${args}).", { label: "fact", detail: "name(args).", type: "keyword" }),
278
+ autocomplete.snippetCompletion("${name} -->\n\t${body}.", { label: "dcg", detail: "Head --> Body.", type: "keyword" }),
279
+ autocomplete.snippetCompletion(":- use_module(library(${lists})).", { label: "use_module", detail: "directive", type: "keyword" }),
280
+ autocomplete.snippetCompletion(":- initialization(${main}).", { label: "initialization", detail: "directive", type: "keyword" }),
281
+ ];
282
+ /// Snippets for goals, offered inside a clause.
283
+ const goalSnippets = [
284
+ autocomplete.snippetCompletion("( ${Condition}\n-> ${Then}\n; ${Else}\n)", { label: "if", detail: "( -> ; )", type: "keyword" }),
285
+ autocomplete.snippetCompletion("( ${Condition}\n-> ${Then}\n)", { label: "if", detail: "( -> )", type: "keyword" }),
286
+ autocomplete.snippetCompletion("findall(${Template}, ${Goal}, ${List})", { label: "findall", detail: "snippet", type: "keyword" }),
287
+ autocomplete.snippetCompletion("forall(${Condition}, ${Action})", { label: "forall", detail: "snippet", type: "keyword" }),
288
+ autocomplete.snippetCompletion("format(\"${~w~n}\", [${Args}])", { label: "format", detail: "snippet", type: "keyword" }),
289
+ autocomplete.snippetCompletion("maplist(${Goal}, ${List})", { label: "maplist", detail: "snippet", type: "keyword" }),
290
+ autocomplete.snippetCompletion("catch(${Goal}, ${Error}, ${Recovery})", { label: "catch", detail: "snippet", type: "keyword" }),
291
+ ];
292
+ // Built-ins with symbol names (`=..`, `\+`) and internal ones (`$...`, `<meta-call>`) are
293
+ // left out: completion starts on a word.
294
+ const word = /^[a-z][A-Za-z0-9_]*$/;
295
+ function predicateOptions() {
296
+ const seen = new Set(), options = [];
297
+ const add = (label, arity, info) => {
298
+ const key = `${label}/${arity}`;
299
+ if (!word.test(label) || seen.has(key))
300
+ return;
301
+ seen.add(key);
302
+ options.push(Object.assign({ label, detail: `/${arity}`, type: "function" }, (info ? { info } : {})));
303
+ };
304
+ for (const [name, arity] of builtins)
305
+ add(name, arity);
306
+ for (const [lib, name, arities] of library)
307
+ for (const arity of arities)
308
+ add(name, arity, `library(${lib})`);
309
+ for (const name of operators)
310
+ if (!seen.has(`${name}/2`))
311
+ options.push({ label: name, type: "keyword" });
312
+ return options;
313
+ }
314
+ /// The built-in and library predicates, with their arity in `detail`, and the
315
+ /// alphanumeric operators such as `is` and `mod`.
316
+ const globalOptions = predicateOptions();
317
+ // Arguments are the items between the top-level commas of an ArgList.
318
+ function arity(argList) {
319
+ if (!argList || argList.name != "ArgList")
320
+ return 0;
321
+ let count = 0, empty = true;
322
+ for (let child = argList.firstChild; child; child = child.nextSibling) {
323
+ if (child.name == ",")
324
+ count++;
325
+ else if (child.name != "CallOpen" && child.name != ")")
326
+ empty = false;
327
+ }
328
+ return empty && count == 0 ? 0 : count + 1;
329
+ }
330
+ // Every predicate and DCG nonterminal defined in the file, as `name/N` or `name//N`.
331
+ function definedPredicates(doc, top, skip) {
332
+ const seen = new Set(), options = [];
333
+ for (let clause = top.firstChild; clause; clause = clause.nextSibling) {
334
+ const head = clause.getChild("HeadFunctor");
335
+ if (!head || head.from == skip)
336
+ continue;
337
+ const neck = clause.getChild("Neck");
338
+ const dcg = neck != null && doc.sliceString(neck.from, neck.to) == "-->";
339
+ const label = doc.sliceString(head.from, head.to);
340
+ const detail = `${dcg ? "//" : "/"}${arity(head.nextSibling)}`;
341
+ if (seen.has(label + detail))
342
+ continue;
343
+ seen.add(label + detail);
344
+ options.push({ label, detail, type: "function", boost: 1 });
345
+ }
346
+ return options;
347
+ }
348
+ // Every named variable in the clause. A variable is local to its clause in Prolog.
349
+ function clauseVariables(doc, clause, skip) {
350
+ const seen = new Set(), options = [];
351
+ clause.cursor().iterate(node => {
352
+ if (node.name != "Variable" || node.from == skip)
353
+ return;
354
+ const name = doc.sliceString(node.from, node.to);
355
+ if (!seen.has(name)) {
356
+ seen.add(name);
357
+ options.push({ label: name, type: "variable", boost: 2 });
358
+ }
359
+ });
360
+ return options;
361
+ }
362
+ /// Completion for SWI-Prolog. A word that starts with an uppercase letter or `_` gets the
363
+ /// variables of the current clause. Any other word gets the predicates defined in the
364
+ /// file, the built-ins and snippets: clause snippets where a clause starts, and goal
365
+ /// snippets inside one. Nothing is offered in comments, strings or quoted atoms.
366
+ function prologCompletion(context) {
367
+ var _a;
368
+ const tree = language.syntaxTree(context.state);
369
+ const inner = tree.resolveInner(context.pos, -1);
370
+ for (let node = inner; node; node = node.parent)
371
+ if (dontComplete.has(node.name))
372
+ return null;
373
+ const match = context.matchBefore(/[\p{L}_][\p{L}\p{N}_]*/u);
374
+ if (!match && !context.explicit)
375
+ return null;
376
+ const from = match ? match.from : context.pos;
377
+ // `0'c` is a character code, and `f(` after a word starts its arguments.
378
+ if (from > 0 && /[0-9']/.test(context.state.sliceDoc(from - 1, from)))
379
+ return null;
380
+ let clause = inner;
381
+ while (clause && !clauses$1.has(clause.name))
382
+ clause = clause.parent;
383
+ const doc = context.state.doc;
384
+ const text = match ? match.text : "";
385
+ const variablesOnly = /^[\p{Lu}\p{Lt}_]/u.test(text);
386
+ const variables = clause ? clauseVariables(doc, clause, from) : [];
387
+ if (variablesOnly)
388
+ return variables.length ? { from, options: variables, validFor: /^[\p{L}\p{N}_]*$/u } : null;
389
+ const ended = ((_a = clause === null || clause === void 0 ? void 0 : clause.lastChild) === null || _a === void 0 ? void 0 : _a.name) == "End" && clause.lastChild.to <= from;
390
+ const atClauseStart = !clause || ended || clause.from == from;
391
+ const options = [
392
+ ...definedPredicates(doc, tree.topNode, from),
393
+ ...(atClauseStart ? clauseSnippets : [...goalSnippets, ...globalOptions]),
394
+ ...(context.explicit && !atClauseStart ? variables : []),
395
+ ];
396
+ return { from, options, validFor: /^[\p{L}\p{N}_]*$/u };
397
+ }
398
+
399
+ const clauses = "Directive Rule Fact";
400
+ // Folds a clause from the end of its first line's construct (the neck, or the head of a
401
+ // fact) to its end token.
402
+ function foldClause(node) {
403
+ var _a;
404
+ const end = node.lastChild, from = ((_a = node.getChild("Neck")) !== null && _a !== void 0 ? _a : node.firstChild).to;
405
+ return (end === null || end === void 0 ? void 0 : end.name) == "End" && end.from > from ? { from, to: end.from } : null;
406
+ }
407
+ // SWI-Prolog's layout of if-then-else: `->`, `*->`, `;`, `|` and `)` line up with the
408
+ // opening parenthesis, the goals one unit further in.
409
+ function parenthesized(cx) {
410
+ const column = cx.column(cx.node.from);
411
+ return /^\s*(->|\*->|;|\||\))/.test(cx.textAfter) ? column : column + cx.unit;
412
+ }
413
+ const prologLanguage = language.LRLanguage.define({
414
+ name: "prolog",
415
+ parser: parser.configure({
416
+ props: [
417
+ prologHighlighting,
418
+ language.indentNodeProp.add({
419
+ [clauses]: language.continuedIndent(),
420
+ Parenthesized: parenthesized,
421
+ ArgList: language.delimitedIndent({ closing: ")" }),
422
+ List: language.delimitedIndent({ closing: "]" }),
423
+ "Curly Dict": language.delimitedIndent({ closing: "}" }),
424
+ }),
425
+ language.foldNodeProp.add({
426
+ [clauses]: foldClause,
427
+ BlockComment: node => ({ from: node.from + 2, to: node.to - 2 }),
428
+ }),
429
+ ],
430
+ }),
431
+ languageData: {
432
+ commentTokens: { line: "%", block: { open: "/*", close: "*/" } },
433
+ closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] },
434
+ },
435
+ });
436
+ /// SWI-Prolog language support for CodeMirror, with completion of built-in predicates,
437
+ /// snippets, and the predicates and variables defined in the file.
438
+ function prolog() {
439
+ return new language.LanguageSupport(prologLanguage, prologLanguage.data.of({ autocomplete: prologCompletion }));
440
+ }
441
+
442
+ exports.clauseSnippets = clauseSnippets;
443
+ exports.globalOptions = globalOptions;
444
+ exports.goalSnippets = goalSnippets;
445
+ exports.prolog = prolog;
446
+ exports.prologCompletion = prologCompletion;
447
+ exports.prologLanguage = prologLanguage;
@@ -0,0 +1,4 @@
1
+ import { LRLanguage, LanguageSupport } from "@codemirror/language";
2
+ export declare const prologLanguage: LRLanguage;
3
+ export { prologCompletion, clauseSnippets, goalSnippets, globalOptions } from "./complete";
4
+ export declare function prolog(): LanguageSupport;
package/dist/index.js ADDED
@@ -0,0 +1,440 @@
1
+ import { ExternalTokenizer, LRParser } from '@lezer/lr';
2
+ import { styleTags, tags } from '@lezer/highlight';
3
+ import { syntaxTree, LRLanguage, indentNodeProp, delimitedIndent, continuedIndent, foldNodeProp, LanguageSupport } from '@codemirror/language';
4
+ import { snippetCompletion } from '@codemirror/autocomplete';
5
+
6
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
7
+ const BlockComment = 1,
8
+ End = 2,
9
+ Neck = 3,
10
+ Colon = 4,
11
+ Control = 5,
12
+ SymbolAtom = 6,
13
+ Atom = 7,
14
+ Operator = 8,
15
+ DirectiveName = 9,
16
+ Builtin = 10,
17
+ Variable = 11,
18
+ Anonymous = 12,
19
+ QuasiQuotation = 13,
20
+ CallOpen = 14,
21
+ DictOpen = 15;
22
+
23
+ // Generated by gen/tables.mjs from spec/prolog/*.json (SWI-Prolog version 10.0.2). Do not edit.
24
+ const operators = ["as", "discontiguous", "div", "dynamic", "initialization", "is", "meta_predicate", "mod", "module_transparent", "multifile", "public", "rdiv", "rem", "table", "thread_initialization", "thread_local", "volatile", "xor"];
25
+ const control = ["!", ",", ";", "->", "*->", "\\+", "call", "catch", "throw", "true", "fail", "false"];
26
+ const directives = ["discontiguous", "dynamic", "ensure_loaded", "initialization", "license", "meta_predicate", "module", "module_transparent", "multifile", "op", "public", "reexport", "set_prolog_flag", "table", "thread_local", "use_foreign_library", "use_module", "volatile"];
27
+ const builtins = [["!", 0], ["*->", 2], [",", 2], ["->", 2], [".", 3], [":<", 2], [";", 2], ["<", 2], ["<meta-call>", 1], ["=", 2], ["=..", 2], ["=:=", 2], ["=<", 2], ["==", 2], ["=@=", 2], ["=\\=", 2], [">", 2], [">:<", 2], [">=", 2], ["?=", 2], ["@", 2], ["@<", 2], ["@=<", 2], ["@>", 2], ["@>=", 2], ["[|]", 2], ["\\+", 1], ["\\=", 2], ["\\==", 2], ["\\=@=", 2], ["abolish", 1], ["abolish", 2], ["abolish_all_tables", 0], ["abolish_module_tables", 1], ["abolish_monotonic_tables", 0], ["abolish_nonincremental_tables", 0], ["abolish_nonincremental_tables", 1], ["abolish_private_tables", 0], ["abolish_shared_tables", 0], ["abolish_table_subgoals", 1], ["abort", 0], ["absolute_file_name", 2], ["absolute_file_name", 3], ["access_file", 2], ["acyclic_term", 1], ["add_import_module", 3], ["answer_count_restraint", 0], ["append", 1], ["apply", 2], ["arg", 3], ["assert", 1], ["assert", 2], ["asserta", 1], ["asserta", 2], ["assertz", 1], ["assertz", 2], ["at_end_of_stream", 0], ["at_end_of_stream", 1], ["at_halt", 1], ["atom", 1], ["atom_chars", 2], ["atom_codes", 2], ["atom_concat", 3], ["atom_length", 2], ["atom_number", 2], ["atom_prefix", 2], ["atom_string", 2], ["atom_to_term", 3], ["atomic", 1], ["atomic_concat", 3], ["atomic_list_concat", 2], ["atomic_list_concat", 3], ["atomics_to_string", 2], ["atomics_to_string", 3], ["attach_packs", 0], ["attach_packs", 1], ["attach_packs", 2], ["attvar", 1], ["autoload", 1], ["autoload", 2], ["autoload_call", 1], ["autoload_path", 1], ["b_getval", 2], ["b_set_dict", 3], ["b_setval", 2], ["bagof", 3], ["between", 3], ["blob", 2], ["bounded_number", 3], ["break", 0], ["byte_count", 2], ["call", 1], ["call", 2], ["call", 3], ["call", 4], ["call", 5], ["call", 6], ["call", 7], ["call", 8], ["call_cleanup", 2], ["call_continuation", 1], ["call_dcg", 3], ["call_residue_vars", 2], ["call_shared_object_function", 2], ["call_with_depth_limit", 3], ["call_with_inference_limit", 3], ["callable", 1], ["cancel_halt", 1], ["catch", 3], ["catch_with_backtrace", 3], ["char_code", 2], ["char_conversion", 2], ["char_type", 2], ["character_count", 2], ["clause", 2], ["clause", 3], ["clause_property", 2], ["close", 1], ["close", 2], ["close_shared_object", 1], ["code_type", 2], ["collation_key", 2], ["compare", 3], ["compile_aux_clauses", 1], ["compile_predicates", 1], ["compiling", 0], ["compound", 1], ["compound_name_arguments", 3], ["compound_name_arity", 3], ["consult", 1], ["context_module", 1], ["copy_predicate_clauses", 2], ["copy_stream_data", 2], ["copy_stream_data", 3], ["copy_term", 2], ["copy_term", 3], ["copy_term", 4], ["copy_term_nat", 2], ["copy_term_nat", 4], ["create_prolog_flag", 3], ["current_arithmetic_function", 1], ["current_atom", 1], ["current_blob", 2], ["current_char_conversion", 2], ["current_engine", 1], ["current_flag", 1], ["current_format_predicate", 2], ["current_functor", 2], ["current_input", 1], ["current_key", 1], ["current_locale", 1], ["current_module", 1], ["current_op", 3], ["current_output", 1], ["current_predicate", 1], ["current_predicate", 2], ["current_prolog_flag", 2], ["current_resource", 2], ["current_signal", 3], ["current_table", 2], ["current_transaction", 1], ["current_trie", 1], ["cyclic_term", 1], ["date_time_stamp", 2], ["dcg_translate_rule", 2], ["dcg_translate_rule", 4], ["debug_reset_from_class", 0], ["default_module", 2], ["del_attr", 2], ["del_attrs", 1], ["del_dict", 4], ["delete_directory", 1], ["delete_file", 1], ["delete_import_module", 2], ["det", 1], ["deterministic", 1], ["dict_create", 3], ["dict_pairs", 3], ["dict_same_keys", 2], ["directory_files", 2], ["discontiguous", 1], ["divmod", 4], ["downcase_atom", 2], ["duplicate_term", 2], ["dwim_match", 2], ["dwim_match", 3], ["dwim_predicate", 2], ["dynamic", 1], ["dynamic", 2], ["engine_create", 3], ["engine_create", 4], ["engine_destroy", 1], ["engine_fetch", 1], ["engine_next", 2], ["engine_next_reified", 2], ["engine_post", 2], ["engine_post", 3], ["engine_self", 1], ["engine_yield", 1], ["ensure_loaded", 1], ["erase", 1], ["exists_directory", 1], ["exists_file", 1], ["exists_source", 1], ["exists_source", 2], ["expand_file_name", 2], ["expand_file_search_path", 2], ["expand_goal", 2], ["expand_goal", 4], ["expand_term", 2], ["expand_term", 4], ["export", 1], ["fail", 0], ["false", 0], ["fast_read", 2], ["fast_term_serialized", 2], ["fast_write", 2], ["file_base_name", 2], ["file_directory_name", 2], ["file_name_extension", 3], ["fill_buffer", 1], ["findall", 3], ["findall", 4], ["findnsols", 4], ["findnsols", 5], ["flag", 3], ["float", 1], ["float_class", 2], ["float_parts", 4], ["flush_output", 0], ["flush_output", 1], ["forall", 2], ["format", 1], ["format", 2], ["format", 3], ["format_predicate", 2], ["format_time", 3], ["format_time", 4], ["freeze", 2], ["frozen", 2], ["functor", 3], ["functor", 4], ["garbage_collect", 0], ["garbage_collect_atoms", 0], ["garbage_collect_clauses", 0], ["gc_file_search_cache", 1], ["get", 1], ["get", 2], ["get0", 1], ["get0", 2], ["get_attr", 3], ["get_attrs", 2], ["get_byte", 1], ["get_byte", 2], ["get_char", 1], ["get_char", 2], ["get_code", 1], ["get_code", 2], ["get_dict", 3], ["get_dict", 5], ["get_flag", 2], ["get_single_char", 1], ["get_string_code", 3], ["get_time", 1], ["getenv", 2], ["ground", 1], ["halt", 0], ["halt", 1], ["ignore", 1], ["import", 1], ["import_module", 2], ["initialization", 1], ["initialization", 2], ["initialize", 0], ["instance", 2], ["integer", 1], ["is", 2], ["is_absolute_file_name", 1], ["is_dict", 1], ["is_dict", 2], ["is_engine", 1], ["is_list", 1], ["is_message_queue", 1], ["is_most_general_term", 1], ["is_stream", 1], ["is_thread", 1], ["is_trie", 1], ["keysort", 2], ["known_licenses", 0], ["leash", 1], ["length", 2], ["license", 0], ["license", 1], ["license", 2], ["line_count", 2], ["line_position", 2], ["load_files", 1], ["load_files", 2], ["locale_create", 3], ["locale_destroy", 1], ["locale_property", 2], ["make_directory", 1], ["make_library_index", 1], ["make_library_index", 2], ["malloc_property", 1], ["memberchk", 2], ["message_queue_create", 1], ["message_queue_create", 2], ["message_queue_destroy", 1], ["message_queue_property", 2], ["message_queue_set", 2], ["message_to_string", 2], ["meta_predicate", 1], ["mode", 1], ["module", 1], ["module_property", 2], ["module_transparent", 1], ["msort", 2], ["multifile", 1], ["mutex_create", 1], ["mutex_create", 2], ["mutex_destroy", 1], ["mutex_lock", 1], ["mutex_property", 2], ["mutex_statistics", 0], ["mutex_trylock", 1], ["mutex_unlock", 1], ["mutex_unlock_all", 0], ["name", 2], ["nb_current", 2], ["nb_delete", 1], ["nb_getval", 2], ["nb_link_dict", 3], ["nb_linkarg", 3], ["nb_linkval", 2], ["nb_set_dict", 3], ["nb_setarg", 3], ["nb_setval", 2], ["nl", 0], ["nl", 1], ["non_terminal", 1], ["nonground", 2], ["nonvar", 1], ["noprofile", 1], ["noprotocol", 0], ["normalize_space", 2], ["not", 1], ["not_exists", 1], ["notrace", 0], ["notrace", 1], ["nth_clause", 3], ["nth_integer_root_and_remainder", 4], ["number", 1], ["number_chars", 2], ["number_codes", 2], ["number_string", 2], ["numbervars", 3], ["numbervars", 4], ["on_signal", 3], ["once", 1], ["op", 3], ["open", 3], ["open", 4], ["open_null_stream", 1], ["open_resource", 2], ["open_resource", 3], ["open_shared_object", 2], ["open_shared_object", 3], ["open_string", 2], ["pack_attach", 2], ["peek_byte", 1], ["peek_byte", 2], ["peek_char", 1], ["peek_char", 2], ["peek_code", 1], ["peek_code", 2], ["peek_string", 3], ["phrase", 2], ["phrase", 3], ["plus", 3], ["predicate_property", 2], ["print", 1], ["print", 2], ["print_message", 2], ["print_message_lines", 3], ["print_toplevel_variables", 0], ["profiler", 2], ["prolog", 0], ["prolog_alert_signal", 2], ["prolog_choice_attribute", 3], ["prolog_current_choice", 1], ["prolog_current_frame", 1], ["prolog_cut_to", 1], ["prolog_debug", 1], ["prolog_frame_attribute", 3], ["prolog_interrupt", 0], ["prolog_listen", 2], ["prolog_listen", 3], ["prolog_load_context", 2], ["prolog_nodebug", 1], ["prolog_skip_level", 2], ["prolog_stack_property", 2], ["prolog_to_os_filename", 2], ["prolog_unlisten", 2], ["prompt", 2], ["prompt1", 1], ["protocol", 1], ["protocola", 1], ["protocolling", 1], ["public", 1], ["put", 1], ["put", 2], ["put_attr", 3], ["put_attrs", 2], ["put_byte", 1], ["put_byte", 2], ["put_char", 1], ["put_char", 2], ["put_code", 1], ["put_code", 2], ["put_dict", 3], ["put_dict", 4], ["qcompile", 1], ["qcompile", 2], ["radial_restraint", 0], ["random_property", 1], ["rational", 1], ["rational", 3], ["read", 1], ["read", 2], ["read_clause", 3], ["read_link", 3], ["read_pending_chars", 3], ["read_pending_codes", 3], ["read_string", 3], ["read_string", 5], ["read_term", 2], ["read_term", 3], ["read_term_from_atom", 3], ["read_term_with_history", 2], ["recorda", 2], ["recorda", 3], ["recorded", 2], ["recorded", 3], ["recordz", 2], ["recordz", 3], ["redefine_system_predicate", 1], ["reexport", 1], ["reexport", 2], ["register_iri_scheme", 3], ["reload_library_index", 0], ["rename_file", 2], ["repeat", 0], ["require", 1], ["reset", 3], ["reset_profiler", 0], ["residual_goals", 1], ["retract", 1], ["retractall", 1], ["rule", 2], ["rule", 3], ["same_file", 2], ["same_term", 2], ["see", 1], ["seeing", 1], ["seek", 4], ["seen", 0], ["select_dict", 3], ["set_end_of_stream", 1], ["set_flag", 2], ["set_input", 1], ["set_locale", 1], ["set_malloc", 1], ["set_module", 1], ["set_output", 1], ["set_prolog_IO", 3], ["set_prolog_flag", 2], ["set_prolog_gc_thread", 1], ["set_prolog_stack", 2], ["set_random", 1], ["set_stream", 2], ["set_stream_position", 2], ["set_system_IO", 3], ["set_thread", 2], ["setarg", 3], ["setenv", 2], ["setlocale", 3], ["setof", 3], ["setup_call_catcher_cleanup", 4], ["setup_call_cleanup", 3], ["shell", 1], ["shell", 2], ["shift", 1], ["shift_for_copy", 1], ["sig_atomic", 1], ["sig_block", 1], ["sig_pending", 1], ["sig_remove", 2], ["sig_unblock", 1], ["size_abstract_term", 3], ["size_file", 2], ["skip", 1], ["skip", 2], ["sleep", 1], ["snapshot", 1], ["sort", 2], ["sort", 4], ["source_file", 1], ["source_file", 2], ["source_file_property", 2], ["source_location", 2], ["split_string", 4], ["stamp_date_time", 3], ["start_abstract_tabling", 3], ["start_moded_tabling", 5], ["start_subsumptive_tabling", 3], ["start_tabling", 3], ["statistics", 2], ["stream_pair", 3], ["stream_position_data", 3], ["stream_property", 2], ["string", 1], ["string_bytes", 3], ["string_chars", 2], ["string_code", 3], ["string_codes", 2], ["string_concat", 3], ["string_length", 2], ["string_lower", 2], ["string_upper", 2], ["strip_module", 3], ["style_check", 1], ["sub_atom", 5], ["sub_atom_icasechk", 3], ["sub_string", 5], ["subsumes_term", 2], ["succ", 2], ["tab", 1], ["tab", 2], ["table", 1], ["tabled_call", 1], ["tell", 1], ["telling", 1], ["term_attvars", 2], ["term_expansion", 2], ["term_hash", 2], ["term_hash", 4], ["term_singletons", 2], ["term_string", 2], ["term_string", 3], ["term_to_atom", 2], ["term_variables", 2], ["term_variables", 3], ["text_to_string", 2], ["thread_affinity", 3], ["thread_create", 2], ["thread_create", 3], ["thread_detach", 1], ["thread_exit", 1], ["thread_get_message", 1], ["thread_get_message", 2], ["thread_get_message", 3], ["thread_idle", 2], ["thread_initialization", 1], ["thread_join", 1], ["thread_join", 2], ["thread_local", 1], ["thread_peek_message", 1], ["thread_peek_message", 2], ["thread_property", 2], ["thread_self", 1], ["thread_send_message", 2], ["thread_send_message", 3], ["thread_setconcurrency", 2], ["thread_signal", 2], ["thread_statistics", 3], ["thread_update", 2], ["thread_wait", 2], ["throw", 1], ["time_file", 2], ["tmp_file", 2], ["tmp_file_stream", 3], ["tnot", 1], ["told", 0], ["trace", 0], ["tracing", 0], ["transaction", 1], ["transaction", 2], ["transaction", 3], ["transaction_updates", 1], ["trie_delete", 3], ["trie_destroy", 1], ["trie_gen", 2], ["trie_gen", 3], ["trie_insert", 2], ["trie_insert", 3], ["trie_insert", 4], ["trie_lookup", 3], ["trie_new", 1], ["trie_property", 2], ["trie_term", 2], ["trie_update", 3], ["trim_heap", 0], ["trim_stacks", 0], ["true", 0], ["tty_get_capability", 3], ["tty_goto", 2], ["tty_put", 2], ["tty_size", 2], ["ttyflush", 0], ["undefined", 0], ["undo", 1], ["unifiable", 3], ["unify_with_occurs_check", 2], ["unload_file", 1], ["unsetenv", 1], ["untable", 1], ["unwrap_predicate", 2], ["upcase_atom", 2], ["use_foreign_library", 1], ["use_foreign_library", 2], ["use_module", 1], ["use_module", 2], ["var", 1], ["var_number", 2], ["var_property", 2], ["variant_hash", 2], ["variant_sha1", 2], ["verbose_expansion", 1], ["version", 0], ["version", 1], ["visible", 1], ["volatile", 1], ["wait_for_input", 3], ["wildcard_match", 2], ["wildcard_match", 3], ["win_rename_file", 2], ["with_mutex", 2], ["with_output_to", 2], ["with_tty_raw", 1], ["working_directory", 2], ["write", 1], ["write", 2], ["write_canonical", 1], ["write_canonical", 2], ["write_length", 3], ["write_term", 2], ["write_term", 3], ["writeln", 1], ["writeln", 2], ["writeq", 1], ["writeq", 2], ["zip_clone", 2], ["zip_close_", 2], ["zip_file_info_", 3], ["zip_lock", 1], ["zip_open_stream", 3], ["zip_unlock", 1], ["zipper_goto", 2], ["zipper_open_current", 3], ["zipper_open_new_file_in_zip", 4]];
28
+
29
+ const controlNames = new Set(control);
30
+ const directiveNames = new Set(directives);
31
+ const operatorNames = new Set(operators);
32
+ const builtinNames = new Set(builtins.map(([name]) => name));
33
+ const necks = new Set([":-", "-->", "?-"]);
34
+
35
+ // The character classes of SWI-Prolog's reader (manual section "Unicode Prolog source"):
36
+ // identifiers are ID_Start ID_Continue*, variables start with an uppercase letter or `_`,
37
+ // non-ASCII symbols and punctuation glue like the ASCII symbol characters.
38
+ const symbolChar = /^(?:[#$&*+\-./:<=>?@^~\\]|(?![\0-\x7f])[\p{S}\p{P}])$/u;
39
+ const nameStart = /^[\p{ID_Start}_]$/u;
40
+ const nameChar = /^\p{ID_Continue}$/u;
41
+ const variableStart = /^[\p{Lu}\p{Lt}_]$/u;
42
+ const layout = /^\s$/u;
43
+
44
+ const chr = (input, offset) => {
45
+ const code = input.peek(offset);
46
+ if (code < 0) return ""
47
+ if (code >= 0xd800 && code < 0xdc00) {
48
+ const low = input.peek(offset + 1);
49
+ if (low >= 0xdc00 && low < 0xe000) return String.fromCharCode(code, low)
50
+ }
51
+ return String.fromCharCode(code)
52
+ };
53
+
54
+ // The character before `(` or `{`: `f(` is a compound and `t{` a dict, `f (` and `t {`
55
+ // are not.
56
+ const before = input => String.fromCharCode(input.peek(-1));
57
+ const endsTag = c => c == "'" || nameChar.test(c);
58
+
59
+ function scan(input, text, test) {
60
+ let c;
61
+ while ((c = chr(input, text.length)) && test.test(c)) text += c;
62
+ return text
63
+ }
64
+
65
+ function nameKind(text) {
66
+ if (controlNames.has(text)) return Control
67
+ if (directiveNames.has(text)) return DirectiveName
68
+ if (operatorNames.has(text)) return Operator
69
+ if (builtinNames.has(text)) return Builtin
70
+ return Atom
71
+ }
72
+
73
+ function symbolKind(text) {
74
+ if (necks.has(text)) return Neck
75
+ if (text == ":") return Colon
76
+ if (controlNames.has(text)) return Control
77
+ return SymbolAtom
78
+ }
79
+
80
+ // SWI-Prolog nests block comments.
81
+ function blockComment(input) {
82
+ let depth = 0;
83
+ for (let i = 0; ; i++) {
84
+ const c = input.peek(i);
85
+ if (c < 0) return input.acceptToken(BlockComment, i)
86
+ if (c == 47 /* / */ && input.peek(i + 1) == 42 /* * */) { depth++; i++; }
87
+ else if (c == 42 && input.peek(i + 1) == 47) {
88
+ i++;
89
+ if (--depth == 0) return input.acceptToken(BlockComment, i + 1)
90
+ }
91
+ }
92
+ }
93
+
94
+ function quasiQuotation(input) {
95
+ for (let i = 2; ; i++) {
96
+ const c = input.peek(i);
97
+ if (c < 0) return input.acceptToken(QuasiQuotation, i)
98
+ if (c == 124 /* | */ && input.peek(i + 1) == 125 /* } */) return input.acceptToken(QuasiQuotation, i + 2)
99
+ }
100
+ }
101
+
102
+ const prologTokens = new ExternalTokenizer((input, stack) => {
103
+ const next = input.next;
104
+ if (next == 47 && input.peek(1) == 42) return blockComment(input)
105
+ if (next == 40 /* ( */) {
106
+ const c = before(input);
107
+ if ((endsTag(c) || symbolChar.test(c)) && stack.canShift(CallOpen)) input.acceptToken(CallOpen, 1);
108
+ return
109
+ }
110
+ if (next == 123 /* { */) {
111
+ if (input.peek(1) == 124) return quasiQuotation(input)
112
+ if (endsTag(before(input)) && stack.canShift(DictOpen)) input.acceptToken(DictOpen, 1);
113
+ return
114
+ }
115
+ const first = chr(input, 0);
116
+ if (symbolChar.test(first)) {
117
+ const text = scan(input, "", symbolChar);
118
+ if (text == ".") {
119
+ const after = chr(input, 1);
120
+ if (!after || after == "%" || layout.test(after)) return input.acceptToken(End, 1)
121
+ }
122
+ return input.acceptToken(symbolKind(text), text.length)
123
+ }
124
+ if (nameStart.test(first)) {
125
+ const text = scan(input, first, nameChar);
126
+ if (text == "_") return input.acceptToken(Anonymous, 1)
127
+ return input.acceptToken(variableStart.test(first) ? Variable : nameKind(text), text.length)
128
+ }
129
+ }, {contextual: true});
130
+
131
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
132
+ const parser = LRParser.deserialize({
133
+ version: 14,
134
+ states: "(|Q]QROOOOQP'#Da'#DaO!sQRO'#DbOOQP'#Db'#DbO&QQRO'#CzO&XQRO'#C}O&`QRO'#DPO(TQRO'#DVOOQP'#Dc'#DcO([QRO'#CnOOQP'#De'#DeO(cQ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SXw!SXo!SXf!SXQ!SX~OlyO~P$jO^pO~Oo{O~P$jOf|O~P$jOQ!RO~P`Of!TO~P$jOQ!WaR!Wa~P`OQ!WO~P`Oo!XO~P$jOSyX~P&gO^pOQ!WiR!Wi~P`Of![O~P$jOQ!]O~P`OQ!WqR!Wq~P`OQ!WyR!Wy~P`O",
136
+ goto: "'`!YPPPPPPPPPPPPPPPPPP!ZP!_!yP#ePPPPPP#nPP#nP#n#nPPP!Z$_!Z$f$l%YPPP%p%t&b#n#n'T'XT^O`!RgSTUXZ[adhjnpqrsv!O!P!S!U!V!Y!Z!^!ReSTUXZ[adhjnpqrsv!O!P!S!U!V!Y!Z!^QrZQzeR!Z!OUYO`l!RgSTUXZ[adhjnpqrsv!O!P!S!U!V!Y!Z!^SZO`R!OlQ`ORu`QnXSqZ[[!Qnq!U!V!Y!^Q!UrQ!VsS!Y!O!PR!^!ZQdSQhTQjUQvaYxdhjv!SR!SpT_O`dcSTUadhjpv!SmmXZ[nqrs!O!P!U!V!Y!Z!^SVO`!QbSTUXZ[adhjnpqrsv!O!P!S!U!V!Y!Z!^R}lT]O`S[O`R!Pl",
137
+ nodeNames: "⚠ BlockComment End Neck Colon Control SymbolAtom Atom Operator DirectiveName Builtin Variable Anonymous QuasiQuotation CallOpen DictOpen LineComment Program Directive QuotedAtom Compound Functor ) ArgList Number String BackquoteString ! ] [ List } { Curly ( Parenthesized Dict , ; | Rule HeadFunctor Fact",
138
+ maxTerm: 55,
139
+ nodeProps: [
140
+ ["closedBy", -2,14,34,")",-2,15,32,"}",29,"]"],
141
+ ["openedBy", 22,"(",28,"[",31,"{"]
142
+ ],
143
+ skippedNodes: [0,1,16],
144
+ repeatNodeCount: 3,
145
+ tokenData: ";P~RqXY#YYZ#Y[]#Y]^#Ypq#Yqr$Zrs$`uv&Pwx&hxy(Xyz(^|}(c!Q!R(h!R!S5P!S!T7a!T!U8O!U![5k!]!^8p!}#O8u#P#Q8z#S#T9P#j#k#Y#o#p:p#p#q:u#q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l9P~:uOp~~:zOw~~;POo~",
146
+ tokenizers: [prologTokens, 0],
147
+ topRules: {"Program":[0,17]},
148
+ tokenPrec: 0
149
+ });
150
+
151
+ const prologHighlighting = styleTags({
152
+ Variable: tags.variableName,
153
+ Anonymous: tags.special(tags.variableName),
154
+ "Atom QuotedAtom": tags.atom,
155
+ Number: tags.number,
156
+ String: tags.string,
157
+ "BackquoteString QuasiQuotation": tags.special(tags.string),
158
+ LineComment: tags.lineComment,
159
+ BlockComment: tags.blockComment,
160
+ Neck: tags.definitionOperator,
161
+ End: tags.punctuation,
162
+ Operator: tags.operatorKeyword,
163
+ SymbolAtom: tags.operator,
164
+ 'Control "!" ";"': tags.controlKeyword,
165
+ DirectiveName: tags.definitionKeyword,
166
+ Builtin: tags.standard(tags.variableName),
167
+ "HeadFunctor/Atom HeadFunctor/QuotedAtom HeadFunctor/Operator HeadFunctor/Control HeadFunctor/DirectiveName HeadFunctor/Builtin HeadFunctor/SymbolAtom": tags.definition(tags.function(tags.variableName)),
168
+ "Functor/Atom Functor/QuotedAtom Functor/SymbolAtom": tags.function(tags.variableName),
169
+ "Functor/Builtin": tags.standard(tags.function(tags.variableName)),
170
+ '"(" ")" CallOpen': tags.paren,
171
+ '"[" "]"': tags.squareBracket,
172
+ '"{" "}" DictOpen': tags.brace,
173
+ '"," "|" Colon': tags.separator,
174
+ });
175
+
176
+ // The library predicates that programs use most, as [library, name, arities].
177
+ // `tables.ts` only has SWI-Prolog's system predicates. Most of these load on first use;
178
+ // clpfd, dcg/basics, readutil and plunit need a `use_module`. Completion offers them, and the
179
+ // tokenizer still reads them as plain atoms.
180
+ const library = [
181
+ ["lists", "append", [2, 3]],
182
+ ["lists", "member", [2]],
183
+ ["lists", "memberchk", [2]],
184
+ ["lists", "delete", [3]],
185
+ ["lists", "exclude", [3]],
186
+ ["lists", "flatten", [2]],
187
+ ["lists", "intersection", [3]],
188
+ ["lists", "last", [2]],
189
+ ["lists", "list_to_set", [2]],
190
+ ["lists", "max_list", [2]],
191
+ ["lists", "max_member", [2, 3]],
192
+ ["lists", "min_list", [2]],
193
+ ["lists", "min_member", [2, 3]],
194
+ ["lists", "nextto", [3]],
195
+ ["lists", "nth0", [3, 4]],
196
+ ["lists", "nth1", [3, 4]],
197
+ ["lists", "numlist", [3]],
198
+ ["lists", "permutation", [2]],
199
+ ["lists", "proper_length", [2]],
200
+ ["lists", "reverse", [2]],
201
+ ["lists", "same_length", [2]],
202
+ ["lists", "select", [3, 4]],
203
+ ["lists", "selectchk", [3]],
204
+ ["lists", "subtract", [3]],
205
+ ["lists", "sum_list", [2]],
206
+ ["lists", "sumlist", [2]],
207
+ ["lists", "union", [3]],
208
+ ["pairs", "pairs_keys_values", [3]],
209
+ ["lists", "clumped", [2]],
210
+ ["lists", "subseq", [3]],
211
+ ["lists", "predsort", [3]],
212
+ ["apply", "maplist", [2, 3, 4, 5, 6, 7]],
213
+ ["apply", "foldl", [4, 5, 6, 7]],
214
+ ["apply", "include", [3]],
215
+ ["apply", "partition", [4, 6]],
216
+ ["apply", "convlist", [3]],
217
+ ["aggregate", "aggregate_all", [3, 4]],
218
+ ["aggregate", "aggregate", [3, 4]],
219
+ ["aggregate", "foreach", [2]],
220
+ ["pairs", "pairs_keys", [2]],
221
+ ["pairs", "pairs_values", [2]],
222
+ ["pairs", "transpose_pairs", [2]],
223
+ ["pairs", "map_list_to_pairs", [3]],
224
+ ["error", "must_be", [2]],
225
+ ["error", "is_of_type", [2]],
226
+ ["error", "domain_error", [2]],
227
+ ["error", "type_error", [2]],
228
+ ["error", "instantiation_error", [1]],
229
+ ["error", "existence_error", [2]],
230
+ ["dcg/basics", "digits", [3]],
231
+ ["dcg/basics", "digit", [3]],
232
+ ["dcg/basics", "integer", [3]],
233
+ ["dcg/basics", "blanks", [2]],
234
+ ["dcg/basics", "string_without", [4]],
235
+ ["dcg/basics", "whites", [2]],
236
+ ["clpfd", "label", [1]],
237
+ ["clpfd", "labeling", [2]],
238
+ ["clpfd", "all_different", [1]],
239
+ ["clpfd", "all_distinct", [1]],
240
+ ["clpfd", "sum", [3]],
241
+ ["clpfd", "tuples_in", [2]],
242
+ ["clpfd", "transpose", [2]],
243
+ ["readutil", "read_term_from_atom", [3]],
244
+ ["readutil", "read_line_to_string", [2]],
245
+ ["readutil", "read_line_to_codes", [2]],
246
+ ["option", "option", [2, 3]],
247
+ ["random", "random_between", [3]],
248
+ ["random", "random_member", [2]],
249
+ ["random", "random_permutation", [2]],
250
+ ["random", "random", [1]],
251
+ ["ordsets", "list_to_ord_set", [2]],
252
+ ["ordsets", "ord_union", [3]],
253
+ ["ordsets", "ord_subtract", [3]],
254
+ ["ordsets", "ord_memberchk", [2]],
255
+ ["ordsets", "ord_insert", [3]],
256
+ ["assoc", "list_to_assoc", [2]],
257
+ ["assoc", "put_assoc", [4]],
258
+ ["assoc", "get_assoc", [3]],
259
+ ["assoc", "empty_assoc", [1]],
260
+ ["assoc", "assoc_to_list", [2]],
261
+ ["assoc", "assoc_to_keys", [2]],
262
+ ["assoc", "assoc_to_values", [2]],
263
+ ["plunit", "begin_tests", [1, 2]],
264
+ ["plunit", "end_tests", [1]],
265
+ ["plunit", "run_tests", [0, 1]],
266
+ ];
267
+
268
+ const clauses$1 = new Set(["Directive", "Rule", "Fact"]);
269
+ const dontComplete = new Set([
270
+ "LineComment", "BlockComment", "QuotedAtom", "String", "BackquoteString", "QuasiQuotation", "Number",
271
+ ]);
272
+ /// Snippets for whole clauses, offered where a new clause starts.
273
+ const clauseSnippets = [
274
+ snippetCompletion("${name}(${Args}) :-\n\t${body}.", { label: "rule", detail: "Head :- Body.", type: "keyword" }),
275
+ snippetCompletion("${name}(${args}).", { label: "fact", detail: "name(args).", type: "keyword" }),
276
+ snippetCompletion("${name} -->\n\t${body}.", { label: "dcg", detail: "Head --> Body.", type: "keyword" }),
277
+ snippetCompletion(":- use_module(library(${lists})).", { label: "use_module", detail: "directive", type: "keyword" }),
278
+ snippetCompletion(":- initialization(${main}).", { label: "initialization", detail: "directive", type: "keyword" }),
279
+ ];
280
+ /// Snippets for goals, offered inside a clause.
281
+ const goalSnippets = [
282
+ snippetCompletion("( ${Condition}\n-> ${Then}\n; ${Else}\n)", { label: "if", detail: "( -> ; )", type: "keyword" }),
283
+ snippetCompletion("( ${Condition}\n-> ${Then}\n)", { label: "if", detail: "( -> )", type: "keyword" }),
284
+ snippetCompletion("findall(${Template}, ${Goal}, ${List})", { label: "findall", detail: "snippet", type: "keyword" }),
285
+ snippetCompletion("forall(${Condition}, ${Action})", { label: "forall", detail: "snippet", type: "keyword" }),
286
+ snippetCompletion("format(\"${~w~n}\", [${Args}])", { label: "format", detail: "snippet", type: "keyword" }),
287
+ snippetCompletion("maplist(${Goal}, ${List})", { label: "maplist", detail: "snippet", type: "keyword" }),
288
+ snippetCompletion("catch(${Goal}, ${Error}, ${Recovery})", { label: "catch", detail: "snippet", type: "keyword" }),
289
+ ];
290
+ // Built-ins with symbol names (`=..`, `\+`) and internal ones (`$...`, `<meta-call>`) are
291
+ // left out: completion starts on a word.
292
+ const word = /^[a-z][A-Za-z0-9_]*$/;
293
+ function predicateOptions() {
294
+ const seen = new Set(), options = [];
295
+ const add = (label, arity, info) => {
296
+ const key = `${label}/${arity}`;
297
+ if (!word.test(label) || seen.has(key))
298
+ return;
299
+ seen.add(key);
300
+ options.push(Object.assign({ label, detail: `/${arity}`, type: "function" }, (info ? { info } : {})));
301
+ };
302
+ for (const [name, arity] of builtins)
303
+ add(name, arity);
304
+ for (const [lib, name, arities] of library)
305
+ for (const arity of arities)
306
+ add(name, arity, `library(${lib})`);
307
+ for (const name of operators)
308
+ if (!seen.has(`${name}/2`))
309
+ options.push({ label: name, type: "keyword" });
310
+ return options;
311
+ }
312
+ /// The built-in and library predicates, with their arity in `detail`, and the
313
+ /// alphanumeric operators such as `is` and `mod`.
314
+ const globalOptions = predicateOptions();
315
+ // Arguments are the items between the top-level commas of an ArgList.
316
+ function arity(argList) {
317
+ if (!argList || argList.name != "ArgList")
318
+ return 0;
319
+ let count = 0, empty = true;
320
+ for (let child = argList.firstChild; child; child = child.nextSibling) {
321
+ if (child.name == ",")
322
+ count++;
323
+ else if (child.name != "CallOpen" && child.name != ")")
324
+ empty = false;
325
+ }
326
+ return empty && count == 0 ? 0 : count + 1;
327
+ }
328
+ // Every predicate and DCG nonterminal defined in the file, as `name/N` or `name//N`.
329
+ function definedPredicates(doc, top, skip) {
330
+ const seen = new Set(), options = [];
331
+ for (let clause = top.firstChild; clause; clause = clause.nextSibling) {
332
+ const head = clause.getChild("HeadFunctor");
333
+ if (!head || head.from == skip)
334
+ continue;
335
+ const neck = clause.getChild("Neck");
336
+ const dcg = neck != null && doc.sliceString(neck.from, neck.to) == "-->";
337
+ const label = doc.sliceString(head.from, head.to);
338
+ const detail = `${dcg ? "//" : "/"}${arity(head.nextSibling)}`;
339
+ if (seen.has(label + detail))
340
+ continue;
341
+ seen.add(label + detail);
342
+ options.push({ label, detail, type: "function", boost: 1 });
343
+ }
344
+ return options;
345
+ }
346
+ // Every named variable in the clause. A variable is local to its clause in Prolog.
347
+ function clauseVariables(doc, clause, skip) {
348
+ const seen = new Set(), options = [];
349
+ clause.cursor().iterate(node => {
350
+ if (node.name != "Variable" || node.from == skip)
351
+ return;
352
+ const name = doc.sliceString(node.from, node.to);
353
+ if (!seen.has(name)) {
354
+ seen.add(name);
355
+ options.push({ label: name, type: "variable", boost: 2 });
356
+ }
357
+ });
358
+ return options;
359
+ }
360
+ /// Completion for SWI-Prolog. A word that starts with an uppercase letter or `_` gets the
361
+ /// variables of the current clause. Any other word gets the predicates defined in the
362
+ /// file, the built-ins and snippets: clause snippets where a clause starts, and goal
363
+ /// snippets inside one. Nothing is offered in comments, strings or quoted atoms.
364
+ function prologCompletion(context) {
365
+ var _a;
366
+ const tree = syntaxTree(context.state);
367
+ const inner = tree.resolveInner(context.pos, -1);
368
+ for (let node = inner; node; node = node.parent)
369
+ if (dontComplete.has(node.name))
370
+ return null;
371
+ const match = context.matchBefore(/[\p{L}_][\p{L}\p{N}_]*/u);
372
+ if (!match && !context.explicit)
373
+ return null;
374
+ const from = match ? match.from : context.pos;
375
+ // `0'c` is a character code, and `f(` after a word starts its arguments.
376
+ if (from > 0 && /[0-9']/.test(context.state.sliceDoc(from - 1, from)))
377
+ return null;
378
+ let clause = inner;
379
+ while (clause && !clauses$1.has(clause.name))
380
+ clause = clause.parent;
381
+ const doc = context.state.doc;
382
+ const text = match ? match.text : "";
383
+ const variablesOnly = /^[\p{Lu}\p{Lt}_]/u.test(text);
384
+ const variables = clause ? clauseVariables(doc, clause, from) : [];
385
+ if (variablesOnly)
386
+ return variables.length ? { from, options: variables, validFor: /^[\p{L}\p{N}_]*$/u } : null;
387
+ const ended = ((_a = clause === null || clause === void 0 ? void 0 : clause.lastChild) === null || _a === void 0 ? void 0 : _a.name) == "End" && clause.lastChild.to <= from;
388
+ const atClauseStart = !clause || ended || clause.from == from;
389
+ const options = [
390
+ ...definedPredicates(doc, tree.topNode, from),
391
+ ...(atClauseStart ? clauseSnippets : [...goalSnippets, ...globalOptions]),
392
+ ...(context.explicit && !atClauseStart ? variables : []),
393
+ ];
394
+ return { from, options, validFor: /^[\p{L}\p{N}_]*$/u };
395
+ }
396
+
397
+ const clauses = "Directive Rule Fact";
398
+ // Folds a clause from the end of its first line's construct (the neck, or the head of a
399
+ // fact) to its end token.
400
+ function foldClause(node) {
401
+ var _a;
402
+ const end = node.lastChild, from = ((_a = node.getChild("Neck")) !== null && _a !== void 0 ? _a : node.firstChild).to;
403
+ return (end === null || end === void 0 ? void 0 : end.name) == "End" && end.from > from ? { from, to: end.from } : null;
404
+ }
405
+ // SWI-Prolog's layout of if-then-else: `->`, `*->`, `;`, `|` and `)` line up with the
406
+ // opening parenthesis, the goals one unit further in.
407
+ function parenthesized(cx) {
408
+ const column = cx.column(cx.node.from);
409
+ return /^\s*(->|\*->|;|\||\))/.test(cx.textAfter) ? column : column + cx.unit;
410
+ }
411
+ const prologLanguage = LRLanguage.define({
412
+ name: "prolog",
413
+ parser: parser.configure({
414
+ props: [
415
+ prologHighlighting,
416
+ indentNodeProp.add({
417
+ [clauses]: continuedIndent(),
418
+ Parenthesized: parenthesized,
419
+ ArgList: delimitedIndent({ closing: ")" }),
420
+ List: delimitedIndent({ closing: "]" }),
421
+ "Curly Dict": delimitedIndent({ closing: "}" }),
422
+ }),
423
+ foldNodeProp.add({
424
+ [clauses]: foldClause,
425
+ BlockComment: node => ({ from: node.from + 2, to: node.to - 2 }),
426
+ }),
427
+ ],
428
+ }),
429
+ languageData: {
430
+ commentTokens: { line: "%", block: { open: "/*", close: "*/" } },
431
+ closeBrackets: { brackets: ["(", "[", "{", "'", '"', "`"] },
432
+ },
433
+ });
434
+ /// SWI-Prolog language support for CodeMirror, with completion of built-in predicates,
435
+ /// snippets, and the predicates and variables defined in the file.
436
+ function prolog() {
437
+ return new LanguageSupport(prologLanguage, prologLanguage.data.of({ autocomplete: prologCompletion }));
438
+ }
439
+
440
+ export { clauseSnippets, globalOptions, goalSnippets, prolog, prologCompletion, prologLanguage };
@@ -0,0 +1 @@
1
+ export declare const library: [string, string, number[]][];
@@ -0,0 +1,4 @@
1
+ export declare const operators: string[];
2
+ export declare const control: string[];
3
+ export declare const directives: string[];
4
+ export declare const builtins: [string, number][];
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@exercism/codemirror-lang-prolog",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "keywords": [
5
+ "codemirror",
6
+ "lezer",
7
+ "prolog",
8
+ "swi-prolog"
9
+ ],
10
+ "description": "SWI-Prolog language support for CodeMirror",
11
+ "scripts": {
12
+ "test": "mocha test/*.js",
13
+ "build": "rollup -c && tsc -p tsconfig.json --declaration --emitDeclarationOnly --outDir dist",
14
+ "prepare": "pnpm run build"
15
+ },
16
+ "type": "module",
17
+ "main": "dist/index.cjs",
18
+ "module": "dist/index.js",
19
+ "exports": {
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ },
23
+ "types": "dist/index.d.ts",
24
+ "files": [
25
+ "dist",
26
+ "LICENSE",
27
+ "NOTICE",
28
+ "README.md"
29
+ ],
30
+ "sideEffects": false,
31
+ "dependencies": {
32
+ "@codemirror/autocomplete": "^6.0.0",
33
+ "@codemirror/language": "^6.0.0",
34
+ "@lezer/common": "^1.5.3",
35
+ "@lezer/highlight": "^1.0.0",
36
+ "@lezer/lr": "^1.0.0"
37
+ },
38
+ "devDependencies": {
39
+ "@codemirror/state": "^6.0.0",
40
+ "@lezer/generator": "^1.0.0",
41
+ "@rollup/plugin-typescript": "^12.1.4",
42
+ "@types/node": "^26.0.0",
43
+ "mocha": "^11.7.1",
44
+ "rollup": "^4.45.1",
45
+ "tslib": "^2.8.1",
46
+ "typescript": "^5.8.3"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/exercism/codemirror-lang-prolog.git",
51
+ "directory": "packages/codemirror-lang-swipl"
52
+ },
53
+ "homepage": "https://github.com/exercism/codemirror-lang-prolog#readme",
54
+ "bugs": {
55
+ "url": "https://github.com/exercism/codemirror-lang-prolog/issues"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "license": "MIT"
61
+ }