@compmd/lezer 0.1.0 → 0.2.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/README.md CHANGED
@@ -10,6 +10,15 @@ import { compmd } from "@compmd/lezer";
10
10
  const language = markdown({ base: markdownLanguage, extensions: [compmd] });
11
11
  ```
12
12
 
13
+ A text that is one expression, not a document (a formula), has a parser of its own:
14
+
15
+ ```ts
16
+ import { Language, defineLanguageFacet } from "@codemirror/language";
17
+ import { celParser } from "@compmd/lezer";
18
+
19
+ const cel = new Language(defineLanguageFacet(), celParser);
20
+ ```
21
+
13
22
  ## What it parses
14
23
 
15
24
  | Construct | Nodes | Spec |
@@ -25,6 +34,10 @@ const language = markdown({ base: markdownLanguage, extensions: [compmd] });
25
34
  | Interpolation, `{{path}}`, in text, fallbacks and quoted params | `Interpolation`, `InterpolationExpression` | §8.1 |
26
35
  | Wiki links, `[[Target]]` and `[[Target\|label]]`, always | `WikiLink`, `WikiLinkTarget`, `WikiLinkLabel` | §2.3 |
27
36
  | Math: inline by Pandoc's rule, display on `$$` lines | `InlineMath`, `MathBlock` | §2.3 |
37
+ | A CEL expression, in an expression param and in `celParser`'s tree: names, fields, calls, indexes, literals, lists, maps, operators and `?:` | `CelBinary`, `CelCall`, `CelMember`, … (`CEL_NODES`) | §8.2 |
38
+
39
+ What is wrong or missing in an expression is a `CelInvalid` node, empty where something is missing, so an expression
40
+ being typed always has a tree. In `celParser`'s tree, under its top node `CelText`, it is Lezer's error node.
28
41
 
29
42
  A component line is one block whose children are the line's parts; a container's content between its opener and its
30
43
  closer stays ordinary Markdown. Nothing inside a component line or an inline component is parsed as Markdown, except
@@ -46,7 +59,8 @@ It lives in [`compmd-grammars`](../README.md), beside the tree-sitter grammar, a
46
59
  ## Limits
47
60
 
48
61
  - **Interpolation in a link's destination** (`[x]({{s.url}})`) isn't parsed.
49
- - **CEL's triple-quoted, raw and bytes literals** inside an expression param aren't told apart from other strings.
62
+ - **CEL comments** (`// …`) aren't parsed: an expression fits on one line (§8.2), and one would hide the param's `)`.
63
+ - **A CEL expression's types** aren't the parser's: it parses any name, call or operator, and the processor checks them.
50
64
  - **`$$` inside a paragraph** isn't display math.
51
65
  - **A definition's body inside a list item or a block quote** isn't parsed again: its lines aren't the document's as
52
66
  they are.
