@tenzir/codemirror-lang-tql 0.4.7 → 0.5.0

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/dist/index.js CHANGED
@@ -1,121 +1,641 @@
1
- import { ContextTracker, ExternalTokenizer, LRParser, LocalTokenGroup } from '@lezer/lr';
2
- import { LRLanguage, LanguageSupport } from '@codemirror/language';
3
- import { styleTags, tags } from '@lezer/highlight';
1
+ import { languageDataProp, indentNodeProp, foldNodeProp, defineLanguageFacet, LanguageSupport, Language } from '@codemirror/language';
2
+ import { NodeProp, Parser, NodeType, Tree, parseMixed } from '@lezer/common';
3
+ import { tags, Tag, styleTags } from '@lezer/highlight';
4
4
 
5
- // This file was generated by lezer-generator. You probably shouldn't edit it.
6
- const newline = 70, ignoredNewline = 71, Ident = 1, FnIdent = 2, DollarIdent = 3, LBracket = 13, RBracket = 14, LParen = 15, RParen = 16, Comma = 21, LBrace = 51, RBrace = 52;
5
+ var brackets = ";; Auto-generated by tenzir/tree-sitter-tql/scripts/generate-brackets.mjs. DO NOT EDIT.\n\n(\"(\" @open \")\" @close)\n(\"[\" @open \"]\" @close)\n(\"{\" @open \"}\" @close)\n";
7
6
 
