@tenzir/codemirror-lang-tql 0.4.8 → 0.5.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
+ The MIT License (MIT)
2
+
3
+ Copyright © 2023 Tenzir GmbH
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 to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ 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, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
18
+ OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
package/README.md CHANGED
@@ -1,15 +1,349 @@
1
- # CodeMirror 6 language package for Tenzir Query Language (TQL)
1
+ # @tenzir/codemirror-lang-tql
2
2
 
3
- ### Generating the docs (horribly WIP)
3
+ [Tenzir Query Language (TQL)](https://docs.tenzir.com/explanations/language) support for
4
+ [CodeMirror 6](https://codemirror.net), backed by
5
+ [tree-sitter-tql](https://github.com/tenzir/tree-sitter-tql), the grammar that
6
+ Zed, VS Code, and Neovim use as well.
4
7
 
5
- #### Codegen
8
+ The package parses TQL with tree-sitter through
9
+ [web-tree-sitter](https://www.npmjs.com/package/web-tree-sitter) and converts
10
+ every tree-sitter tree into a Lezer tree, so all of CodeMirror works from the
11
+ one grammar:
6
12
 
7
- ```fish
8
- node scripts/index.js ~/code/tenzir/tenzir/web/docs/operators/ output.js
13
+ - Highlighting from tree-sitter-tql's `highlights.scm`, as standard
14
+ `@lezer/highlight` tags
15
+ - Bracket matching and quote pairing that skip strings and comments, including
16
+ strings that are not closed yet
17
+ - Indentation from `indents.scm`, folding from `folds.scm`, bracket pairs from
18
+ `brackets.scm`
19
+ - Comment toggling
20
+ - Nested languages from `injections.scm`, such as YAML in front matter
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ pnpm add @tenzir/codemirror-lang-tql web-tree-sitter tree-sitter-tql
26
+ ```
27
+
28
+ `web-tree-sitter`, `@codemirror/language`, `@lezer/common`, and
29
+ `@lezer/highlight` are peer dependencies. `tree-sitter-tql` provides the
30
+ grammar's WebAssembly; its queries ship inside this package.
31
+
32
+ ## Usage
33
+
34
+ Tree-sitter runs as WebAssembly, which loads asynchronously, and the host
35
+ decides where it comes from. Load web-tree-sitter and the grammar, then pass
36
+ both to `tql()`:
37
+
38
+ ```ts
39
+ import { syntaxHighlighting } from "@codemirror/language";
40
+ import { EditorView, basicSetup } from "codemirror";
41
+ import { tql, tqlHighlighter } from "@tenzir/codemirror-lang-tql";
42
+ import grammarWasmUrl from "tree-sitter-tql/tree-sitter-tql.wasm?url";
43
+ import runtimeWasmUrl from "web-tree-sitter/web-tree-sitter.wasm?url";
44
+
45
+ // Import web-tree-sitter on demand to keep it out of the main chunk.
46
+ const { Language, Parser, Query } = await import("web-tree-sitter");
47
+ await Parser.init({ locateFile: () => runtimeWasmUrl });
48
+ const language = await Language.load(grammarWasmUrl);
49
+
50
+ // Create the language once and share it between editors.
51
+ const tqlSupport = tql({ Parser, Query, language });
52
+
53
+ new EditorView({
54
+ parent: document.body,
55
+ doc: 'from "events.json" | where severity == "high"',
56
+ extensions: [
57
+ basicSetup,
58
+ tqlSupport,
59
+ syntaxHighlighting(
60
+ tqlHighlighter({
61
+ keyword: "text-red",
62
+ operator: "text-red",
63
+ attribute: "text-red",
64
+ function: "text-purple",
65
+ string: "text-blue",
66
+ number: "text-blue",
67
+ boolean: "text-blue",
68
+ constant: "text-blue",
69
+ variable: "text-blue",
70
+ comment: "text-gray",
71
+ }),
72
+ ),
73
+ ],
74
+ });
75
+ ```
76
+
77
+ `tql()` takes web-tree-sitter's classes from the host rather than importing
78
+ them, so the package never loads web-tree-sitter by itself, and the parser
79
+ always comes from the same web-tree-sitter instance as the grammar.
80
+
81
+ If you don't need control over loading, `loadTql()` does all of the above:
82
+
83
+ ```ts
84
+ import { loadTql } from "@tenzir/codemirror-lang-tql";
85
+
86
+ const tqlSupport = await loadTql({ runtimeWasmUrl, grammarWasmUrl });
87
+ ```
88
+
89
+ It imports web-tree-sitter on demand and only initializes it when nothing
90
+ initialized it before, since initializing it again would invalidate grammars
91
+ that the host loaded already.
92
+
93
+ ## Migrating from 0.4
94
+
95
+ 0.5 replaces the hand-written Lezer grammar with tree-sitter-tql, which loads
96
+ asynchronously:
97
+
98
+ - `TQL()` and `TenzirQueryLang` are gone. Create the language support once with
99
+ `await loadTql({ runtimeWasmUrl, grammarWasmUrl })`, or load web-tree-sitter
100
+ yourself and call `tql({ Parser, Query, language })`, and share it between
101
+ editors. Until it has loaded, editors can run without it.
102
+ - Instead of `TenzirQueryLang.parser`, use `support.language.parser`, for
103
+ example to highlight read-only views with `highlightTree`. It only exists
104
+ once the grammar loaded.
105
+ - Highlighting uses the tags of the [capture mapping](#highlighting) instead
106
+ of the coarse tags of 0.4. A `HighlightStyle` for those still matches most
107
+ nodes, since functions and attributes fall back to `name` and numbers and
108
+ booleans to `literal`, but operators are now `operator` rather than
109
+ `punctuation`, `null` falls back to `keyword` rather than `literal`, and `$`
110
+ variables to `name`. Check your style, or style by capture name with
111
+ `tqlHighlighter(classes)`.
112
+ - Install `web-tree-sitter` and `tree-sitter-tql` and serve their `.wasm`
113
+ files, for example with Vite's `?url` imports.
114
+ - Front matter now parses, and its fences highlight as comments. To edit its
115
+ body as YAML, pass `nested: { yaml: yamlLanguage.parser }`, as shown under
116
+ [Front matter](#front-matter).
117
+
118
+ ## API
119
+
120
+ ```ts
121
+ function tql(treeSitter: TqlTreeSitter, options?: TqlOptions): LanguageSupport;
122
+
123
+ function loadTql(options: LoadTqlOptions): Promise<LanguageSupport>;
124
+
125
+ function tqlHighlighter(classes: Readonly<Record<string, string>>): Highlighter;
126
+
127
+ const tqlCaptureTags: Readonly<Record<string, Tag>>;
128
+
129
+ const tqlQueries: {
130
+ highlights: string;
131
+ indents: string;
132
+ folds: string;
133
+ brackets: string;
134
+ injections: string;
135
+ };
136
+
137
+ // The type of `support.language.parser`.
138
+ class TqlParser extends Parser {
139
+ delete(): void; // frees the combined query and unfinished parses
140
+ }
141
+
142
+ interface TqlTreeSitter {
143
+ Parser: typeof import("web-tree-sitter").Parser; // after Parser.init()
144
+ Query: typeof import("web-tree-sitter").Query;
145
+ language: import("web-tree-sitter").Language;
146
+ }
147
+
148
+ interface TqlOptions {
149
+ highlights?: string; // highlight query, tree-sitter-tql's by default
150
+ indents?: string; // indent query, tree-sitter-tql's by default
151
+ folds?: string; // fold query, tree-sitter-tql's by default
152
+ brackets?: string; // bracket query, tree-sitter-tql's by default
153
+ injections?: string; // injection query, tree-sitter-tql's by default
154
+ tags?: TqlCaptureTags; // capture tags over the defaults
155
+ nested?: Readonly<Record<string, Parser>>; // parsers by injected language
156
+ }
157
+
158
+ interface LoadTqlOptions extends TqlOptions {
159
+ runtimeWasmUrl?: string; // web-tree-sitter.wasm
160
+ grammarWasmUrl: string; // tree-sitter-tql.wasm
161
+ }
162
+
163
+ type TqlCaptureTags = Readonly<Record<string, Tag | null>>;
9
164
  ```
10
165
 
11
- #### Format ugly js
166
+ ## Highlighting
12
167
 
13
- ```fish
14
- prettier --write output.js
168
+ The highlight query's captures become these tags (`tqlCaptureTags`):
169
+
170
+ | Capture | Tag |
171
+ | ----------------------- | ---------------------------------- |
172
+ | `keyword` | `tags.keyword` |
173
+ | `operator` | `tags.operator` |
174
+ | `attribute` | `tags.attributeName` |
175
+ | `function` | `tags.function(tags.variableName)` |
176
+ | `function.call` | `tags.function(tags.variableName)` |
177
+ | `function.operator` | `tags.function(tags.variableName)` |
178
+ | `function.method` | `tags.function(tags.propertyName)` |
179
+ | `string` | `tags.string` |
180
+ | `string.escape` | `tags.escape` |
181
+ | `string.special` | `tags.special(tags.string)` |
182
+ | `number` | `tags.number` |
183
+ | `number.time` | `tags.number` |
184
+ | `number.duration` | `tags.number` |
185
+ | `boolean` | `tags.bool` |
186
+ | `constant` | `tags.constant(tags.name)` |
187
+ | `constant.ip` | `tags.constant(tags.name)` |
188
+ | `constant.subnet` | `tags.constant(tags.name)` |
189
+ | `constant.builtin` | `tags.null` |
190
+ | `variable` | `tags.variableName` |
191
+ | `variable.builtin` | `tags.special(tags.variableName)` |
192
+ | `variable.parameter` | `tags.local(tags.variableName)` |
193
+ | `property` | `tags.propertyName` |
194
+ | `type` | `tags.typeName` |
195
+ | `label` | `tags.labelName` |
196
+ | `comment` | `tags.comment` |
197
+ | `punctuation` | `tags.punctuation` |
198
+ | `punctuation.bracket` | `tags.bracket` |
199
+ | `punctuation.delimiter` | `tags.separator` |
200
+
201
+ A capture without an entry takes the tag of the nearest capture it refines, so
202
+ `function.builtin` would be a `function`. Pipeline operators (`function.operator`),
203
+ times and durations (`number.time`, `number.duration`), and IP addresses and
204
+ subnets (`constant.ip`, `constant.subnet`) share the tags of the captures they
205
+ refine, so standard highlight styles color them as before, while
206
+ `tqlHighlighter` can color them apart by capture name. Captures starting with `_` never
207
+ color.
208
+
209
+ Captures follow tree-sitter's rules: an inner node's capture wins over the
210
+ capture of a node around it, such as the braces of a replacement in a format
211
+ string, and of two captures of the same node, the later pattern wins. Nodes
212
+ inside a captured node without a capture of their own take its tag, so a whole
213
+ format string is a string except where its parts say otherwise.
214
+
215
+ A node's tag is the tag of its capture with a modifier naming the capture,
216
+ so captures that share a tag, like `function` and `function.call`, stay
217
+ distinct. Any `@lezer/highlight` highlighter works, like `HighlightStyle` or
218
+ `classHighlighter`, and falls back to the tags in the table.
219
+ `tqlHighlighter(classes)` styles by capture name instead, the way tree-sitter
220
+ themes do: `classes` maps a capture to a CSS class, and an entry also covers the
221
+ captures that refine it, so `function` covers `function.call` and
222
+ `function.method` unless they have entries of their own. Unlike
223
+ `tagHighlighter`, it does not fall back from a tag to its parents.
224
+
225
+ A tree-sitter theme that leaves a capture unstyled shows the color of the node
226
+ around it, such as the parentheses of a call inside a format string. To do the
227
+ same, map such captures to `null`:
228
+
229
+ ```ts
230
+ const extensions = [
231
+ tql({ Parser, Query, language }, { tags: { punctuation: null } }),
232
+ syntaxHighlighting(tqlHighlighter(classes)),
233
+ ];
234
+ ```
235
+
236
+ ## Editing
237
+
238
+ - **Quote pairing:** `closeBrackets()` pairs `(`, `[`, `{`, `"`, and `'`, also
239
+ after the string prefixes `f` and `b`, and the raw prefixes `r` and `br`
240
+ with up to 8 `#`. tree-sitter-tql parses a string without its closing quote
241
+ as a string that runs to the end of the document, as TQL's strings may span
242
+ lines, so typing the closing quote doesn't insert a pair. The same goes for a
243
+ `/*` comment without its `*/`.
244
+ - **Bracket matching:** the tokens that `brackets.scm` pairs as `@open` and
245
+ `@close` (`( )`, `[ ]`, and `{ }`) match in the tree, so brackets in strings
246
+ and comments don't count.
247
+ - **Indentation:** lines inside the nodes that `indents.scm` captures as
248
+ `@indent` (blocks, pipelines, records, lists, match arms) are indented one
249
+ unit past the line where the node starts, and a line starting with an
250
+ `@outdent` token (`}` and `]`) lines up with that line. A line that starts
251
+ inside a node captured as `@indent.auto` (strings, the text of format
252
+ strings, comments, and the body of front matter) keeps its indentation, so a
253
+ new line there takes the indentation of the line before, as in
254
+ nvim-treesitter. At the top level, a new line keeps the indentation of the
255
+ line before, too. `indentOnInput()` reindents a line once you type its
256
+ closing bracket.
257
+ - **Folding:** the nodes that `folds.scm` captures as `@fold` fold between
258
+ their `@open` and `@close` brackets, and front matter between its fences.
259
+ - **Comments:** `//` for lines and `/* */` for blocks.
260
+
261
+ ## Front matter
262
+
263
+ TQL files may start with YAML front matter between `---` fences. The fences
264
+ highlight as comments. tree-sitter-tql's `injections.scm` injects the `yaml`
265
+ language into the body, and `nested` maps an injected language to the parser
266
+ that parses it. To edit the body as YAML, pass the parser of
267
+ `@codemirror/lang-yaml`'s language, which brings YAML's highlighting,
268
+ indentation, and `#` comments:
269
+
270
+ ```ts
271
+ import { yamlLanguage } from "@codemirror/lang-yaml";
272
+
273
+ const tqlSupport = tql({ Parser, Query, language }, { nested: { yaml: yamlLanguage.parser } });
15
274
  ```
275
+
276
+ The bare parser of `@lezer/yaml` only highlights the body. A language without
277
+ a parser in `nested` stays part of the TQL tree. The bridge reads the language
278
+ from `#set! injection.language`, not from `@injection.language` captures.
279
+
280
+ ## Lifetime and performance
281
+
282
+ Each parse runs tree-sitter on the document, or the prefix where CodeMirror
283
+ asks it to stop, without reusing an earlier tree. A generator yields between
284
+ steps targeting 4 ms, so CodeMirror can continue parsing in the background.
285
+ The queries run combined into one, on subtrees of up to 256 nodes; larger
286
+ subtrees are queried one level at a time instead of repeatedly querying their
287
+ enclosing nodes. Sibling patterns, like the bracket pairs of `brackets.scm`,
288
+ only match among the children of nodes with up to 256 children. A list of
289
+ thousands of items thus keeps each step short, but its own brackets lose their
290
+ bracket props: they still match by name, and the list folds by lines, like
291
+ front matter, rather than between its brackets.
292
+
293
+ Each parse owns its native parser and tree and frees them as soon as their
294
+ work finishes, also on errors. CodeMirror has no cancellation hook for parses
295
+ it drops, so a finalizer frees an abandoned parse's native handles once the
296
+ parse is garbage-collected. Active parses are never evicted, including when
297
+ several editors share the language. To free the combined query and all
298
+ unfinished parses immediately, without waiting for garbage collection, use:
299
+
300
+ ```ts
301
+ import type { TqlParser } from "@tenzir/codemirror-lang-tql";
302
+
303
+ (tqlSupport.language.parser as TqlParser).delete();
304
+ ```
305
+
306
+ Afterwards, editors must not use the language anymore. Since the language is
307
+ meant to be created once per page, most hosts never need to free it.
308
+
309
+ The Lezer tree also serves views without an editor:
310
+
311
+ ```ts
312
+ import { highlightTree } from "@lezer/highlight";
313
+
314
+ const tree = tqlSupport.language.parser.parse(text);
315
+ highlightTree(tree, highlighter, (from, to, classes) => { /* … */ });
316
+ ```
317
+
318
+ ## Limitations
319
+
320
+ - The bundled queries come from tree-sitter-tql 1.3.0 (`tqlQueries`). A query
321
+ that names a node type the loaded grammar lacks does not compile, and `tql()`
322
+ throws. With a different version of the grammar, pass its queries as
323
+ `highlights`, `indents`, `folds`, `brackets`, and `injections`, for example
324
+ as Vite `?raw` imports.
325
+ - A new line at the very end of the document indents by the nodes around the
326
+ cursor, even right after a string or `/*` comment that is not closed yet.
327
+ CodeMirror only asks the nodes that a position lies inside of, and the end
328
+ of the document lies inside none. Inside a block, such a line takes the
329
+ block's indentation instead of the indentation of the line before.
330
+ - A nested parse over several ranges sees the gaps between them as spaces, so
331
+ a token cannot continue across a gap.
332
+ - Around syntax errors, tree-sitter may recover differently when it resumes a
333
+ parse that yielded than when it parses the whole document at once.
334
+ - The 4 ms target is not a hard deadline. Custom queries that match many
335
+ descendants, large individual tokens, freeing the native tree of a document
336
+ with a million nodes, and garbage collection can make a step take longer.
337
+ - Cleanup of abandoned parses depends on garbage collection and is not
338
+ immediate. Call `delete()` when retiring the language to free all native
339
+ handles deterministically.
340
+
341
+ ## Development
342
+
343
+ ```sh
344
+ pnpm install
345
+ pnpm build
346
+ pnpm test
347
+ ```
348
+
349
+ The tests load the real grammar from `node_modules`.