@compmd/lezer 0.0.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 +80 -2
- package/dist/cel-parse.d.ts +16 -0
- package/dist/cel-parse.js +235 -0
- package/dist/cel-parser.d.ts +15 -0
- package/dist/cel-parser.js +46 -0
- package/dist/cel-tokens.d.ts +24 -0
- package/dist/cel-tokens.js +78 -0
- package/dist/compmd.d.ts +14 -0
- package/dist/compmd.js +42 -0
- package/dist/component-line.d.ts +17 -0
- package/dist/component-line.js +167 -0
- package/dist/component-parts.d.ts +11 -0
- package/dist/component-parts.js +51 -0
- package/dist/context.d.ts +6 -0
- package/dist/context.js +3 -0
- package/dist/definition.d.ts +3 -0
- package/dist/definition.js +118 -0
- package/dist/fallback.d.ts +10 -0
- package/dist/fallback.js +31 -0
- package/dist/frontmatter.d.ts +3 -0
- package/dist/frontmatter.js +38 -0
- package/dist/highlighting.d.ts +12 -0
- package/dist/highlighting.js +84 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/inline-component.d.ts +3 -0
- package/dist/inline-component.js +36 -0
- package/dist/interpolation.d.ts +6 -0
- package/dist/interpolation.js +44 -0
- package/dist/math.d.ts +10 -0
- package/dist/math.js +59 -0
- package/dist/nodes.d.ts +20 -0
- package/dist/nodes.js +101 -0
- package/dist/params.d.ts +33 -0
- package/dist/params.js +151 -0
- package/dist/syntax.d.ts +52 -0
- package/dist/syntax.js +52 -0
- package/dist/wiki-link.d.ts +3 -0
- package/dist/wiki-link.js +25 -0
- package/package.json +38 -13
package/README.md
CHANGED
|
@@ -1,5 +1,83 @@
|
|
|
1
1
|
# @compmd/lezer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CompMD's grammar for CodeMirror: an [`@lezer/markdown`](https://github.com/lezer-parser/markdown) extension that adds
|
|
4
|
+
[CompMD](https://compmd.dev)'s syntax ([spec](https://compmd.dev/spec/) v1) to CommonMark and GFM, with highlighting tags.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
```ts
|
|
7
|
+
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
|
8
|
+
import { compmd } from "@compmd/lezer";
|
|
9
|
+
|
|
10
|
+
const language = markdown({ base: markdownLanguage, extensions: [compmd] });
|
|
11
|
+
```
|
|
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
|
+
|
|
22
|
+
## What it parses
|
|
23
|
+
|
|
24
|
+
| Construct | Nodes | Spec |
|
|
25
|
+
|---|---|---|
|
|
26
|
+
| Frontmatter at the document's start, YAML between `---` lines or TOML between `+++` lines, never Markdown; its `md` key | `Frontmatter`, `FrontmatterKey` | §2.1 |
|
|
27
|
+
| A container's opener, closer and continuation lines | `ComponentOpen`, `ComponentClose`, `ComponentContinuation` | §3 |
|
|
28
|
+
| Leaves and slots | `ComponentLeaf`, `ComponentSlot` | §3, §4 |
|
|
29
|
+
| A line starting with `::` that matches no form | `ComponentMalformed` | §10 (F016) |
|
|
30
|
+
| Inline components, `:name[fallback]{…}` | `InlineComponent` | §3.2 |
|
|
31
|
+
| Params: keys, breakpoints, strings with their escapes, expressions with their parentheses, JSON, bare values, `.class`, `#id`; a list that isn't closed, invalid to the line's end | `ParamList`, `ParamKey`, `ParamOperator`, `ParamString`, `ParamEscape`, … `ParamInvalid` | §3.1, §5 |
|
|
32
|
+
| Component definitions and signature fences: the info string in the param syntax, the signature, the `---` line, and the body parsed as CompMD again | `ComponentDefinition`, `DefinitionInfo`, `DefinitionSignature`, `DefinitionSeparator`, `DefinitionBody` | §7.1, §7.2 |
|
|
33
|
+
| A fallback `[…]`, its inside parsed as inline Markdown | `ComponentFallback` | §4.4 |
|
|
34
|
+
| Interpolation, `{{path}}`, in text, fallbacks and quoted params | `Interpolation`, `InterpolationExpression` | §8.1 |
|
|
35
|
+
| Wiki links, `[[Target]]` and `[[Target\|label]]`, always | `WikiLink`, `WikiLinkTarget`, `WikiLinkLabel` | §2.3 |
|
|
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.
|
|
41
|
+
|
|
42
|
+
A component line is one block whose children are the line's parts; a container's content between its opener and its
|
|
43
|
+
closer stays ordinary Markdown. Nothing inside a component line or an inline component is parsed as Markdown, except
|
|
44
|
+
its fallback. `COMPMD_NODES` names the nodes that are CompMD's own, for an editor that draws Markdown in place and
|
|
45
|
+
leaves these as their source.
|
|
46
|
+
|
|
47
|
+
## What it shares with CompMD's other grammars
|
|
48
|
+
|
|
49
|
+
It lives in [`compmd-grammars`](../README.md), beside the tree-sitter grammar, and reads the same text the same way:
|
|
50
|
+
|
|
51
|
+
- **The syntax's pieces** (a name, the line forms, a bare value, an escape, an interpolation, the frontmatter's key) are
|
|
52
|
+
`syntax/patterns.js`'s, and **each node's highlighting tag** is its token's in `syntax/tokens.json` (`NODE_TOKENS`
|
|
53
|
+
names each node's token, `TOKEN_TAGS` each token's tag), so a component's name has the same colour group as in every
|
|
54
|
+
other editor. The package is published on its own, so it carries a copy of both, `src/syntax.ts`, which
|
|
55
|
+
`pnpm run generate` writes and `pnpm test` checks.
|
|
56
|
+
- **The shared test set** (`tests/`) runs on it as on tree-sitter: each span's tag, and the spec's documents and the
|
|
57
|
+
conformance set, on which both grammars mark the same lines as malformed.
|
|
58
|
+
|
|
59
|
+
## Limits
|
|
60
|
+
|
|
61
|
+
- **Interpolation in a link's destination** (`[x]({{s.url}})`) isn't parsed.
|
|
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.
|
|
64
|
+
- **`$$` inside a paragraph** isn't display math.
|
|
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
|
|
66
|
+
they are.
|
|
67
|
+
- **A fenced code block's info string** is read in the param syntax only for a definition; other fences' stay
|
|
68
|
+
@lezer/markdown's.
|
|
69
|
+
|
|
70
|
+
## Development
|
|
71
|
+
|
|
72
|
+
From the repository's root (`pnpm install` there):
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
pnpm --dir lezer run generate # src/syntax.ts, after a change to syntax/
|
|
76
|
+
pnpm --dir lezer test # Vitest, and src/syntax.ts is current
|
|
77
|
+
pnpm --dir lezer lint # tsc
|
|
78
|
+
pnpm --dir lezer build # dist/
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
MIT
|
|
@@ -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.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { MarkdownConfig } from "@lezer/markdown";
|
|
2
|
+
/**
|
|
3
|
+
* CompMD's syntax (spec v1 §2.1, §2.3, §3, §7.1, §7.2, §8.1) for `@lezer/markdown`: frontmatter, component lines,
|
|
4
|
+
* inline components with their params and fallbacks, component definitions and signature fences, interpolation, wiki
|
|
5
|
+
* links, and math by Pandoc's rule. Use it with GFM,
|
|
6
|
+
* which CompMD's base syntax includes.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
|
10
|
+
* import { compmd } from "@compmd/lezer";
|
|
11
|
+
*
|
|
12
|
+
* const language = markdown({ base: markdownLanguage, extensions: [compmd] });
|
|
13
|
+
*/
|
|
14
|
+
export declare const compmd: MarkdownConfig;
|
package/dist/compmd.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// The grammar: CompMD's syntax as one @lezer/markdown extension.
|
|
2
|
+
import { endLeafAtComponentLine, parseComponentLineBlock } from "./component-line.js";
|
|
3
|
+
import { parseDefinition } from "./definition.js";
|
|
4
|
+
import { parseFrontmatter } from "./frontmatter.js";
|
|
5
|
+
import { compmdHighlighting } from "./highlighting.js";
|
|
6
|
+
import { parseInlineComponent } from "./inline-component.js";
|
|
7
|
+
import { parseInterpolation } from "./interpolation.js";
|
|
8
|
+
import { endLeafAtMathBlock, parseInlineMath, parseMathBlock } from "./math.js";
|
|
9
|
+
import { CEL_NODES, COMPONENT_LINES, OTHER_BLOCKS, PARTS } from "./nodes.js";
|
|
10
|
+
import { parseWikiLink } from "./wiki-link.js";
|
|
11
|
+
/**
|
|
12
|
+
* CompMD's syntax (spec v1 §2.1, §2.3, §3, §7.1, §7.2, §8.1) for `@lezer/markdown`: frontmatter, component lines,
|
|
13
|
+
* inline components with their params and fallbacks, component definitions and signature fences, interpolation, wiki
|
|
14
|
+
* links, and math by Pandoc's rule. Use it with GFM,
|
|
15
|
+
* which CompMD's base syntax includes.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
|
19
|
+
* import { compmd } from "@compmd/lezer";
|
|
20
|
+
*
|
|
21
|
+
* const language = markdown({ base: markdownLanguage, extensions: [compmd] });
|
|
22
|
+
*/
|
|
23
|
+
export const compmd = {
|
|
24
|
+
defineNodes: [
|
|
25
|
+
...[...COMPONENT_LINES, ...OTHER_BLOCKS].map((name) => ({ name, block: true })),
|
|
26
|
+
...PARTS,
|
|
27
|
+
...CEL_NODES,
|
|
28
|
+
],
|
|
29
|
+
props: [compmdHighlighting],
|
|
30
|
+
parseBlock: [
|
|
31
|
+
{ name: "Frontmatter", parse: parseFrontmatter, before: "HorizontalRule" },
|
|
32
|
+
{ name: "ComponentDefinition", parse: parseDefinition, before: "FencedCode" },
|
|
33
|
+
{ name: "ComponentLine", parse: parseComponentLineBlock, before: "FencedCode", endLeaf: endLeafAtComponentLine },
|
|
34
|
+
{ name: "MathBlock", parse: parseMathBlock, before: "FencedCode", endLeaf: endLeafAtMathBlock },
|
|
35
|
+
],
|
|
36
|
+
parseInline: [
|
|
37
|
+
{ name: "Interpolation", parse: parseInterpolation, before: "Emphasis" },
|
|
38
|
+
{ name: "InlineComponent", parse: parseInlineComponent, before: "Emphasis" },
|
|
39
|
+
{ name: "WikiLink", parse: parseWikiLink, before: "Link" },
|
|
40
|
+
{ name: "InlineMath", parse: parseInlineMath, before: "Emphasis" },
|
|
41
|
+
],
|
|
42
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { BlockContext, Element, Line } from "@lezer/markdown";
|
|
2
|
+
import type { ElementContext } from "./context.ts";
|
|
3
|
+
import type { ComponentLine } from "./nodes.ts";
|
|
4
|
+
/** A parsed component line: its node type and its children. */
|
|
5
|
+
interface Parsed {
|
|
6
|
+
readonly type: ComponentLine;
|
|
7
|
+
readonly children: readonly Element[];
|
|
8
|
+
}
|
|
9
|
+
/** Parses one line that starts with `::` (`rest`), at document position `start`; a line matching no form is malformed (F016). */
|
|
10
|
+
export declare function parseComponentLine(cx: ElementContext, rest: string, start: number): Parsed;
|
|
11
|
+
/** Whether `line` starts a component line: `::` at its start, indented less than code. */
|
|
12
|
+
export declare function startsComponentLine(line: Line): boolean;
|
|
13
|
+
/** The block parser: one component line, one block. */
|
|
14
|
+
export declare function parseComponentLineBlock(cx: BlockContext, line: Line): boolean;
|
|
15
|
+
/** Ends a paragraph at a component line, so it is never a paragraph's lazy continuation. */
|
|
16
|
+
export declare const endLeafAtComponentLine: (_cx: BlockContext, line: Line) => boolean;
|
|
17
|
+
export {};
|