8
- class MyContext {
9
- constructor(parent, data) {
10
- this.parent = parent !== null && parent !== void 0 ? parent : this;
11
- this.data = data;
7
+ var folds = ";; Auto-generated by tenzir/tree-sitter-tql/scripts/generate-folds.mjs. DO NOT EDIT.\n\n[\n (then_block)\n (else_block)\n (pipeline_block)\n (pipeline_expression)\n (match_statement)\n (match_arm)\n (list)\n (record)\n (frontmatter)\n] @fold\n";
8
+
9
+ var highlights = ";; Auto-generated by tenzir/tree-sitter-tql/scripts/generate-highlights.mjs. DO NOT EDIT.\n\n[\n \"let\"\n \"if\"\n \"else\"\n \"match\"\n \"and\"\n \"or\"\n \"not\"\n \"move\"\n \"in\"\n \"this\"\n \"?\"\n \".\"\n \"...\"\n \"[\"\n \"]\"\n \"{\"\n \"}\"\n \":\"\n] @keyword\n\n[\n \"+\"\n \"-\"\n \"*\"\n \"/\"\n] @keyword\n\n\"_\" @variable.builtin\n\n\"null\" @constant.builtin\n\n[\n \"true\"\n \"false\"\n] @boolean\n\n(dollar_var) @variable.builtin\n(global_sigil) @keyword\n(metadata_sigil) @keyword\n(meta_selector) @attribute\n(number) @number\n(string) @string\n(format_expr) @string\n(ip) @constant\n(subnet) @constant\n(time) @number\n(duration) @number\n(frontmatter_open) @comment\n(frontmatter_close) @comment\n(comment) @comment\n\n(invocation\n operator: (entity) @function.call)\n(call_expression\n (entity) @function.call)\n(call_expression\n method: (entity) @function.method)\n((identifier) @variable.builtin (#match? @variable.builtin \"^\\$[A-Za-z_]\\w*$\"))\n\n[\n \"(\"\n \")\"\n] @punctuation.bracket\n\n[\n \",\"\n] @punctuation.delimiter\n\n[\n \"=\"\n \"=>\"\n \"|\"\n \"..\"\n \"::\"\n \"==\"\n \"!=\"\n \">\"\n \">=\"\n \"<\"\n \"<=\"\n] @operator\n";
10
+
11
+ var indents = ";; Auto-generated by tenzir/tree-sitter-tql/scripts/generate-indents.mjs. DO NOT EDIT.\n\n[\n (then_block)\n (else_block)\n (pipeline_block)\n (pipeline_expression)\n (match_statement)\n (match_arm)\n (list)\n (record)\n] @indent\n\n[\n \"}\"\n \"]\"\n] @outdent\n\n[\n (string)\n (format_text)\n (comment)\n (frontmatter_body)\n] @indent.auto\n";
12
+
13
+ var injections = ";; Auto-generated by tenzir/tree-sitter-tql/scripts/generate-injections.mjs. DO NOT EDIT.\n\n;; Highlight YAML frontmatter using the YAML grammar.\n\n(frontmatter\n body: (frontmatter_body) @injection.content\n (#set! injection.language \"yaml\")\n (#set! injection.combined)\n (#set! injection.include-children))\n";
14
+
15
+ /**
16
+ * The style tags that the highlight query's captures map to by default.
17
+ *
18
+ * A capture without an entry of its own falls back to its parent capture by
19
+ * dropping trailing components, so `@function.builtin` resolves like
20
+ * `@function`. Captures that resolve to no tag do not color anything.
21
+ */
22
+ const tqlCaptureTags = {
23
+ keyword: tags.keyword,
24
+ operator: tags.operator,
25
+ attribute: tags.attributeName,
26
+ function: tags.function(tags.variableName),
27
+ "function.call": tags.function(tags.variableName),
28
+ "function.method": tags.function(tags.propertyName),
29
+ string: tags.string,
30
+ "string.escape": tags.escape,
31
+ "string.special": tags.special(tags.string),
32
+ number: tags.number,
33
+ boolean: tags.bool,
34
+ constant: tags.constant(tags.name),
35
+ "constant.builtin": tags.null,
36
+ variable: tags.variableName,
37
+ "variable.builtin": tags.special(tags.variableName),
38
+ "variable.parameter": tags.local(tags.variableName),
39
+ property: tags.propertyName,
40
+ type: tags.typeName,
41
+ label: tags.labelName,
42
+ comment: tags.comment,
43
+ punctuation: tags.punctuation,
44
+ "punctuation.bracket": tags.bracket,
45
+ "punctuation.delimiter": tags.separator,
46
+ };
47
+ /** The entry of `table` for `capture` or the nearest capture it refines. */
48
+ const lookupCapture = (table, capture) => {
49
+ for (let name = capture;;) {
50
+ if (Object.prototype.hasOwnProperty.call(table, name))
51
+ return table[name];
52
+ const dot = name.lastIndexOf(".");
53
+ if (dot < 0)
54
+ return undefined;
55
+ name = name.slice(0, dot);
12
56
  }
13
- ignoreNewlines(value) {
14
- return new MyContext(this, Object.assign(Object.assign({}, this.data), { ignoreNewlines: value }));
57
+ };
58
+ /** The modifier that marks a tag as coming from a capture, by capture name. */
59
+ const modifiers = new Map();
60
+ /** The capture name of a tag that `captureTag` returned. */
61
+ const captureNames = new Map();
62
+ /**
63
+ * The tag of a capture, if it has one, with `tags` over the defaults. It is
64
+ * the capture's standard tag with a modifier for the capture, so standard
65
+ * highlighters fall back to the standard tag, while `tqlHighlighter` tells
66
+ * captures apart that share one.
67
+ */
68
+ const captureTag = (capture, tags = {}) => {
69
+ if (capture.startsWith("_"))
70
+ return undefined;
71
+ let tag = lookupCapture(tags, capture);
72
+ if (tag === undefined)
73
+ tag = lookupCapture(tqlCaptureTags, capture);
74
+ if (!tag)
75
+ return undefined;
76
+ let modifier = modifiers.get(capture);
77
+ if (modifier === undefined) {
78
+ modifier = Tag.defineModifier(`@${capture}`);
79
+ modifiers.set(capture, modifier);
15
80
  }
16
- justHadComma(value) {
17
- return new MyContext(this.parent, Object.assign(Object.assign({}, this.data), { justHadComma: value }));
81
+ const captured = modifier(tag);
82
+ captureNames.set(captured, capture);
83
+ return captured;
84
+ };
85
+ /**
86
+ * A highlighter that styles TQL by capture name, the way tree-sitter themes
87
+ * do: `classes` maps capture names to CSS classes, and a capture without an
88
+ * entry takes the class of the nearest capture it refines, so a `function`
89
+ * entry covers `function.call` and `function.method`. Unlike `tagHighlighter`,
90
+ * this does not fall back to a tag's parents, so `function.call` never takes
91
+ * the class of `variable`.
92
+ */
93
+ const tqlHighlighter = (classes) => {
94
+ return {
95
+ style: (styles) => {
96
+ let result = null;
97
+ for (const tag of styles) {
98
+ const capture = captureNames.get(tag);
99
+ const cls = capture === undefined ? undefined : lookupCapture(classes, capture);
100
+ if (cls)
101
+ result = result ? `${result} ${cls}` : cls;
102
+ }
103
+ return result;
104
+ },
105
+ };
106
+ };
107
+
108
+ /**
109
+ * The most nodes that one query covers: the descendants of a subtree queried
110
+ * at once, or the children among which sibling patterns match.
111
+ */
112
+ const QUERY_SIZE = 256;
113
+ /** The type id tree-sitter gives error nodes. */
114
+ const ERROR_TYPE = 0xffff;
115
+ const INDENT = 1;
116
+ const OUTDENT = 2;
117
+ const FOLD = 4;
118
+ const AUTO = 8;
119
+ const OPEN = 16;
120
+ const CLOSE = 32;
121
+ /** Flags that captures of the indent and fold queries set on a node. */
122
+ const captureFlags = {
123
+ indent: INDENT,
124
+ "indent.begin": INDENT,
125
+ outdent: OUTDENT,
126
+ "indent.end": OUTDENT,
127
+ "indent.branch": OUTDENT,
128
+ "indent.dedent": OUTDENT,
129
+ "indent.auto": AUTO,
130
+ fold: FOLD,
131
+ open: OPEN,
132
+ close: CLOSE,
133
+ };
134
+ /** The language that the injection query injects into a node. */
135
+ const injectionProp = new NodeProp();
136
+ /** Marks tokens that close an indented node, like a block's `}`. */
137
+ const outdentProp = new NodeProp({ deserialize: (x) => x === "true" });
138
+ /**
139
+ * Indents the lines inside a node one unit past the line it starts on, except
140
+ * for a line that starts with the token closing the node.
141
+ */
142
+ const indentInside = (cx) => {
143
+ const after = cx.textAfter;
144
+ const space = /^\s*/.exec(after)[0].length;
145
+ // A new line between brackets pushes the closing one onto a line of its
146
+ // own, where it is not part of the line's text anymore.
147
+ if (space === after.length)
148
+ return cx.baseIndent + cx.unit;
149
+ const at = cx.pos + space;
150
+ for (let child = cx.node.lastChild; child && child.to >= at; child = child.prevSibling) {
151
+ if (child.from === at && child.type.prop(outdentProp))
152
+ return cx.baseIndent;
153
+ }
154
+ return cx.baseIndent + cx.unit;
155
+ };
156
+ /**
157
+ * Leaves the indentation of a line that starts inside a node alone, so that a
158
+ * new line keeps the indentation of the line before, as `@indent.auto` does in
159
+ * nvim-treesitter. Elsewhere, the nodes around it decide.
160
+ */
161
+ const indentAuto = (cx) => cx.pos > cx.node.from && cx.pos < cx.node.to ? null : cx.continue();
162
+ /**
163
+ * Keeps the indentation of the line before at the top level, where TQL's
164
+ * statements and pipes all line up.
165
+ */
166
+ const indentTop = (cx) => cx.lineIndent(cx.pos, -1);
167
+ /**
168
+ * Folds between a node's brackets, or from the end of its first line to the
169
+ * start of its last line when that line holds only its closing token, like the
170
+ * fence of front matter.
171
+ */
172
+ const foldRange = (node, state) => {
173
+ const first = node.firstChild;
174
+ let last = node.lastChild;
175
+ if (!first || !last)
176
+ return null;
177
+ const from = first.type.prop(NodeProp.closedBy) ? first.to : state.doc.lineAt(node.from).to;
178
+ while (last.lastChild && last.lastChild.to === last.to)
179
+ last = last.lastChild;
180
+ let to = node.to;
181
+ if (last.type.prop(NodeProp.openedBy)) {
182
+ to = last.from;
183
+ }
184
+ else if (last.from > from && state.doc.lineAt(last.from).from === last.from) {
185
+ to = state.doc.lineAt(last.from - 1).to;
186
+ }
187
+ return to > from ? { from, to } : null;
188
+ };
189
+ /** Quotes a node name for `styleTags`, which splits selectors at spaces. */
190
+ const selector = (name) => JSON.stringify(name).replace(/ /g, "\\u0020");
191
+ /** How long one step of a parse may take before it yields, in milliseconds. */
192
+ const STEP_TIME = 4;
193
+ const now = () => performance.now();
194
+ /** Native handles only: this must not retain the parse or its generator. */
195
+ class ParseResources {
196
+ parser = null;
197
+ tree = null;
198
+ cursor = null;
199
+ delete() {
200
+ this.cursor?.delete();
201
+ this.tree?.delete();
202
+ this.parser?.delete();
203
+ this.cursor = this.tree = this.parser = null;
18
204
  }
19
205
  }
20
- const startContext = new MyContext(null, { ignoreNewlines: false, justHadComma: false });
21
- const context = new ContextTracker({
22
- start: startContext,
23
- reduce(context, term, stack, input) {
24
- return context;
25
- },
26
- shift(context, term, stack, input) {
27
- context = context.justHadComma(term === Comma);
28
- if (term === LParen || term == LBracket) {
29
- return context.ignoreNewlines(true);
206
+ /** The node types, captures, and queries of one TQL parser. */
207
+ class Grammar {
208
+ /** All queries in one, which runs faster. */
209
+ query;
210
+ /** Sibling patterns start one level below the parent that contains them. */
211
+ queryDepth;
212
+ /** The index of the first pattern that is not a highlight. */
213
+ #indents;
214
+ /** The tags of the captures that color, by index. */
215
+ tags = [];
216
+ /** The index of a coloring capture, by name. */
217
+ captures = new Map();
218
+ /** The tokens that a bracket pattern pairs, by pattern index. */
219
+ #pairs = new Map();
220
+ top;
221
+ types = new Map();
222
+ language;
223
+ Parser;
224
+ /** Handles stay enumerable for delete(), without retaining dropped parses. */
225
+ #pending = new Set();
226
+ #collected = new FinalizationRegistry((resources) => this.release(resources));
227
+ nextId = 1;
228
+ constructor(treeSitter, queries, data) {
229
+ const { Parser: TSParser, Query, language } = treeSitter;
230
+ this.language = language;
231
+ this.Parser = TSParser;
232
+ const highlights = new Query(language, queries.highlights);
233
+ // Owned here until the end, so that a failure frees it.
234
+ let query = null;
235
+ try {
236
+ this.#indents = highlights.patternCount();
237
+ for (const name of highlights.captureNames) {
238
+ const tag = captureTag(name, queries.tags);
239
+ if (tag && !this.captures.has(name)) {
240
+ this.captures.set(name, this.tags.length);
241
+ this.tags.push(tag);
242
+ }
243
+ }
244
+ const { indents, folds, brackets, injections } = queries;
245
+ query = new Query(language, [queries.highlights, indents, folds, brackets, injections].join("\n"));
246
+ const patterns = Array.from({ length: query.patternCount() }, (_, i) => i);
247
+ this.queryDepth = patterns.some((i) => !query.isPatternRooted(i)) ? 1 : 0;
248
+ this.query = query;
249
+ query = null;
250
+ }
251
+ finally {
252
+ highlights.delete();
253
+ query?.delete();
30
254
  }
31
- if (term === LBrace) {
32
- return context.ignoreNewlines(false);
255
+ this.top = NodeType.define({
256
+ id: 0,
257
+ name: language.name ?? "document",
258
+ top: true,
259
+ props: [
260
+ [languageDataProp, data],
261
+ [indentNodeProp, indentTop],
262
+ ],
263
+ });
264
+ }
265
+ /** CodeMirror drops parses without cancelling them. Never evict live ones. */
266
+ track(parse) {
267
+ const resources = new ParseResources();
268
+ this.#pending.add(resources);
269
+ this.#collected.register(parse, resources, resources);
270
+ return resources;
271
+ }
272
+ release(resources) {
273
+ this.#collected.unregister(resources);
274
+ this.#pending.delete(resources);
275
+ resources.delete();
276
+ }
277
+ /**
278
+ * Runs the queries on all of a small subtree at once. On a larger one, it
279
+ * runs the patterns that start at `node` and, unless it has too many
280
+ * children for one step, the sibling patterns among them. Returns whether
281
+ * the queries covered the whole subtree.
282
+ */
283
+ captureAt(node, captured) {
284
+ if (node.descendantCount <= QUERY_SIZE) {
285
+ this.capture(node, {}, captured);
286
+ return true;
33
287
  }
34
- if (term === RParen || term == RBrace || term == RBracket) {
35
- return context.parent;
288
+ const maxStartDepth = node.childCount <= QUERY_SIZE ? this.queryDepth : 0;
289
+ this.capture(node, { maxStartDepth }, captured);
290
+ return false;
291
+ }
292
+ /** Runs the queries on `node` and records what they capture on nodes. */
293
+ capture(node, options, captured) {
294
+ // Unlike captures, matches need not wait for earlier matches to finish,
295
+ // which would buffer all of a wide node behind its opening bracket.
296
+ for (const { patternIndex, captures, setProperties } of this.query.matches(node, options)) {
297
+ for (const { name, node: target } of captures) {
298
+ if (patternIndex >= this.#indents) {
299
+ const injection = name === "injection.content" && setProperties?.["injection.language"];
300
+ if (injection)
301
+ capturedAt(captured, target.id).injection = injection;
302
+ const flags = captureFlags[name];
303
+ if (!flags)
304
+ continue;
305
+ const entry = capturedAt(captured, target.id);
306
+ entry.flags |= flags;
307
+ if (flags & (OPEN | CLOSE)) {
308
+ // Each bracket pattern pairs one opening and one closing token.
309
+ let pair = this.#pairs.get(patternIndex);
310
+ if (pair === undefined)
311
+ this.#pairs.set(patternIndex, (pair = {}));
312
+ pair[name] = target.type;
313
+ entry.bracket = patternIndex;
314
+ }
315
+ continue;
316
+ }
317
+ const capture = this.captures.get(name);
318
+ if (capture === undefined)
319
+ continue;
320
+ const entry = capturedAt(captured, target.id);
321
+ // Of two captures of the same node, the later pattern wins.
322
+ if (entry.capture < 0 || patternIndex >= entry.pattern) {
323
+ entry.capture = capture;
324
+ entry.pattern = patternIndex;
325
+ }
326
+ }
36
327
  }
37
- return context;
38
328
  }
39
- });
40
- function code(x) {
41
- return x.charCodeAt(0);
42
- }
43
- const newlines = new ExternalTokenizer((input, stack) => {
44
- let ctx = stack.context.data;
45
- if (input.next == code("\n")) {
46
- let ignore = ctx.ignoreNewlines || ctx.justHadComma;
47
- input.acceptToken(ignore ? ignoredNewline : newline, 1);
48
- return;
49
- }
50
- }, { contextual: true });
51
- const identifiers = new ExternalTokenizer((input, stack) => {
52
- const a = code("a");
53
- const z = code("z");
54
- const A = code("A");
55
- const Z = code("Z");
56
- const u = code("_");
57
- const n0 = code("0");
58
- const n9 = code("9");
59
- const first = (n) => (a <= n && n <= z) || (A <= n && n <= Z) || (n == u);
60
- const rest = (n) => first(n) || (n0 <= n && n <= n9);
61
- let token = Ident;
62
- if (!first(input.peek(0))) {
63
- if (input.peek(0) != code("$")) {
64
- return;
329
+ /** The node type for a tree-sitter type with what the queries captured. */
330
+ type(typeId, name, capture, entry) {
331
+ const flags = entry?.flags ?? 0;
332
+ const pair = entry && this.#pairs.get(entry.bracket);
333
+ const partner = flags & OPEN ? pair?.close : flags & CLOSE ? pair?.open : undefined;
334
+ const injection = entry?.injection;
335
+ const key = `${typeId}:${capture}:${flags}:${partner ?? ""}:${injection ?? ""}`;
336
+ let type = this.types.get(key);
337
+ if (type === undefined) {
338
+ const error = typeId === ERROR_TYPE;
339
+ const typeName = error ? "⚠" : name();
340
+ const props = [];
341
+ if (partner && flags & OPEN)
342
+ props.push([NodeProp.closedBy, [partner]]);
343
+ if (partner && flags & CLOSE)
344
+ props.push([NodeProp.openedBy, [partner]]);
345
+ if (capture >= 0)
346
+ props.push(styleTags({ [selector(typeName)]: this.tags[capture] }));
347
+ if (flags & INDENT)
348
+ props.push([indentNodeProp, indentInside]);
349
+ else if (flags & AUTO)
350
+ props.push([indentNodeProp, indentAuto]);
351
+ if (flags & OUTDENT)
352
+ props.push([outdentProp, true]);
353
+ if (flags & FOLD)
354
+ props.push([foldNodeProp, foldRange]);
355
+ if (injection)
356
+ props.push([injectionProp, injection]);
357
+ type = NodeType.define({ id: this.nextId++, name: typeName, error, props });
358
+ this.types.set(key, type);
65
359
  }
66
- token = DollarIdent;
360
+ return type;
361
+ }
362
+ delete() {
363
+ for (const resources of this.#pending)
364
+ this.release(resources);
365
+ this.query.delete();
67
366
  }
68
- let n = 1;
69
- while (rest(input.peek(n))) {
70
- n += 1;
367
+ }
368
+ const capturedAt = (captured, id) => {
369
+ let entry = captured.get(id);
370
+ if (entry === undefined) {
371
+ entry = { capture: -1, pattern: -1, flags: 0, bracket: -1 };
372
+ captured.set(id, entry);
71
373
  }
72
- if (input.peek(n) == code("(")) {
73
- token = FnIdent;
374
+ return entry;
375
+ };
376
+ /**
377
+ * The text from the first range's start to the last range's end, or to
378
+ * `end`, with the gaps between ranges, which belong to another language,
379
+ * blanked out.
380
+ */
381
+ const readRanges = (input, ranges, end = Infinity) => {
382
+ if (ranges.length === 0)
383
+ return input.read(0, Math.min(input.length, end));
384
+ let text = "";
385
+ for (let i = 0; i < ranges.length && ranges[i].from < end; i++) {
386
+ if (i > 0)
387
+ text += " ".repeat(ranges[i].from - ranges[i - 1].to);
388
+ text += input.read(ranges[i].from, Math.min(ranges[i].to, end));
74
389
  }
75
- input.acceptToken(token, n);
76
- });
390
+ return text;
391
+ };
392
+ /**
393
+ * A Lezer parser that parses TQL with tree-sitter-tql and converts the result
394
+ * into a Lezer tree, so that CodeMirror's highlighting, bracket matching,
395
+ * indentation, folding, and commands work from TQL's tree-sitter grammar.
396
+ *
397
+ * Every parse parses the whole document, or the part before where CodeMirror
398
+ * asks it to stop, in steps targeting a few milliseconds. Native parsers and
399
+ * trees are freed when their work finishes. `delete()` frees the combined
400
+ * query and any unfinished parses; afterwards, this parser must not be used.
401
+ */
402
+ class TqlParser extends Parser {
403
+ #grammar;
404
+ #wrapper;
405
+ /** @internal */
406
+ constructor(treeSitter, queries, data, wrapper) {
407
+ super();
408
+ this.#grammar = new Grammar(treeSitter, queries, data);
409
+ this.#wrapper = wrapper;
410
+ }
411
+ createParse(input, fragments, ranges) {
412
+ const from = ranges.length ? ranges[0].from : 0;
413
+ const parse = new TqlParse(this.#grammar, input, ranges, from);
414
+ return this.#wrapper ? this.#wrapper(parse, input, fragments, ranges) : parse;
415
+ }
416
+ /** Frees the combined query and the native handles of unfinished parses. */
417
+ delete() {
418
+ this.#grammar.delete();
419
+ }
420
+ }
421
+ /**
422
+ * The generator keeps local parse state across bounded advances. Its finally
423
+ * block frees native handles on completion or errors; Grammar also owns those
424
+ * handles for explicit deletion and finalization of abandoned parses.
425
+ */
426
+ class TqlParse {
427
+ grammar;
428
+ input;
429
+ ranges;
430
+ from;
431
+ stoppedAt = null;
432
+ parsedPos;
433
+ #deadline = 0;
434
+ #work = null;
435
+ #result = null;
436
+ constructor(grammar, input, ranges, from) {
437
+ this.grammar = grammar;
438
+ this.input = input;
439
+ this.ranges = ranges;
440
+ this.from = from;
441
+ this.parsedPos = from;
442
+ }
443
+ stopAt(pos) {
444
+ this.stoppedAt = pos;
445
+ }
446
+ advance() {
447
+ if (this.#result)
448
+ return this.#result;
449
+ if (!this.#work)
450
+ this.#work = this.run();
451
+ this.#deadline = now() + STEP_TIME;
452
+ const step = this.#work.next();
453
+ if (!step.done)
454
+ return null;
455
+ this.#work = null;
456
+ return (this.#result = step.value);
457
+ }
458
+ *run() {
459
+ const grammar = this.grammar;
460
+ const resources = grammar.track(this);
461
+ let text = "";
462
+ let parser = null;
463
+ let tree = null;
464
+ let cursor = null;
465
+ try {
466
+ text = readRanges(this.input, this.ranges, this.stoppedAt ?? Infinity);
467
+ parser = resources.parser = new grammar.Parser();
468
+ parser.setLanguage(grammar.language);
469
+ while (!tree) {
470
+ if (this.stoppedAt !== null && this.stoppedAt <= this.from)
471
+ return new Tree(grammar.top, [], [], 0);
472
+ let interrupted = false;
473
+ tree = resources.tree = parser.parse(text, null, {
474
+ progressCallback: () => (interrupted = now() > this.#deadline),
475
+ });
476
+ if (!tree) {
477
+ if (!interrupted)
478
+ throw new Error("tree-sitter did not parse");
479
+ yield;
480
+ }
481
+ }
482
+ parser.delete();
483
+ parser = resources.parser = null;
484
+ const captured = new Map();
485
+ // The depth up to which nodes are queried as the walk enters them.
486
+ let queriedDepth = Infinity;
487
+ // The root of the tree-sitter tree, error or not, goes below the top.
488
+ cursor = resources.cursor = tree.walk();
489
+ const frames = [{
490
+ type: grammar.top,
491
+ from: 0,
492
+ to: text.length,
493
+ capture: -1,
494
+ children: [],
495
+ positions: [],
496
+ }];
497
+ const add = (node, from) => {
498
+ const parent = frames[frames.length - 1];
499
+ parent.children.push(node);
500
+ parent.positions.push(from - parent.from);
501
+ };
502
+ const close = (end) => {
503
+ const frame = frames.pop();
504
+ add(new Tree(frame.type, frame.children, frame.positions, (end ?? frame.to) - frame.from), frame.from);
505
+ };
506
+ let exhausted = false;
507
+ let end = text.length;
508
+ for (let steps = 0; !exhausted; steps++) {
509
+ const from = cursor.startIndex;
510
+ this.parsedPos = this.from + from;
511
+ if ((steps & 15) === 0 && now() > this.#deadline)
512
+ yield;
513
+ if (this.stoppedAt !== null && this.parsedPos >= this.stoppedAt) {
514
+ end = from;
515
+ break;
516
+ }
517
+ if (cursor.nodeIsMissing) {
518
+ add(new Tree(grammar.type(ERROR_TYPE, () => "⚠", -1), [], [], 0), from);
519
+ }
520
+ else {
521
+ // Query small subtrees once. For larger ones, query the node, then
522
+ // visit its children.
523
+ if (frames.length <= queriedDepth) {
524
+ queriedDepth = grammar.captureAt(cursor.currentNode, captured) ? frames.length : Infinity;
525
+ }
526
+ const entry = captured.get(cursor.nodeId);
527
+ const parent = frames[frames.length - 1];
528
+ // Uncolored descendants inherit the enclosing capture.
529
+ const capture = entry && entry.capture >= 0 ? entry.capture : parent.capture;
530
+ const type = grammar.type(cursor.nodeTypeId, () => cursor.nodeType, capture, entry);
531
+ const to = cursor.endIndex;
532
+ if (cursor.gotoFirstChild()) {
533
+ frames.push({ type, from, to, capture, children: [], positions: [] });
534
+ continue;
535
+ }
536
+ add(new Tree(type, [], [], to - from), from);
537
+ }
538
+ while (!cursor.gotoNextSibling()) {
539
+ if (frames.length === 1) {
540
+ exhausted = true;
541
+ break;
542
+ }
543
+ close();
544
+ cursor.gotoParent();
545
+ }
546
+ }
547
+ while (frames.length > 1)
548
+ close(end);
549
+ const top = frames[0];
550
+ const result = new Tree(top.type, top.children, top.positions, end);
551
+ this.parsedPos = this.from + end;
552
+ cursor.delete();
553
+ cursor = resources.cursor = null;
554
+ tree.delete();
555
+ tree = resources.tree = null;
556
+ return result;
557
+ }
558
+ catch (error) {
559
+ console.error("Failed to parse TQL", error);
560
+ this.parsedPos = this.from + text.length;
561
+ return new Tree(grammar.top, [], [], text.length);
562
+ }
563
+ finally {
564
+ grammar.release(resources);
565
+ }
566
+ }
567
+ }
77
568
 
78
- // This file was generated by lezer-generator. You probably shouldn't edit it.
79
- const spec_Ident = {__proto__:null,move:20, and:74, else:76, false:78, if:80, in:82, let:84, match:86, meta:88, not:90, null:92, or:94, this:96, true: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!hrO!pSO!g!oi!U!oi~OP|Og|Of!]i~OP!jO~PcOi!kO~P!VO!U!lO~O!Z!SO!w!nO!x!SO~O!w!pO!{!VO~O#O!YO#P!rO~O!U!tO~P+wO!hrO!pSO!g!oq!U!oq~Oi!vO~P!VO!hrO!pSO!g!oy!U!oy~OSd~",
84
- goto: "'i!}PPPPP#OP#R#i#tP$PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP$YPP$b$j$Y$YP#i$m$x%O%b%j%p%v%|&S&YPPPPPPPP&lP&r'V$YP$Y'aPP'aPP'aR`PSZOfScR!O`rYbsy{!g!h!uT!]l!^cXORZcfrtz!OcUORZcfrtz!OQoUQu^R!bq]kU^lnq!^]lU^lnq!^R!`lcWORZcfrtz!OQw_R!ewQROWaRtz!OQtZQzcR!OfUnU^qR!anQ!^lR!s!^Q!TgR!m!TQ!WhR!o!WQ!ZiR!q!ZQ}dR!i}QsYQybW!dsy!h!uQ!h{R!u!gQ[OR!RfSYOfUbRZ!OS{ctQ!crR!gzWmU^nqT!]l!^]jU^lnq!^",
85
- nodeNames: "⚠ Ident FnIdent DollarIdent LineComment BlockComment Pipeline Pipe OpStmt OpName move Soup Scalar [ ] ( ) + - * / , = . ' : ! ? < > @ % & # ; ^ ` and else false if in let match meta not null or this true EmptyRecord { } RecordStart RecordRest PipeExpr String StringEsc AssignStmt UnExpr",
86
- maxTerm: 93,
87
- context: context,
88
- skippedNodes: [0,4,5,60],
89
- repeatNodeCount: 9,
90
- tokenData: "FgnR}OX$OXY%sY[$O[]%s]p$Opq%sqr)_rs)|st*]tu$Ouv*zvw+iwx,Wxy,uyz-dz{.R{|.p|}/_}!O/|!O!P0k!P!Q1Y!Q![5W![!]8u!]!^:V!^!_:t!_!`;c!`!a<Q!a!b<o!b!c=^!c!}$O!}#O={#O#P>j#P#QAQ#Q#RAo#R#S$O#S#TB^#T#f$O#f#gB{#g#o$O#o#pDf#p#qET#q#rEr#r;'S$O;'S;=`Fa<%lO$Ol$X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P%U#P;'S$k;'S;=`%m<%lO$kn=iUnQ!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$kn>WU]Q!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$kn>qY!{W#O`OY?aYZ?tZ]?a]^?t^r?ars@ss;'S?a;'S;=`@x;=`<%l@s<%lO?a[?hS!ZS!{WOr%Us;'S%U;'S;=`%g<%lO%U^?}[!ZS!{W!kQOX%UXY(bY[%U[](b]p%Upq(bqr%Us#O%U#O#P's#P;'S%U;'S;=`%g<%lO%US@xO!ZS[@}P!ZS;=`<%l?anA]U^Q!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$knAzUsQ!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$knBiUtQ!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$knCUW!{W#O`!xSOr$krsCnstCst#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$kQCsO!zQ^CzV!{W!xSOr$krsDas#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$kQDfO!}QnDqU!TQ!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$knE`U!pQ!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$knE}U!UQ!{W#O`!xSOr$ks#O$k#O#P%U#P;'S$k;'S;=`%m<%lO$klFdP;=`<%l$O",
91
- tokenizers: [1, 2, 3, 4, newlines, identifiers, new LocalTokenGroup("b~RPz{U~XP!P!Q[~aO!n~~", 17, 75)],
92
- topRules: {"Pipeline":[0,6]},
93
- dynamicPrecedences: {"53":2,"58":1},
94
- specialized: [{term: 1, get: value => spec_Ident[value] || -1}],
95
- tokenPrec: 977
569
+ /** The queries of tree-sitter-tql that `tql` uses unless given others. */
570
+ const tqlQueries = { highlights, indents, folds, brackets, injections };
571
+ const rawPrefixes = ["r", "br"].flatMap((prefix) => {
572
+ return Array.from({ length: 9 }, (_, hashes) => prefix + "#".repeat(hashes));
96
573
  });
97
-
98
- const punctuation = `"+" "-" "*" "/" "=" "." "'" ":" "!" "?" "<" ">" "@" "%" "&" "#" ";" "^" "\`"`;
99
- const TenzirQueryLang = LRLanguage.define({
100
- languageData: {
574
+ /**
575
+ * TQL language support for CodeMirror from tree-sitter-tql: highlighting,
576
+ * bracket matching, quote pairing, indentation, folding, and comment
577
+ * toggling.
578
+ *
579
+ * Takes web-tree-sitter's classes and the grammar the host loaded, after
580
+ * `Parser.init()` and `Language.load()`, so the host decides where the
581
+ * WebAssembly comes from and when it loads. Each parse owns a native parser
582
+ * and tree and frees them when its work finishes. The language owns the
583
+ * combined query, which lives in WebAssembly memory until
584
+ * `(support.language.parser as TqlParser).delete()` frees it along with any
585
+ * unfinished parses, so create the language once and share it between
586
+ * editors.
587
+ */
588
+ function tql(treeSitter, options = {}) {
589
+ const data = defineLanguageFacet({
101
590
  commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
102
- },
103
- parser: parser.configure({
104
- props: [
105
- styleTags({
106
- "Scalar true false null DollarIdent": tags.literal,
107
- String: tags.string,
108
- "StringEsc and else if in let match meta not or this move": tags.keyword,
109
- "OpName! FnIdent": tags.name,
110
- [punctuation]: tags.punctuation,
111
- "LineComment BlockComment": tags.comment,
112
- }),
113
- ],
114
- // TODO: add folding later
115
- }),
116
- });
117
- function TQL() {
118
- return new LanguageSupport(TenzirQueryLang);
591
+ closeBrackets: {
592
+ // Raw strings take up to 8 hashes, as in tree-sitter-tql.
593
+ stringPrefixes: ["f", "b", ...rawPrefixes],
594
+ },
595
+ indentOnInput: /^\s*[}\]]$/,
596
+ });
597
+ const nested = options.nested;
598
+ const wrapper = nested
599
+ ? parseMixed((node) => {
600
+ const name = node.type.prop(injectionProp);
601
+ const parser = name !== undefined && Object.hasOwn(nested, name) ? nested[name] : undefined;
602
+ return parser ? { parser } : null;
603
+ })
604
+ : undefined;
605
+ const parser = new TqlParser(treeSitter, {
606
+ highlights: options.highlights ?? highlights,
607
+ indents: options.indents ?? indents,
608
+ folds: options.folds ?? folds,
609
+ brackets: options.brackets ?? brackets,
610
+ injections: options.injections ?? injections,
611
+ tags: options.tags ?? {},
612
+ }, data, wrapper);
613
+ return new LanguageSupport(new Language(data, parser, [], "tql"));
614
+ }
615
+ let initialized;
616
+ /**
617
+ * Imports web-tree-sitter on demand, initializes it unless that happened
618
+ * already, loads the grammar, and returns `tql()` for it.
619
+ */
620
+ async function loadTql(options) {
621
+ const { Language: TreeSitterLanguage, Parser: TreeSitterParser, Query } = await import('web-tree-sitter');
622
+ initialized ??= (async () => {
623
+ try {
624
+ // Initializing again would replace the runtime under the grammars that
625
+ // the host loaded already, so only initialize what cannot parse yet.
626
+ new TreeSitterParser().delete();
627
+ }
628
+ catch {
629
+ const url = options.runtimeWasmUrl;
630
+ await TreeSitterParser.init(url === undefined ? undefined : { locateFile: () => url });
631
+ }
632
+ })().catch((error) => {
633
+ initialized = undefined;
634
+ throw error;
635
+ });
636
+ await initialized;
637
+ const language = await TreeSitterLanguage.load(options.grammarWasmUrl);
638
+ return tql({ Parser: TreeSitterParser, Query, language }, options);
119
639
  }
120
640
 
121
- export { TQL, TenzirQueryLang };
641
+ export { TqlParser, loadTql, tql, tqlCaptureTags, tqlHighlighter, tqlQueries };