@@ -0,0 +1,16 @@
1
+ import type { CelNodeName } from "./nodes.ts";
2
+ /** A node of a parsed expression, as offsets into its text. */
3
+ export interface CelNode {
4
+ readonly type: CelNodeName;
5
+ readonly from: number;
6
+ readonly to: number;
7
+ readonly children: readonly CelNode[];
8
+ }
9
+ /**
10
+ * `text`, a CEL expression, as the nodes of its tree, in order: the expression, then anything after it that doesn't
11
+ * belong, marked `CelInvalid`. Never throws: what is wrong or missing is a `CelInvalid` node.
12
+ *
13
+ * @example
14
+ * parseCel("1 + 2"); // [CelBinary(CelNumber, CelArithmeticOperator, CelNumber)]
15
+ */
16
+ export declare function parseCel(text: string): CelNode[];
@@ -0,0 +1,235 @@
1
+ // A CEL expression (cel-spec, "Syntax"; CompMD's profile, spec §8.2) parsed into nodes: precedence climbing over the
2
+ // tokens, recovering from errors so an expression being typed always gives a tree. What is wrong or missing is a
3
+ // `CelInvalid` node, empty where something is missing.
4
+ import { tokenize } from "./cel-tokens.js";
5
+ /** The binary operators by precedence, lowest first (`?:` is below them all). */
6
+ const BINARY_LEVELS = [
7
+ ["||"],
8
+ ["&&"],
9
+ ["<", "<=", ">=", ">", "==", "!=", "in"],
10
+ ["+", "-"],
11
+ ["*", "/", "%"],
12
+ ];
13
+ /** The node of each operator's token. */
14
+ function operatorNode(text) {
15
+ if (text === "in")
16
+ return "CelIn";
17
+ if (["||", "&&", "!"].includes(text))
18
+ return "CelLogicOperator";
19
+ if (["<", "<=", ">=", ">", "==", "!="].includes(text))
20
+ return "CelCompareOperator";
21
+ return "CelArithmeticOperator";
22
+ }
23
+ const BRACKETS = {
24
+ "(": "CelParen",
25
+ ")": "CelParen",
26
+ "[": "CelBracket",
27
+ "]": "CelBracket",
28
+ "{": "CelBrace",
29
+ "}": "CelBrace",
30
+ };
31
+ const LITERAL_NAMES = { true: "CelBool", false: "CelBool", null: "CelNull" };
32
+ /** Tokens an expression never starts at, other than operators: closers, separators and `in`. */
33
+ const NEVER_START = new Set([")", "]", "}", ",", ":", "?", "in"]);
34
+ function node(type, from, to, children = []) {
35
+ return { type, from, to, children };
36
+ }
37
+ class ExpressionParser {
38
+ text;
39
+ tokens;
40
+ next = 0;
41
+ constructor(text, tokens) {
42
+ this.text = text;
43
+ this.tokens = tokens;
44
+ }
45
+ /** The whole text: an expression, then each thing after it that doesn't belong, marked. */
46
+ parse() {
47
+ const nodes = [this.expression()];
48
+ while (this.peek()) {
49
+ const token = this.peek();
50
+ if (this.startsExpression(token)) {
51
+ nodes.push(node("CelInvalid", token.from, token.from), this.expression());
52
+ }
53
+ else {
54
+ this.next++;
55
+ nodes.push(node("CelInvalid", token.from, token.to, [this.tokenNode(token)]));
56
+ }
57
+ }
58
+ return nodes;
59
+ }
60
+ peek() {
61
+ return this.tokens[this.next];
62
+ }
63
+ textOf(token) {
64
+ return token && this.text.slice(token.from, token.to);
65
+ }
66
+ at(text) {
67
+ return this.textOf(this.peek()) === text;
68
+ }
69
+ /** Where a missing token would be: after the last one taken. */
70
+ here() {
71
+ return this.tokens[this.next - 1]?.to ?? 0;
72
+ }
73
+ startsExpression(token) {
74
+ const text = this.textOf(token);
75
+ if (token.type === "Operator")
76
+ return text === "!" || text === "-";
77
+ return !NEVER_START.has(text);
78
+ }
79
+ /** The node of a token standing alone: punctuation, an operator, a literal, or what isn't a token. */
80
+ tokenNode(token) {
81
+ const text = this.textOf(token);
82
+ switch (token.type) {
83
+ case "Operator":
84
+ return node(operatorNode(text), token.from, token.to);
85
+ case "Punctuation":
86
+ return node(BRACKETS[text] ?? "CelPunctuation", token.from, token.to);
87
+ case "Number":
88
+ return node("CelNumber", token.from, token.to);
89
+ case "String":
90
+ case "Bytes":
91
+ return this.literal(token);
92
+ case "Name":
93
+ return node(text === "in" ? "CelIn" : (LITERAL_NAMES[text] ?? "CelVariable"), token.from, token.to);
94
+ case "Unknown":
95
+ return node("CelInvalid", token.from, token.to);
96
+ }
97
+ }
98
+ /** A string or bytes literal; one missing its closing quote is followed by an empty `CelInvalid`. */
99
+ literal(token) {
100
+ const type = token.type === "Bytes" ? "CelBytes" : "CelString";
101
+ if (!token.open)
102
+ return node(type, token.from, token.to);
103
+ return node(type, token.from, token.to, [node("CelInvalid", token.to, token.to)]);
104
+ }
105
+ /** The token `text`, taken, or an empty `CelInvalid` where it should be. */
106
+ expect(text) {
107
+ if (!this.at(text))
108
+ return node("CelInvalid", this.here(), this.here());
109
+ return this.tokenNode(this.tokens[this.next++]);
110
+ }
111
+ /** `a ? b : c`, right to left. */
112
+ expression() {
113
+ const condition = this.binary(0);
114
+ if (!this.at("?"))
115
+ return condition;
116
+ const question = this.expect("?");
117
+ const then = this.binary(0);
118
+ const colon = this.expect(":");
119
+ const otherwise = this.expression();
120
+ return node("CelConditional", condition.from, otherwise.to, [condition, question, then, colon, otherwise]);
121
+ }
122
+ binary(level) {
123
+ if (level === BINARY_LEVELS.length)
124
+ return this.unary();
125
+ let left = this.binary(level + 1);
126
+ while (BINARY_LEVELS[level].some((operator) => this.at(operator))) {
127
+ const operator = this.tokenNode(this.tokens[this.next++]);
128
+ const right = this.binary(level + 1);
129
+ left = node("CelBinary", left.from, right.to, [left, operator, right]);
130
+ }
131
+ return left;
132
+ }
133
+ unary() {
134
+ if (!this.at("!") && !this.at("-"))
135
+ return this.member();
136
+ const operator = this.tokenNode(this.tokens[this.next++]);
137
+ const operand = this.unary();
138
+ return node("CelUnary", operator.from, operand.to, [operator, operand]);
139
+ }
140
+ /** A primary followed by its fields, calls and indexes: `md.doc.tags[0]`, `name.startsWith("A")`. */
141
+ member() {
142
+ let target = this.primary();
143
+ for (;;) {
144
+ if (this.at(".")) {
145
+ const dot = this.expect(".");
146
+ const name = this.peek()?.type === "Name" ? this.tokens[this.next++] : undefined;
147
+ if (name && this.at("(")) {
148
+ const call = [target, dot, node("CelFunction", name.from, name.to), this.arguments()];
149
+ target = node("CelCall", target.from, call.at(-1).to, call);
150
+ }
151
+ else {
152
+ const field = name ? node("CelField", name.from, name.to) : node("CelInvalid", dot.to, dot.to);
153
+ target = node("CelMember", target.from, field.to, [target, dot, field]);
154
+ }
155
+ }
156
+ else if (this.at("[")) {
157
+ const open = this.expect("[");
158
+ const index = this.expression();
159
+ const close = this.expect("]");
160
+ target = node("CelIndex", target.from, close.to, [target, open, index, close]);
161
+ }
162
+ else {
163
+ return target;
164
+ }
165
+ }
166
+ }
167
+ primary() {
168
+ const token = this.peek();
169
+ if (!token || !this.startsExpression(token))
170
+ return node("CelInvalid", this.here(), this.here());
171
+ if (token.type === "Name" && LITERAL_NAMES[this.textOf(token)] === undefined)
172
+ return this.nameOrCall();
173
+ if (this.at("."))
174
+ return this.nameOrCall();
175
+ if (this.at("("))
176
+ return this.parenthesized();
177
+ if (this.at("["))
178
+ return this.list("[", "]", "CelList", () => this.expression());
179
+ if (this.at("{"))
180
+ return this.list("{", "}", "CelMap", () => this.mapEntry());
181
+ this.next++;
182
+ return this.tokenNode(token);
183
+ }
184
+ /** A variable, `.name` from the root, or a function call `size(x)`. */
185
+ nameOrCall() {
186
+ const dot = this.at(".") ? [this.expect(".")] : [];
187
+ const name = this.peek()?.type === "Name" ? this.tokens[this.next++] : undefined;
188
+ if (!name) {
189
+ const from = dot[0]?.from ?? this.here();
190
+ return node("CelInvalid", from, this.here(), dot);
191
+ }
192
+ const from = dot[0]?.from ?? name.from;
193
+ if (!this.at("("))
194
+ return node("CelVariable", from, name.to, dot);
195
+ const call = [...dot, node("CelFunction", name.from, name.to), this.arguments()];
196
+ return node("CelCall", from, call.at(-1).to, call);
197
+ }
198
+ arguments() {
199
+ return this.list("(", ")", "CelArguments", () => this.expression());
200
+ }
201
+ parenthesized() {
202
+ const open = this.expect("(");
203
+ const inner = this.expression();
204
+ const close = this.expect(")");
205
+ return node("CelParenthesized", open.from, close.to, [open, inner, close]);
206
+ }
207
+ /** `open item, item, … close`, a trailing comma allowed. */
208
+ list(open, close, type, item) {
209
+ const children = [this.expect(open)];
210
+ while (this.peek() && !this.at(close)) {
211
+ children.push(item());
212
+ if (!this.at(","))
213
+ break;
214
+ children.push(this.expect(","));
215
+ }
216
+ children.push(this.expect(close));
217
+ return node(type, children[0].from, children.at(-1).to, children);
218
+ }
219
+ mapEntry() {
220
+ const key = this.expression();
221
+ const colon = this.expect(":");
222
+ const value = this.expression();
223
+ return node("CelMapEntry", key.from, value.to, [key, colon, value]);
224
+ }
225
+ }
226
+ /**
227
+ * `text`, a CEL expression, as the nodes of its tree, in order: the expression, then anything after it that doesn't
228
+ * belong, marked `CelInvalid`. Never throws: what is wrong or missing is a `CelInvalid` node.
229
+ *
230
+ * @example
231
+ * parseCel("1 + 2"); // [CelBinary(CelNumber, CelArithmeticOperator, CelNumber)]
232
+ */
233
+ export function parseCel(text) {
234
+ return new ExpressionParser(text, tokenize(text)).parse();
235
+ }
@@ -0,0 +1,15 @@
1
+ import { Parser } from "@lezer/common";
2
+ /** The top node of a tree from {@link celParser}. */
3
+ export declare const CEL_TOP = "CelText";
4
+ /**
5
+ * A Lezer parser for a text that is one CEL expression in CompMD's profile (spec §8.2): a formula, not a document. It
6
+ * never fails: what is wrong or missing is a `CelInvalid` node, Lezer's error node. Its nodes carry the grammar's
7
+ * highlighting, so CodeMirror's `Language` can use it as it is.
8
+ *
9
+ * @example
10
+ * import { Language, defineLanguageFacet } from "@codemirror/language";
11
+ * import { celParser } from "@compmd/lezer";
12
+ *
13
+ * const cel = new Language(defineLanguageFacet(), celParser);
14
+ */
15
+ export declare const celParser: Parser;
@@ -0,0 +1,46 @@
1
+ // A Lezer parser for a text that is one CEL expression, as a formula is: the expression parser's nodes as a tree, with
2
+ // the grammar's highlighting.
3
+ import { NodeSet, NodeType, Parser, Tree, } from "@lezer/common";
4
+ import { parseCel } from "./cel-parse.js";
5
+ import { compmdHighlighting } from "./highlighting.js";
6
+ import { CEL_NODES } from "./nodes.js";
7
+ /** The top node of a tree from {@link celParser}. */
8
+ export const CEL_TOP = "CelText";
9
+ /** Each node's type ID: the top node's is 0. */
10
+ const ids = new Map(CEL_NODES.map((name, index) => [name, index + 1]));
11
+ const nodeSet = new NodeSet([
12
+ NodeType.define({ id: 0, name: CEL_TOP, top: true }),
13
+ ...CEL_NODES.map((name) => NodeType.define({ id: ids.get(name), name, error: name === "CelInvalid" })),
14
+ ]).extend(compmdHighlighting);
15
+ function subtree(node) {
16
+ return new Tree(nodeSet.types[ids.get(node.type)], node.children.map(subtree), node.children.map((child) => child.from - node.from), node.to - node.from);
17
+ }
18
+ /** `text`'s tree: a `CelText` holding the expression's nodes. */
19
+ function celTree(text) {
20
+ const nodes = parseCel(text);
21
+ return new Tree(nodeSet.types[0], nodes.map(subtree), nodes.map((node) => node.from), text.length);
22
+ }
23
+ class CelParser extends Parser {
24
+ createParse(input, _fragments, ranges) {
25
+ const from = ranges[0].from;
26
+ const to = ranges.at(-1).to;
27
+ return {
28
+ parsedPos: from,
29
+ stoppedAt: null,
30
+ stopAt() { },
31
+ advance: () => celTree(input.read(from, to)),
32
+ };
33
+ }
34
+ }
35
+ /**
36
+ * A Lezer parser for a text that is one CEL expression in CompMD's profile (spec §8.2): a formula, not a document. It
37
+ * never fails: what is wrong or missing is a `CelInvalid` node, Lezer's error node. Its nodes carry the grammar's
38
+ * highlighting, so CodeMirror's `Language` can use it as it is.
39
+ *
40
+ * @example
41
+ * import { Language, defineLanguageFacet } from "@codemirror/language";
42
+ * import { celParser } from "@compmd/lezer";
43
+ *
44
+ * const cel = new Language(defineLanguageFacet(), celParser);
45
+ */
46
+ export const celParser = new CelParser();
@@ -0,0 +1,24 @@
1
+ /** The kind of a token. */
2
+ export type TokenType = "Name" | "Number" | "String" | "Bytes" | "Operator" | "Punctuation" | "Unknown";
3
+ /** One token, as offsets into the scanned text. A string or bytes literal missing its closing quote is `open`. */
4
+ export interface Token {
5
+ readonly type: TokenType;
6
+ readonly from: number;
7
+ readonly to: number;
8
+ readonly open?: true;
9
+ }
10
+ /**
11
+ * A string or bytes literal at `at`, in any of CEL's forms (quoted, triple-quoted, raw, bytes), with its prefix, or
12
+ * `undefined` when there is none.
13
+ *
14
+ * @example
15
+ * literalAt(`r'''a)'''`, 0); // { type: "String", from: 0, to: 9 }
16
+ */
17
+ export declare function literalAt(text: string, at: number): Token | undefined;
18
+ /**
19
+ * The tokens of `text`, a CEL expression, skipping white space.
20
+ *
21
+ * @example
22
+ * tokenize("md.doc.price * 2"); // Name, Punctuation, Name, Punctuation, Name, Operator, Number
23
+ */
24
+ export declare function tokenize(text: string): Token[];
@@ -0,0 +1,78 @@
1
+ // CEL's tokens (cel-spec, "Syntax"), for the expression parser: names, numbers, strings and bytes in each of their
2
+ // forms, operators and punctuation. A character that starts no token is a token of its own, `Unknown`.
3
+ const NAME = /[A-Za-z_][A-Za-z0-9_]*/y;
4
+ const NUMBER = /0[xX][0-9A-Fa-f]+[uU]?|(?:[0-9]*\.[0-9]+|[0-9]+(?=[eE]))(?:[eE][+-]?[0-9]+)?|[0-9]+[uU]?/y;
5
+ const OPERATOR = /\|\||&&|==|!=|<=|>=|[<>+\-*/%!]/y;
6
+ const PUNCTUATION = /[()[\]{},:?.]/y;
7
+ const SPACE = /[ \t\n\r\f]+/y;
8
+ /** A string's or bytes literal's prefix: `r` (raw) and `b` (bytes), in either order and case. */
9
+ const PREFIX = /(?:[rR][bB]?|[bB][rR]?)?(?='|")/y;
10
+ function matchAt(pattern, text, at) {
11
+ pattern.lastIndex = at;
12
+ return pattern.test(text) ? pattern.lastIndex : undefined;
13
+ }
14
+ /**
15
+ * The end of a quoted literal whose quote starts at `at`, and whether it was closed. A single-quoted one ends at a
16
+ * line break; a raw one has no escapes.
17
+ */
18
+ function quotedEnd(text, at, raw) {
19
+ const triple = text.startsWith(text[at].repeat(3), at);
20
+ const quote = triple ? text.slice(at, at + 3) : text[at];
21
+ for (let pos = at + quote.length; pos < text.length; pos++) {
22
+ if (!raw && text[pos] === "\\")
23
+ pos++;
24
+ else if (text.startsWith(quote, pos))
25
+ return { end: pos + quote.length, closed: true };
26
+ else if (!triple && text[pos] === "\n")
27
+ return { end: pos, closed: false };
28
+ }
29
+ return { end: text.length, closed: false };
30
+ }
31
+ /**
32
+ * A string or bytes literal at `at`, in any of CEL's forms (quoted, triple-quoted, raw, bytes), with its prefix, or
33
+ * `undefined` when there is none.
34
+ *
35
+ * @example
36
+ * literalAt(`r'''a)'''`, 0); // { type: "String", from: 0, to: 9 }
37
+ */
38
+ export function literalAt(text, at) {
39
+ const quoteAt = matchAt(PREFIX, text, at);
40
+ if (quoteAt === undefined)
41
+ return undefined;
42
+ const prefix = text.slice(at, quoteAt).toLowerCase();
43
+ const { end, closed } = quotedEnd(text, quoteAt, prefix.includes("r"));
44
+ const type = prefix.includes("b") ? "Bytes" : "String";
45
+ return closed ? { type, from: at, to: end } : { type, from: at, to: end, open: true };
46
+ }
47
+ function tokenAt(text, at) {
48
+ const literal = literalAt(text, at);
49
+ if (literal)
50
+ return literal;
51
+ for (const [type, pattern] of [
52
+ ["Name", NAME],
53
+ ["Number", NUMBER],
54
+ ["Operator", OPERATOR],
55
+ ["Punctuation", PUNCTUATION],
56
+ ]) {
57
+ const end = matchAt(pattern, text, at);
58
+ if (end !== undefined)
59
+ return { type, from: at, to: end };
60
+ }
61
+ return { type: "Unknown", from: at, to: at + 1 };
62
+ }
63
+ /**
64
+ * The tokens of `text`, a CEL expression, skipping white space.
65
+ *
66
+ * @example
67
+ * tokenize("md.doc.price * 2"); // Name, Punctuation, Name, Punctuation, Name, Operator, Number
68
+ */
69
+ export function tokenize(text) {
70
+ const tokens = [];
71
+ let at = matchAt(SPACE, text, 0) ?? 0;
72
+ while (at < text.length) {
73
+ const token = tokenAt(text, at);
74
+ tokens.push(token);
75
+ at = matchAt(SPACE, text, token.to) ?? token.to;
76
+ }
77
+ return tokens;
78
+ }
package/dist/compmd.js CHANGED
@@ -6,7 +6,7 @@ import { compmdHighlighting } from "./highlighting.js";
6
6
  import { parseInlineComponent } from "./inline-component.js";
7
7
  import { parseInterpolation } from "./interpolation.js";
8
8
  import { endLeafAtMathBlock, parseInlineMath, parseMathBlock } from "./math.js";
9
- import { COMPONENT_LINES, OTHER_BLOCKS, PARTS } from "./nodes.js";
9
+ import { CEL_NODES, COMPONENT_LINES, OTHER_BLOCKS, PARTS } from "./nodes.js";
10
10
  import { parseWikiLink } from "./wiki-link.js";
11
11
  /**
12
12
  * CompMD's syntax (spec v1 §2.1, §2.3, §3, §7.1, §7.2, §8.1) for `@lezer/markdown`: frontmatter, component lines,
@@ -24,6 +24,7 @@ export const compmd = {
24
24
  defineNodes: [
25
25
  ...[...COMPONENT_LINES, ...OTHER_BLOCKS].map((name) => ({ name, block: true })),
26
26
  ...PARTS,
27
+ ...CEL_NODES,
27
28
  ],
28
29
  props: [compmdHighlighting],
29
30
  parseBlock: [
@@ -1,10 +1,28 @@
1
1
  // The parts component lines and inline components share: a param list, and a fallback `[…]`.
2
+ import { parseCel } from "./cel-parse.js";
2
3
  import { interpolationsIn } from "./interpolation.js";
3
- /** A span as an element, with its parts and, in a quoted string, its interpolations, in document order. */
4
+ /** A node of a parsed CEL expression as an element, its offsets from `base`. */
5
+ function celElement(cx, node, base) {
6
+ const children = node.children.map((child) => celElement(cx, child, base));
7
+ return cx.elt(node.type, base + node.from, base + node.to, children);
8
+ }
9
+ /**
10
+ * What a span holds besides its parts: a quoted string's interpolations, or an expression's CEL nodes, parsed from
11
+ * the text between its parentheses (which are its parts, `ParamExpressionMark`s).
12
+ */
13
+ function spanContent(cx, span, text, base) {
14
+ if (span.type === "ParamString")
15
+ return interpolationsIn(cx, text.slice(span.from, span.to), base + span.from);
16
+ if (span.type !== "ParamExpression")
17
+ return [];
18
+ const from = span.from + 1;
19
+ const to = span.parts?.length === 2 ? span.to - 1 : span.to;
20
+ return parseCel(text.slice(from, to)).map((node) => celElement(cx, node, base + from));
21
+ }
22
+ /** A span as an element, with its parts and what it holds, in document order. */
4
23
  function spanElement(cx, span, text, base) {
5
24
  const parts = (span.parts ?? []).map((part) => spanElement(cx, part, text, base));
6
- const interpolations = span.type === "ParamString" ? interpolationsIn(cx, text.slice(span.from, span.to), base + span.from) : [];
7
- const children = [...parts, ...interpolations].sort((a, b) => a.from - b.from);
25
+ const children = [...parts, ...spanContent(cx, span, text, base)].sort((a, b) => a.from - b.from);
8
26
  return cx.elt(span.type, base + span.from, base + span.to, children);
9
27
  }
10
28
  /** The spans of `scanned` (offsets into `text`) as elements, `text` starting at document position `base`. */
@@ -37,6 +37,24 @@ const OWN_TAGS = {
37
37
  ParamJson: t.literal,
38
38
  "ComponentMalformed ParamInvalid": t.invalid,
39
39
  Frontmatter: t.meta,
40
+ // An expression's CEL, its own language (`tokens.json`), tagged as the tree-sitter `cel` grammar captures it.
41
+ CelVariable: t.variableName,
42
+ CelField: t.propertyName,
43
+ CelFunction: t.function(t.variableName),
44
+ CelNumber: t.number,
45
+ CelString: t.string,
46
+ CelBytes: t.special(t.string),
47
+ CelBool: t.bool,
48
+ CelNull: t.null,
49
+ CelLogicOperator: t.logicOperator,
50
+ CelCompareOperator: t.compareOperator,
51
+ CelArithmeticOperator: t.arithmeticOperator,
52
+ CelIn: t.operatorKeyword,
53
+ CelParen: t.paren,
54
+ CelBracket: t.squareBracket,
55
+ CelBrace: t.brace,
56
+ CelPunctuation: t.punctuation,
57
+ CelInvalid: t.invalid,
40
58
  };
41
59
  const MODIFIERS = {
42
60
  special: t.special,
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
+ export { CEL_TOP, celParser } from "./cel-parser.ts";
1
2
  export { compmd } from "./compmd.ts";
2
3
  export { compmdHighlighting, NODE_TOKENS, tagNamed } from "./highlighting.ts";
3
4
  export { TOKEN_TAGS, type Token } from "./syntax.ts";
4
- export { COMPMD_NODES, COMPONENT_LINES, type ComponentLine } from "./nodes.ts";
5
+ export { CEL_NODES, type CelNodeName, COMPMD_NODES, COMPONENT_LINES, type ComponentLine } from "./nodes.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
+ export { CEL_TOP, celParser } from "./cel-parser.js";
1
2
  export { compmd } from "./compmd.js";
2
3
  export { compmdHighlighting, NODE_TOKENS, tagNamed } from "./highlighting.js";
3
4
  export { TOKEN_TAGS } from "./syntax.js";
4
- export { COMPMD_NODES, COMPONENT_LINES } from "./nodes.js";
5
+ export { CEL_NODES, COMPMD_NODES, COMPONENT_LINES } from "./nodes.js";
package/dist/nodes.d.ts CHANGED
@@ -6,6 +6,13 @@ export type ComponentLine = (typeof COMPONENT_LINES)[number];
6
6
  export declare const OTHER_BLOCKS: readonly ["Frontmatter", "MathBlock", "ComponentDefinition"];
7
7
  /** Inline and part nodes: the pieces of a component line, an inline component, an interpolation, a wiki link, math. */
8
8
  export declare const PARTS: readonly ["InlineComponent", "ComponentMark", "ComponentName", "ComponentSlotName", "ComponentFallback", "ComponentFallbackMark", "ParamList", "ParamBrace", "ParamKey", "ParamBreakpoint", "ParamOperator", "ParamString", "ParamEscape", "ParamExpression", "ParamExpressionMark", "ParamJson", "ParamBare", "ParamClass", "ParamClassMark", "ParamClassName", "ParamId", "ParamIdMark", "ParamIdName", "ParamInvalid", "DefinitionInfo", "DefinitionSignature", "DefinitionSeparator", "DefinitionBody", "Interpolation", "InterpolationMark", "InterpolationExpression", "WikiLink", "WikiLinkMark", "WikiLinkTarget", "WikiLinkLabel", "InlineMath", "InlineMathMark", "MathBlockMark", "FrontmatterMark", "FrontmatterKey"];
9
+ /**
10
+ * The nodes of a CEL expression (spec §8.2): in a tree of its own from `celParser`, and inside an expression param
11
+ * (`ParamExpression`). `CelInvalid` is what is wrong, or empty where something is missing.
12
+ */
13
+ export declare const CEL_NODES: readonly ["CelConditional", "CelBinary", "CelUnary", "CelMember", "CelIndex", "CelCall", "CelArguments", "CelParenthesized", "CelList", "CelMap", "CelMapEntry", "CelVariable", "CelField", "CelFunction", "CelNumber", "CelString", "CelBytes", "CelBool", "CelNull", "CelLogicOperator", "CelCompareOperator", "CelArithmeticOperator", "CelIn", "CelParen", "CelBracket", "CelBrace", "CelPunctuation", "CelInvalid"];
14
+ /** One of {@link CEL_NODES}. */
15
+ export type CelNodeName = (typeof CEL_NODES)[number];
9
16
  /**
10
17
  * The nodes that are CompMD's own, not Markdown: an editor that draws Markdown in place shows these as their source.
11
18
  * A component's fallback (`ComponentFallback`) is inside them but holds ordinary inline Markdown.
package/dist/nodes.js CHANGED
@@ -54,6 +54,40 @@ export const PARTS = [
54
54
  "FrontmatterMark",
55
55
  "FrontmatterKey",
56
56
  ];
57
+ /**
58
+ * The nodes of a CEL expression (spec §8.2): in a tree of its own from `celParser`, and inside an expression param
59
+ * (`ParamExpression`). `CelInvalid` is what is wrong, or empty where something is missing.
60
+ */
61
+ export const CEL_NODES = [
62
+ "CelConditional",
63
+ "CelBinary",
64
+ "CelUnary",
65
+ "CelMember",
66
+ "CelIndex",
67
+ "CelCall",
68
+ "CelArguments",
69
+ "CelParenthesized",
70
+ "CelList",
71
+ "CelMap",
72
+ "CelMapEntry",
73
+ "CelVariable",
74
+ "CelField",
75
+ "CelFunction",
76
+ "CelNumber",
77
+ "CelString",
78
+ "CelBytes",
79
+ "CelBool",
80
+ "CelNull",
81
+ "CelLogicOperator",
82
+ "CelCompareOperator",
83
+ "CelArithmeticOperator",
84
+ "CelIn",
85
+ "CelParen",
86
+ "CelBracket",
87
+ "CelBrace",
88
+ "CelPunctuation",
89
+ "CelInvalid",
90
+ ];
57
91
  /**
58
92
  * The nodes that are CompMD's own, not Markdown: an editor that draws Markdown in place shows these as their source.
59
93
  * A component's fallback (`ComponentFallback`) is inside them but holds ordinary inline Markdown.
package/dist/params.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // A CompMD param list (spec §3.1, §5.1), scanned into spans. Each value finds its own end from its first character,
2
2
  // so a broken quote or bracket damages only its own line (spec §5). The pieces every grammar shares (a name, a bare
3
3
  // value, an escape) are `syntax/patterns.js`'s.
4
+ import { literalAt } from "./cel-tokens.js";
4
5
  import { PATTERNS } from "./syntax.js";
5
6
  /** A component's, slot's or param key's name (spec §3.1). */
6
7
  const NAME = new RegExp(`^${PATTERNS.name}`);
@@ -17,23 +18,20 @@ function stringEnd(text, from) {
17
18
  }
18
19
  return text.length;
19
20
  }
20
- /**
21
- * After the bracket matching the one at `from`, counting only outside strings, or the text's end. An expression's
22
- * strings are CEL's (`"…"`, `'…'`), a JSON value's are `"…"`. CEL's triple-quoted, raw and bytes literals are not
23
- * told apart (see the README's limits).
24
- */
25
- function bracketedEnd(text, from, open, close, quotes) {
21
+ /** A JSON value's strings: `"…"`, with escapes. */
22
+ const jsonStringEnd = (text, at) => (text[at] === '"' ? stringEnd(text, at) : undefined);
23
+ /** An expression's strings and bytes: CEL's, in every form (quoted, triple-quoted, raw, bytes). */
24
+ const celLiteralEnd = (text, at) => literalAt(text, at)?.to;
25
+ /** After the bracket matching the one at `from`, counting only outside the strings `literalEnd` finds, or the text's end. */
26
+ function bracketedEnd(text, from, open, close, literalEnd) {
26
27
  let depth = 0;
27
28
  for (let at = from; at < text.length; at++) {
28
- const char = text[at];
29
- if (quotes.includes(char)) {
30
- for (at++; at < text.length && text[at] !== char; at++)
31
- if (text[at] === "\\")
32
- at++;
33
- }
34
- else if (char === open)
29
+ const literal = literalEnd(text, at);
30
+ if (literal !== undefined)
31
+ at = literal - 1;
32
+ else if (text[at] === open)
35
33
  depth++;
36
- else if (char === close && --depth === 0)
34
+ else if (text[at] === close && --depth === 0)
37
35
  return at + 1;
38
36
  }
39
37
  return text.length;
@@ -46,7 +44,7 @@ function stringSpan(text, from) {
46
44
  }
47
45
  /** An expression `(…)` from `from`, with its parentheses when it is closed. */
48
46
  function expressionSpan(text, from) {
49
- const to = bracketedEnd(text, from, "(", ")", "\"'");
47
+ const to = bracketedEnd(text, from, "(", ")", celLiteralEnd);
50
48
  const open = { type: "ParamExpressionMark", from, to: from + 1 };
51
49
  const closed = to - from > 1 && text[to - 1] === ")";
52
50
  const parts = closed ? [open, { type: "ParamExpressionMark", from: to - 1, to }] : [open];
@@ -59,9 +57,9 @@ function valueSpan(text, from) {
59
57
  case "(":
60
58
  return expressionSpan(text, from);
61
59
  case "[":
62
- return { type: "ParamJson", from, to: bracketedEnd(text, from, "[", "]", '"') };
60
+ return { type: "ParamJson", from, to: bracketedEnd(text, from, "[", "]", jsonStringEnd) };
63
61
  case "{":
64
- return { type: "ParamJson", from, to: bracketedEnd(text, from, "{", "}", '"') };
62
+ return { type: "ParamJson", from, to: bracketedEnd(text, from, "{", "}", jsonStringEnd) };
65
63
  default:
66
64
  return { type: "ParamBare", from, to: from + (BARE_VALUE.exec(text.slice(from))?.[0].length ?? 0) };
67
65
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@compmd/lezer",
3
- "version": "0.1.0",
4
- "description": "CompMD's grammar for CodeMirror: an @lezer/markdown extension with CompMD's components, params, interpolation, wiki links and math.",
3
+ "version": "0.2.0",
4
+ "description": "CompMD's grammar for CodeMirror: an @lezer/markdown extension with CompMD's components, params, CEL expressions, interpolation, wiki links and math.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {