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