@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.
@@ -0,0 +1,167 @@
1
+ // Component lines (spec §3): a container's opener `::: name {…}`, its closer `::: /name`, a continuation `::: + …`, a
2
+ // slot `:: #name`, and a leaf `:: name[fallback] {…}`. Each is a single-line block whose children are its parts; a
3
+ // container's content between opener and closer stays ordinary Markdown. The forms are `syntax/patterns.js`'s.
4
+ import { fallbackElement, invalidParamsElement, paramListElement, spanElements } from "./component-parts.js";
5
+ import { fallbackEnd } from "./fallback.js";
6
+ import { scanParamBody, scanParamList } from "./params.js";
7
+ import { PATTERNS } from "./syntax.js";
8
+ /** A line form's pattern, at the line's start. */
9
+ const form = (source) => new RegExp(`^${source}`);
10
+ const CONTINUATION = form(PATTERNS.lines.continuation);
11
+ const CLOSER = form(PATTERNS.lines.containerCloser);
12
+ const OPENER = form(PATTERNS.lines.containerOpener);
13
+ const SLOT = form(PATTERNS.lines.slot);
14
+ const LEAF = form(PATTERNS.lines.leaf);
15
+ /** A form's marks without what must follow them: a line with them that matches no form is malformed, not text. */
16
+ const CONTAINER_MARKS = form(`:::${PATTERNS.space}+`);
17
+ const CLOSER_MARKS = form(`:::${PATTERNS.space}+/`);
18
+ const SLOT_MARKS = form(`::${PATTERNS.space}+#`);
19
+ const MALFORMED = { type: "ComponentMalformed", children: [] };
20
+ /** Where each group of a form's match ends, as offsets into the line. */
21
+ function groupEnds(match) {
22
+ let at = 0;
23
+ return match.slice(1).map((group) => (at += group?.length ?? 0));
24
+ }
25
+ /** Builds the parts of one line, `rest` (the line from its `::`), which starts at document position `start`. */
26
+ class LineReader {
27
+ cx;
28
+ rest;
29
+ start;
30
+ constructor(cx, rest, start) {
31
+ this.cx = cx;
32
+ this.rest = rest;
33
+ this.start = start;
34
+ }
35
+ part(type, from, to) {
36
+ return this.cx.elt(type, this.start + from, this.start + to);
37
+ }
38
+ /** Whether only white space follows `from`. */
39
+ endsAt(from) {
40
+ return this.rest.slice(from).trim() === "";
41
+ }
42
+ /** The offset after white space from `from`. */
43
+ skipSpace(from) {
44
+ return from + (/^[ \t]*/.exec(this.rest.slice(from))?.[0].length ?? 0);
45
+ }
46
+ /**
47
+ * The param list at `from` as elements, and the offset after it; a list that isn't closed is invalid to the line's
48
+ * end, so the line keeps its form (spec §5). `undefined` without a `{` there.
49
+ */
50
+ params(from) {
51
+ if (this.rest[from] !== "{")
52
+ return undefined;
53
+ const list = scanParamList(this.rest, from);
54
+ if (list)
55
+ return { elements: [paramListElement(this.cx, list, this.rest, from, this.start)], end: list.end };
56
+ const end = this.rest.trimEnd().length;
57
+ return { elements: [invalidParamsElement(this.cx, from, end, this.start)], end };
58
+ }
59
+ paramBody(from) {
60
+ const body = scanParamBody(this.rest, from);
61
+ return { elements: spanElements(this.cx, body, this.rest, this.start), end: body.end };
62
+ }
63
+ fallback(from, to) {
64
+ return fallbackElement(this.cx, this.rest, from, to, this.start);
65
+ }
66
+ }
67
+ function continuation(line) {
68
+ const match = CONTINUATION.exec(line.rest);
69
+ if (!match)
70
+ return undefined;
71
+ const [marker, , plus] = groupEnds(match);
72
+ const body = line.paramBody(plus);
73
+ if (!line.endsAt(body.end))
74
+ return undefined;
75
+ return {
76
+ type: "ComponentContinuation",
77
+ children: [line.part("ComponentMark", 0, marker), line.part("ComponentMark", plus - 1, plus), ...body.elements],
78
+ };
79
+ }
80
+ function closer(line) {
81
+ const match = CLOSER.exec(line.rest);
82
+ if (!match)
83
+ return CLOSER_MARKS.test(line.rest) ? MALFORMED : undefined;
84
+ const [marker, , slash, name] = groupEnds(match);
85
+ if (!line.endsAt(name))
86
+ return MALFORMED;
87
+ return {
88
+ type: "ComponentClose",
89
+ children: [line.part("ComponentMark", 0, marker), line.part("ComponentMark", slash - 1, slash), line.part("ComponentName", slash, name)],
90
+ };
91
+ }
92
+ function opener(line) {
93
+ if (!CONTAINER_MARKS.test(line.rest))
94
+ return undefined;
95
+ const match = OPENER.exec(line.rest);
96
+ if (!match)
97
+ return MALFORMED;
98
+ const [marker, space, name] = groupEnds(match);
99
+ const params = line.params(line.skipSpace(name));
100
+ if (!line.endsAt(params?.end ?? name))
101
+ return MALFORMED;
102
+ return {
103
+ type: "ComponentOpen",
104
+ children: [line.part("ComponentMark", 0, marker), line.part("ComponentName", space, name), ...(params?.elements ?? [])],
105
+ };
106
+ }
107
+ function slot(line) {
108
+ const match = SLOT.exec(line.rest);
109
+ if (!match)
110
+ return SLOT_MARKS.test(line.rest) ? MALFORMED : undefined;
111
+ const [marker, , hash, name] = groupEnds(match);
112
+ if (!line.endsAt(name))
113
+ return MALFORMED;
114
+ return {
115
+ type: "ComponentSlot",
116
+ children: [line.part("ComponentMark", 0, marker), line.part("ComponentMark", hash - 1, hash), line.part("ComponentSlotName", hash, name)],
117
+ };
118
+ }
119
+ function leaf(line) {
120
+ const match = LEAF.exec(line.rest);
121
+ if (!match)
122
+ return undefined;
123
+ const [marker, space, name] = groupEnds(match);
124
+ const children = [line.part("ComponentMark", 0, marker), line.part("ComponentName", space, name)];
125
+ let end = name;
126
+ if (line.rest[end] === "[") {
127
+ const closed = fallbackEnd(line.rest, end);
128
+ if (closed === undefined)
129
+ return undefined;
130
+ children.push(line.fallback(end, closed));
131
+ end = closed;
132
+ }
133
+ const params = line.params(line.skipSpace(end));
134
+ if (params) {
135
+ children.push(...params.elements);
136
+ end = params.end;
137
+ }
138
+ return line.endsAt(end) ? { type: "ComponentLeaf", children } : undefined;
139
+ }
140
+ /** The forms in the order they are tried: the longest marks first. */
141
+ const FORMS = [continuation, closer, opener, slot, leaf];
142
+ /** Parses one line that starts with `::` (`rest`), at document position `start`; a line matching no form is malformed (F016). */
143
+ export function parseComponentLine(cx, rest, start) {
144
+ const line = new LineReader(cx, rest, start);
145
+ for (const tryForm of FORMS) {
146
+ const parsed = tryForm(line);
147
+ if (parsed)
148
+ return parsed;
149
+ }
150
+ return MALFORMED;
151
+ }
152
+ /** Whether `line` starts a component line: `::` at its start, indented less than code. */
153
+ export function startsComponentLine(line) {
154
+ return line.indent < line.baseIndent + 4 && line.text.startsWith("::", line.pos);
155
+ }
156
+ /** The block parser: one component line, one block. */
157
+ export function parseComponentLineBlock(cx, line) {
158
+ if (!startsComponentLine(line))
159
+ return false;
160
+ const start = cx.lineStart + line.pos;
161
+ const { type, children } = parseComponentLine(cx, line.text.slice(line.pos), start);
162
+ cx.addElement(cx.elt(type, start, cx.lineStart + line.text.trimEnd().length, children));
163
+ cx.nextLine();
164
+ return true;
165
+ }
166
+ /** Ends a paragraph at a component line, so it is never a paragraph's lazy continuation. */
167
+ export const endLeafAtComponentLine = (_cx, line) => startsComponentLine(line);
@@ -0,0 +1,11 @@
1
+ import type { Element } from "@lezer/markdown";
2
+ import type { ElementContext } from "./context.ts";
3
+ import type { Scanned } from "./params.ts";
4
+ /** The spans of `scanned` (offsets into `text`) as elements, `text` starting at document position `base`. */
5
+ export declare function spanElements(cx: ElementContext, scanned: Scanned, text: string, base: number): Element[];
6
+ /** A `ParamList` element for the list `{…}` from `from` (offsets into `text`, which starts at `base`). */
7
+ export declare function paramListElement(cx: ElementContext, list: Scanned, text: string, from: number, base: number): Element;
8
+ /** A `ParamInvalid` element: a param list that isn't closed, from its `{` at `from` to `to` (offsets into `text`). */
9
+ export declare function invalidParamsElement(cx: ElementContext, from: number, to: number, base: number): Element;
10
+ /** A `ComponentFallback` element for `[…]` from `from` to `to` (offsets into `text`), its inside parsed as inline Markdown. */
11
+ export declare function fallbackElement(cx: ElementContext, text: string, from: number, to: number, base: number): Element;
@@ -0,0 +1,51 @@
1
+ // The parts component lines and inline components share: a param list, and a fallback `[…]`.
2
+ import { parseCel } from "./cel-parse.js";
3
+ import { interpolationsIn } from "./interpolation.js";
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. */
23
+ function spanElement(cx, span, text, base) {
24
+ const parts = (span.parts ?? []).map((part) => spanElement(cx, part, text, base));
25
+ const children = [...parts, ...spanContent(cx, span, text, base)].sort((a, b) => a.from - b.from);
26
+ return cx.elt(span.type, base + span.from, base + span.to, children);
27
+ }
28
+ /** The spans of `scanned` (offsets into `text`) as elements, `text` starting at document position `base`. */
29
+ export function spanElements(cx, scanned, text, base) {
30
+ return scanned.spans.map((span) => spanElement(cx, span, text, base));
31
+ }
32
+ /** A `ParamList` element for the list `{…}` from `from` (offsets into `text`, which starts at `base`). */
33
+ export function paramListElement(cx, list, text, from, base) {
34
+ return cx.elt("ParamList", base + from, base + list.end, [
35
+ cx.elt("ParamBrace", base + from, base + from + 1),
36
+ ...spanElements(cx, list, text, base),
37
+ cx.elt("ParamBrace", base + list.end - 1, base + list.end),
38
+ ]);
39
+ }
40
+ /** A `ParamInvalid` element: a param list that isn't closed, from its `{` at `from` to `to` (offsets into `text`). */
41
+ export function invalidParamsElement(cx, from, to, base) {
42
+ return cx.elt("ParamInvalid", base + from, base + to);
43
+ }
44
+ /** A `ComponentFallback` element for `[…]` from `from` to `to` (offsets into `text`), its inside parsed as inline Markdown. */
45
+ export function fallbackElement(cx, text, from, to, base) {
46
+ return cx.elt("ComponentFallback", base + from, base + to, [
47
+ cx.elt("ComponentFallbackMark", base + from, base + from + 1),
48
+ ...cx.parser.parseInline(text.slice(from + 1, to - 1), base + from + 1),
49
+ cx.elt("ComponentFallbackMark", base + to - 1, base + to),
50
+ ]);
51
+ }
@@ -0,0 +1,6 @@
1
+ import type { Element, MarkdownParser } from "@lezer/markdown";
2
+ /** The part of a `BlockContext` or `InlineContext` the grammar's element builders use. */
3
+ export interface ElementContext {
4
+ elt(type: string, from: number, to: number, children?: readonly Element[]): Element;
5
+ readonly parser: MarkdownParser;
6
+ }
@@ -0,0 +1,3 @@
1
+ // What the grammar's parsers need from @lezer/markdown's block and inline contexts: making elements, and parsing a
2
+ // fallback's inline Markdown.
3
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { BlockContext, Line } from "@lezer/markdown";
2
+ /** The block parser: a definition or a signature fence, to its closing fence or the end of its container. */
3
+ export declare function parseDefinition(cx: BlockContext, line: Line): boolean;
@@ -0,0 +1,118 @@
1
+ // A component definition (spec §7.2) and a signature fence (§7.1): a fenced code block whose info string is `compmd`
2
+ // with a `component=` attribute. Its info string is read in the param syntax, the component's name as a name; its
3
+ // signature is the lines before the first `---` line, and a definition's body, after it, is CompMD again, parsed by
4
+ // the same parser. Any other fence stays @lezer/markdown's.
5
+ import { paramListElement, spanElements } from "./component-parts.js";
6
+ import { scanParamBody, scanParamList } from "./params.js";
7
+ /** A fence's opening line: its fence, then `compmd` and the rest of the info string. */
8
+ const OPENING = /^(`{3,}|~{3,})([ \t]*)compmd(?=[ \t]|$)/;
9
+ const LANGUAGE = "compmd";
10
+ /** The info string's attributes and param lists from `from`, until text that is neither. */
11
+ function scanInfo(text, from) {
12
+ const parts = [];
13
+ let at = from;
14
+ for (;;) {
15
+ while (text[at] === " " || text[at] === "\t")
16
+ at++;
17
+ const list = text[at] === "{";
18
+ const scanned = list ? scanParamList(text, at) : scanParamBody(text, at, "{");
19
+ if (!scanned || scanned.end === at)
20
+ return parts;
21
+ parts.push({ list, from: at, scanned });
22
+ at = scanned.end;
23
+ }
24
+ }
25
+ /** Whether `span` is the value of a `component` attribute, among `spans`. */
26
+ function isComponentName(text, spans, index) {
27
+ const key = spans[index - 2];
28
+ return spans[index].type === "ParamBare" && key?.type === "ParamKey" && text.slice(key.from, key.to) === "component";
29
+ }
30
+ /** Whether the info string names a component. */
31
+ function namesComponent(text, parts) {
32
+ return parts.some((part) => !part.list && part.scanned.spans.some((_, i) => isComponentName(text, part.scanned.spans, i)));
33
+ }
34
+ /** The info string's elements, `text` starting at document position `base`; the component's name is a `ComponentName`. */
35
+ function infoElements(cx, text, parts, base) {
36
+ return parts.flatMap(({ list, from, scanned }) => {
37
+ if (list)
38
+ return [paramListElement(cx, scanned, text, from, base)];
39
+ const elements = spanElements(cx, scanned, text, base);
40
+ return elements.map((element, i) => isComponentName(text, scanned.spans, i) ? cx.elt("ComponentName", element.from, element.to) : element);
41
+ });
42
+ }
43
+ /** Whether `line` closes a fence opened by `fence`: the same character, at least as many, then only white space. */
44
+ function closes(line, fence) {
45
+ const run = /^(`+|~+)[ \t]*$/.exec(line.text.slice(line.pos));
46
+ return line.indent < line.baseIndent + 4 && !!run && run[1][0] === fence[0] && run[1].length >= fence.length;
47
+ }
48
+ /** `lines` as one element of `type`; a body's CompMD is parsed again when its lines are the document's as they are. */
49
+ function linesElement(cx, type, lines, nested) {
50
+ if (lines.length === 0)
51
+ return [];
52
+ const from = lines[0].from;
53
+ const to = lines[lines.length - 1].to;
54
+ const parsed = nested && lines.every((line) => line.whole);
55
+ const children = parsed ? [cx.elt(cx.parser.parse(lines.map((line) => line.text).join("\n")), from)] : [];
56
+ return [cx.elt(type, from, to, children)];
57
+ }
58
+ /** The block parser: a definition or a signature fence, to its closing fence or the end of its container. */
59
+ export function parseDefinition(cx, line) {
60
+ if (line.indent >= line.baseIndent + 4)
61
+ return false;
62
+ const text = line.text.slice(line.pos);
63
+ const opening = OPENING.exec(text);
64
+ if (!opening)
65
+ return false;
66
+ const fence = opening[1];
67
+ const languageFrom = opening[0].length - LANGUAGE.length;
68
+ if (fence[0] === "`" && text.includes("`", fence.length))
69
+ return false;
70
+ const parts = scanInfo(text, opening[0].length);
71
+ if (!namesComponent(text, parts))
72
+ return false;
73
+ const start = cx.lineStart + line.pos;
74
+ const opened = [
75
+ cx.elt("CodeMark", start, start + fence.length),
76
+ cx.elt("CodeInfo", start + languageFrom, start + opening[0].length),
77
+ cx.elt("DefinitionInfo", start + opening[0].length, start + text.trimEnd().length, infoElements(cx, text, parts, start)),
78
+ ];
79
+ const signature = [];
80
+ const body = [];
81
+ let separator;
82
+ let closing;
83
+ let end = start + text.trimEnd().length;
84
+ while (cx.nextLine()) {
85
+ if (closes(line, fence)) {
86
+ const from = cx.lineStart + line.pos;
87
+ end = from + line.text.slice(line.pos).trimEnd().length;
88
+ closing = cx.elt("CodeMark", from, end);
89
+ cx.nextLine();
90
+ break;
91
+ }
92
+ const content = {
93
+ from: cx.lineStart + line.basePos,
94
+ to: cx.lineStart + line.text.length,
95
+ text: line.text.slice(line.basePos),
96
+ whole: line.basePos === 0,
97
+ };
98
+ if (!separator && content.text.trimEnd() === "---")
99
+ separator = cx.elt("DefinitionSeparator", content.from, content.from + 3);
100
+ else
101
+ (separator ? body : signature).push(content);
102
+ }
103
+ if (!closing) {
104
+ const last = separator ? body : signature;
105
+ while (last.length && last[last.length - 1].text.trim() === "")
106
+ last.pop();
107
+ end = last[last.length - 1]?.to ?? separator?.to ?? end;
108
+ }
109
+ const children = [
110
+ ...opened,
111
+ ...linesElement(cx, "DefinitionSignature", signature, false),
112
+ ...(separator ? [separator] : []),
113
+ ...linesElement(cx, "DefinitionBody", body, true),
114
+ ...(closing ? [closing] : []),
115
+ ];
116
+ cx.addElement(cx.elt("ComponentDefinition", start, end, children));
117
+ return true;
118
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The offset after the `]` that closes a fallback whose `[` is at `from`. Brackets nest, `\[` and `\]` don't count, and
3
+ * code spans bind tighter, so a `]` inside backticks doesn't close it.
4
+ *
5
+ * @returns the offset after the closing `]`, or `undefined` when the fallback isn't closed in `text`.
6
+ *
7
+ * @example
8
+ * fallbackEnd("[a [b] c] rest", 0); // 9
9
+ */
10
+ export declare function fallbackEnd(text: string, from: number): number | undefined;
@@ -0,0 +1,31 @@
1
+ // A component's fallback text, `[…]` (spec §4.4): where it ends.
2
+ /**
3
+ * The offset after the `]` that closes a fallback whose `[` is at `from`. Brackets nest, `\[` and `\]` don't count, and
4
+ * code spans bind tighter, so a `]` inside backticks doesn't close it.
5
+ *
6
+ * @returns the offset after the closing `]`, or `undefined` when the fallback isn't closed in `text`.
7
+ *
8
+ * @example
9
+ * fallbackEnd("[a [b] c] rest", 0); // 9
10
+ */
11
+ export function fallbackEnd(text, from) {
12
+ let depth = 0;
13
+ for (let at = from; at < text.length; at++) {
14
+ const char = text[at];
15
+ if (char === "\\")
16
+ at++;
17
+ else if (char === "`")
18
+ at = codeSpanEnd(text, at) - 1;
19
+ else if (char === "[")
20
+ depth++;
21
+ else if (char === "]" && --depth === 0)
22
+ return at + 1;
23
+ }
24
+ return undefined;
25
+ }
26
+ /** The offset after the code span whose opening backticks are at `from`, or after the backticks if it isn't closed. */
27
+ function codeSpanEnd(text, from) {
28
+ const run = /^`+/.exec(text.slice(from))[0];
29
+ const close = text.indexOf(run, from + run.length);
30
+ return close >= 0 ? close + run.length : from + run.length;
31
+ }
@@ -0,0 +1,3 @@
1
+ import type { BlockContext, Line } from "@lezer/markdown";
2
+ /** The block parser: from a first line `---` or `+++` to the next such line. Without a closing line, it isn't frontmatter. */
3
+ export declare function parseFrontmatter(cx: BlockContext, line: Line): boolean;
@@ -0,0 +1,38 @@
1
+ // Frontmatter (spec §2.1): a block at the document's start between `---` lines (YAML) or `+++` lines (TOML). Its
2
+ // lines are never Markdown, so `---` doesn't become a rule or a setext heading. The `md` key, everything CompMD
3
+ // reads, is found by `syntax/patterns.js`'s `frontmatterKey`.
4
+ import { PATTERNS } from "./syntax.js";
5
+ /** Each delimiter line, with the pattern of its format's `md` key at a line's start. */
6
+ const FORMATS = {
7
+ "---": new RegExp(PATTERNS.frontmatterKey.yaml),
8
+ "+++": new RegExp(PATTERNS.frontmatterKey.toml),
9
+ };
10
+ const KEY = "md";
11
+ /** The `FrontmatterKey` on the line `text`, which starts at document position `start`, if it has one. */
12
+ function keyOn(cx, key, text, start) {
13
+ const match = key.exec(text);
14
+ if (!match)
15
+ return undefined;
16
+ const from = start + match[0].lastIndexOf(KEY);
17
+ return cx.elt("FrontmatterKey", from, from + KEY.length);
18
+ }
19
+ /** The block parser: from a first line `---` or `+++` to the next such line. Without a closing line, it isn't frontmatter. */
20
+ export function parseFrontmatter(cx, line) {
21
+ const key = FORMATS[line.text];
22
+ if (cx.lineStart !== 0 || !key)
23
+ return false;
24
+ const delimiter = line.text;
25
+ const keys = [];
26
+ while (cx.nextLine()) {
27
+ if (line.text === delimiter) {
28
+ const end = cx.lineStart + delimiter.length;
29
+ cx.addElement(cx.elt("Frontmatter", 0, end, [cx.elt("FrontmatterMark", 0, 3), ...keys, cx.elt("FrontmatterMark", end - 3, end)]));
30
+ cx.nextLine();
31
+ return true;
32
+ }
33
+ const found = keyOn(cx, key, line.text, cx.lineStart);
34
+ if (found)
35
+ keys.push(found);
36
+ }
37
+ return false;
38
+ }
@@ -0,0 +1,12 @@
1
+ import { Tag } from "@lezer/highlight";
2
+ import { type Token } from "./syntax.ts";
3
+ /** The token each of the grammar's nodes stands for. */
4
+ export declare const NODE_TOKENS: Readonly<Record<string, Token>>;
5
+ /**
6
+ * The tag a token's tag name stands for: a `@lezer/highlight` tag (`tagName`), or one modified (`special(string)`).
7
+ *
8
+ * @throws when the name isn't one: `tokens.json` names a tag `@lezer/highlight` doesn't have.
9
+ */
10
+ export declare function tagNamed(name: string): Tag;
11
+ /** The `styleTags` prop for the grammar's nodes. */
12
+ export declare const compmdHighlighting: import("@lezer/common").NodePropSource;
@@ -0,0 +1,84 @@
1
+ // Highlighting tags for the grammar's nodes. A node that is one of CompMD's shared tokens takes the token's tag
2
+ // (`syntax/tokens.json`, through `syntax.ts`), so a name has the same colour group as in every other editor; the rest
3
+ // are the grammar's own.
4
+ import { styleTags, Tag, tags as t } from "@lezer/highlight";
5
+ import { TOKEN_TAGS } from "./syntax.js";
6
+ /** The token each of the grammar's nodes stands for. */
7
+ export const NODE_TOKENS = {
8
+ ComponentMark: "component-marker",
9
+ ComponentName: "component-name",
10
+ ComponentSlotName: "slot-name",
11
+ ComponentFallbackMark: "fallback-bracket",
12
+ ParamBrace: "param-brace",
13
+ ParamKey: "param-key",
14
+ ParamBreakpoint: "breakpoint",
15
+ ParamOperator: "param-operator",
16
+ ParamClassMark: "param-class",
17
+ ParamClassName: "param-class",
18
+ ParamIdMark: "param-id",
19
+ ParamIdName: "param-id",
20
+ ParamString: "param-string",
21
+ ParamEscape: "string-escape",
22
+ ParamBare: "param-bare",
23
+ ParamExpressionMark: "expression-paren",
24
+ InterpolationMark: "interpolation-brace",
25
+ InterpolationExpression: "interpolation-path",
26
+ WikiLinkTarget: "wiki-link-target",
27
+ WikiLinkLabel: "wiki-link-label",
28
+ InlineMath: "math",
29
+ MathBlock: "math",
30
+ FrontmatterKey: "frontmatter-key",
31
+ DefinitionSeparator: "definition-separator",
32
+ };
33
+ /** The nodes that are no token of their own: what is inside them is another language's, or a mark. */
34
+ const OWN_TAGS = {
35
+ "WikiLinkMark InlineMathMark MathBlockMark FrontmatterMark": t.processingInstruction,
36
+ ParamExpression: t.special(t.variableName),
37
+ ParamJson: t.literal,
38
+ "ComponentMalformed ParamInvalid": t.invalid,
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,
58
+ };
59
+ const MODIFIERS = {
60
+ special: t.special,
61
+ definition: t.definition,
62
+ constant: t.constant,
63
+ function: t.function,
64
+ standard: t.standard,
65
+ local: t.local,
66
+ };
67
+ /**
68
+ * The tag a token's tag name stands for: a `@lezer/highlight` tag (`tagName`), or one modified (`special(string)`).
69
+ *
70
+ * @throws when the name isn't one: `tokens.json` names a tag `@lezer/highlight` doesn't have.
71
+ */
72
+ export function tagNamed(name) {
73
+ const modified = /^(\w+)\((\w+)\)$/.exec(name);
74
+ const modifier = modified ? MODIFIERS[modified[1]] : undefined;
75
+ const base = t[modified ? modified[2] : name];
76
+ if (!(base instanceof Tag) || (modified && !modifier))
77
+ throw new Error(`no Lezer tag ${name}`);
78
+ return modifier ? modifier(base) : base;
79
+ }
80
+ /** The `styleTags` prop for the grammar's nodes. */
81
+ export const compmdHighlighting = styleTags({
82
+ ...Object.fromEntries(Object.entries(NODE_TOKENS).map(([node, token]) => [node, tagNamed(TOKEN_TAGS[token])])),
83
+ ...OWN_TAGS,
84
+ });
@@ -0,0 +1,5 @@
1
+ export { CEL_TOP, celParser } from "./cel-parser.ts";
2
+ export { compmd } from "./compmd.ts";
3
+ export { compmdHighlighting, NODE_TOKENS, tagNamed } from "./highlighting.ts";
4
+ export { TOKEN_TAGS, type Token } from "./syntax.ts";
5
+ export { CEL_NODES, type CelNodeName, COMPMD_NODES, COMPONENT_LINES, type ComponentLine } from "./nodes.ts";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { CEL_TOP, celParser } from "./cel-parser.js";
2
+ export { compmd } from "./compmd.js";
3
+ export { compmdHighlighting, NODE_TOKENS, tagNamed } from "./highlighting.js";
4
+ export { TOKEN_TAGS } from "./syntax.js";
5
+ export { CEL_NODES, COMPMD_NODES, COMPONENT_LINES } from "./nodes.js";
@@ -0,0 +1,3 @@
1
+ import type { InlineContext } from "@lezer/markdown";
2
+ /** The inline parser. A fallback is required; `{{` right after it starts an interpolation, not a param list (spec §3.1). */
3
+ export declare function parseInlineComponent(cx: InlineContext, next: number, pos: number): number;
@@ -0,0 +1,36 @@
1
+ // Inline components, `:name[fallback]{…}` (spec §3.2).
2
+ import { fallbackElement, paramListElement } from "./component-parts.js";
3
+ import { fallbackEnd } from "./fallback.js";
4
+ import { scanParamList } from "./params.js";
5
+ import { PATTERNS } from "./syntax.js";
6
+ const COLON = 58;
7
+ /** `:name[`, an inline component's start (`syntax/patterns.js`). */
8
+ const START = new RegExp(`^${PATTERNS.inlineComponentStart}`);
9
+ /** Where an inline component may start (spec §3.2 rule 4): at the start, or after white space or punctuation other than `:` and `\`. */
10
+ function mayStartAt(cx, pos) {
11
+ if (pos === cx.offset)
12
+ return true;
13
+ const before = String.fromCharCode(cx.char(pos - 1));
14
+ return /\s/.test(before) || (/[\p{P}\p{S}]/u.test(before) && before !== ":" && before !== "\\");
15
+ }
16
+ /** The inline parser. A fallback is required; `{{` right after it starts an interpolation, not a param list (spec §3.1). */
17
+ export function parseInlineComponent(cx, next, pos) {
18
+ if (next !== COLON || !mayStartAt(cx, pos))
19
+ return -1;
20
+ const text = cx.slice(pos, cx.end);
21
+ const start = START.exec(text);
22
+ if (!start)
23
+ return -1;
24
+ const fallbackAt = start[0].length - 1;
25
+ const fallback = fallbackEnd(text, fallbackAt);
26
+ if (fallback === undefined)
27
+ return -1;
28
+ const list = text.startsWith("{{", fallback) ? undefined : scanParamList(text, fallback);
29
+ const children = [
30
+ cx.elt("ComponentMark", pos, pos + 1),
31
+ cx.elt("ComponentName", pos + 1, pos + fallbackAt),
32
+ fallbackElement(cx, text, fallbackAt, fallback, pos),
33
+ ...(list ? [paramListElement(cx, list, text, fallback, pos)] : []),
34
+ ];
35
+ return cx.addElement(cx.elt("InlineComponent", pos, pos + (list?.end ?? fallback), children));
36
+ }
@@ -0,0 +1,6 @@
1
+ import type { Element, InlineContext } from "@lezer/markdown";
2
+ import type { ElementContext } from "./context.ts";
3
+ /** The interpolations in a quoted param string `text`, which starts at document position `base`. `\{{` isn't one. */
4
+ export declare function interpolationsIn(cx: ElementContext, text: string, base: number): Element[];
5
+ /** The inline parser: `{{path}}` in text and fallbacks. An escaped `\{{` is left to Markdown's escapes. */
6
+ export declare function parseInterpolation(cx: InlineContext, next: number, pos: number): number;