@aufbau/syntax 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The `@syntax` annotation vocabulary — the "little extra metadata" that
3
+ * turns an MM0 theory into a full surface-language spec.
4
+ *
5
+ * Annotations ride MM0's `--|` doc-comment channel, the same one Aufbau uses
6
+ * for `@acui`, `@congr`, `@rewrite`, and the rest. Anything that is not
7
+ * `@syntax` is *foreign*: preserved untouched for whoever owns it, never
8
+ * interpreted here. The library also owns stripping `@syntax` lines before a theory is
9
+ * handed to the engine, which currently rejects annotations it does not
10
+ * know.
11
+ *
12
+ * Attachment rules (checked by the spec builder, not here):
13
+ * - `juxtaposed` attaches to a binary term whose arguments and result
14
+ * share one sort (adjacency of that sort's expressions denotes it);
15
+ * - `elided` attaches to a nullary term (supplied when an argument of
16
+ * its sort is missing, dropped again when printing);
17
+ * - `role` attaches to a `term` or `def`;
18
+ * - everything else is spec-wide and may sit on any statement.
19
+ *
20
+ * The lexicon itself needs no `@syntax` at all: letters are ordinary term
21
+ * declarations, and variables ride the engine's own `@vars` annotation.
22
+ */
23
+ import { diagnostic } from "../diagnostics.js";
24
+ export const LINT_NAMES = [
25
+ "parenthesize-binary-only",
26
+ "closed-sentences",
27
+ ];
28
+ const TEMPLATES = {
29
+ syntax_unknown_subcommand: "unknown @syntax subcommand {subcommand}",
30
+ syntax_bad_flag: "@syntax {flag} takes no arguments",
31
+ syntax_bad_brackets: "bracket pairs come as: <open> <close> [<open> <close>…]",
32
+ syntax_bad_assoc_none: "@syntax assoc-none wants one precedence number",
33
+ syntax_unknown_lint: "unknown lint {name}; known lints: {known}",
34
+ syntax_bad_display: "@syntax display wants drop-outer-parens or rotate-brackets <pairs…>",
35
+ syntax_bad_elab: "@syntax elab wants: elab $ <pattern> $ => $ <template> $ [input-only]",
36
+ syntax_bad_pattern_element: "cannot read pattern element {element}",
37
+ syntax_bad_template_element: "cannot read template element {element}",
38
+ syntax_bad_role: "@syntax role wants one role name",
39
+ };
40
+ function fail(id, params, span) {
41
+ const template = TEMPLATES[id] ?? id;
42
+ return {
43
+ annotation: null,
44
+ diagnostic: diagnostic(id, template, params, span),
45
+ };
46
+ }
47
+ function ok(annotation) {
48
+ return { annotation, diagnostic: null };
49
+ }
50
+ function parsePairs(words) {
51
+ if (words.length === 0 || words.length % 2 !== 0) {
52
+ return null;
53
+ }
54
+ const pairs = [];
55
+ for (let i = 0; i < words.length; i += 2) {
56
+ const open = words[i];
57
+ const close = words[i + 1];
58
+ if (open === undefined || close === undefined || open === close) {
59
+ return null;
60
+ }
61
+ pairs.push([open, close]);
62
+ }
63
+ return pairs;
64
+ }
65
+ const CAPTURE = /^\?([A-Za-z_][A-Za-z0-9_]*):([A-Za-z_][A-Za-z0-9_]*)([+?]?)$/;
66
+ const REFERENCE = /^\?([A-Za-z_][A-Za-z0-9_]*)(?:(.)\*)?$/;
67
+ function parsePattern(text) {
68
+ const elements = [];
69
+ for (const word of text.split(/\s+/).filter((w) => w.length > 0)) {
70
+ if (word.startsWith("?")) {
71
+ const match = CAPTURE.exec(word);
72
+ if (match === null) {
73
+ return word;
74
+ }
75
+ elements.push({
76
+ kind: "capture",
77
+ name: match[1] ?? "",
78
+ class: match[2] ?? "",
79
+ quantifier: (match[3] ?? ""),
80
+ });
81
+ continue;
82
+ }
83
+ elements.push({ kind: "literal", token: word });
84
+ }
85
+ return elements;
86
+ }
87
+ function parseTemplate(text) {
88
+ const elements = [];
89
+ for (const word of text.split(/\s+/).filter((w) => w.length > 0)) {
90
+ if (word.startsWith("?")) {
91
+ const match = REFERENCE.exec(word);
92
+ if (match === null) {
93
+ return word;
94
+ }
95
+ elements.push({
96
+ kind: "reference",
97
+ name: match[1] ?? "",
98
+ separator: match[2] ?? null,
99
+ });
100
+ continue;
101
+ }
102
+ elements.push({ kind: "literal", token: word });
103
+ }
104
+ return elements;
105
+ }
106
+ const ELAB = /^\$(.*?)\$\s*=>\s*\$(.*?)\$\s*(input-only)?\s*$/s;
107
+ /**
108
+ * Parse one annotation payload (the text after `--|`). Returns null for a
109
+ * foreign annotation — anything that does not begin `@syntax`.
110
+ */
111
+ export function parseSyntaxAnnotation(text, span) {
112
+ const trimmed = text.trim();
113
+ if (!trimmed.startsWith("@syntax")) {
114
+ return null;
115
+ }
116
+ const rest = trimmed.slice("@syntax".length).trim();
117
+ const words = rest.split(/\s+/).filter((w) => w.length > 0);
118
+ const subcommand = words[0];
119
+ switch (subcommand) {
120
+ case "juxtaposed":
121
+ case "elided": {
122
+ if (words.length !== 1) {
123
+ return fail("syntax_bad_flag", { flag: subcommand }, span);
124
+ }
125
+ return ok({ kind: subcommand });
126
+ }
127
+ case "brackets": {
128
+ const pairs = parsePairs(words.slice(1));
129
+ if (pairs === null) {
130
+ return fail("syntax_bad_brackets", {}, span);
131
+ }
132
+ return ok({ kind: "brackets", pairs });
133
+ }
134
+ case "assoc-none": {
135
+ const number = words[1];
136
+ if (words.length !== 2 ||
137
+ number === undefined ||
138
+ !/^\d+$/.test(number)) {
139
+ return fail("syntax_bad_assoc_none", {}, span);
140
+ }
141
+ return ok({ kind: "assoc-none", prec: Number.parseInt(number, 10) });
142
+ }
143
+ case "lint": {
144
+ const name = words[1];
145
+ if (words.length !== 2 ||
146
+ name === undefined ||
147
+ !LINT_NAMES.includes(name)) {
148
+ return fail("syntax_unknown_lint", { name: name ?? "", known: LINT_NAMES.join(", ") }, span);
149
+ }
150
+ return ok({ kind: "lint", name: name });
151
+ }
152
+ case "display": {
153
+ if (words[1] === "drop-outer-parens" && words.length === 2) {
154
+ return ok({ kind: "display-drop-outer-parens" });
155
+ }
156
+ if (words[1] === "rotate-brackets") {
157
+ const pairs = parsePairs(words.slice(2));
158
+ if (pairs !== null) {
159
+ return ok({ kind: "display-rotate-brackets", pairs });
160
+ }
161
+ }
162
+ return fail("syntax_bad_display", {}, span);
163
+ }
164
+ case "elab": {
165
+ const match = ELAB.exec(rest.slice("elab".length).trim());
166
+ if (match === null) {
167
+ return fail("syntax_bad_elab", {}, span);
168
+ }
169
+ const pattern = parsePattern(match[1] ?? "");
170
+ if (typeof pattern === "string") {
171
+ return fail("syntax_bad_pattern_element", { element: pattern }, span);
172
+ }
173
+ const template = parseTemplate(match[2] ?? "");
174
+ if (typeof template === "string") {
175
+ return fail("syntax_bad_template_element", { element: template }, span);
176
+ }
177
+ return ok({
178
+ kind: "elab",
179
+ rule: {
180
+ inputOnly: match[3] === "input-only",
181
+ pattern,
182
+ span,
183
+ template,
184
+ },
185
+ });
186
+ }
187
+ case "role": {
188
+ const role = words[1];
189
+ if (words.length !== 2 || role === undefined) {
190
+ return fail("syntax_bad_role", {}, span);
191
+ }
192
+ return ok({ kind: "role", role });
193
+ }
194
+ default:
195
+ return fail("syntax_unknown_subcommand", { subcommand: subcommand ?? "(none)" }, span);
196
+ }
197
+ }
198
+ //# sourceMappingURL=annotations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"annotations.js","sourceRoot":"","sources":["../../src/reader/annotations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAmB,UAAU,EAAa,MAAM,mBAAmB,CAAC;AAE3E,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,0BAA0B;IAC1B,kBAAkB;CACV,CAAC;AA2EX,MAAM,SAAS,GAA2B;IACxC,yBAAyB,EAAE,yCAAyC;IACpE,eAAe,EAAE,mCAAmC;IACpD,mBAAmB,EACjB,yDAAyD;IAC3D,qBAAqB,EAAE,gDAAgD;IACvE,mBAAmB,EAAE,2CAA2C;IAChE,kBAAkB,EAChB,qEAAqE;IACvE,eAAe,EACb,uEAAuE;IACzE,0BAA0B,EAAE,uCAAuC;IACnE,2BAA2B,EAAE,wCAAwC;IACrE,eAAe,EAAE,kCAAkC;CACpD,CAAC;AAEF,SAAS,IAAI,CACX,EAAU,EACV,MAA8B,EAC9B,IAAU;IAEV,MAAM,QAAQ,GAAG,S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,EAAE,EACrB,IAAI,CACL,CAAC;YACJ,CAAC;YAED,OAAO,EAAE,CAAC;gBACR,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE;oBACJ,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC,KAAK,YAAY;oBACpC,OAAO;oBACP,IAAI;oBACJ,QAAQ;iBACT;aACF,CAAC,CAAC;QACL,CAAC;QAED,KAAK,MAAM,CAAC,CAAC,CAAC;YACZ,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAEtB,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC7C,OAAO,IAAI,CAAC,iBAAiB,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;YAC3C,CAAC;YAED,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACpC,CAAC;QAED;YACE,OAAO,IAAI,CACT,2BAA2B,EAC3B,EAAE,UAAU,EAAE,UAAU,IAAI,QAAQ,EAAE,EACtC,IAAI,CACL,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["/**\n * The `@syntax` annotation vocabulary — the \"little extra metadata\" that\n * turns an MM0 theory into a full surface-language spec.\n *\n * Annotations ride MM0's `--|` doc-comment channel, the same one Aufbau uses\n * for `@acui`, `@congr`, `@rewrite`, and the rest. Anything that is not\n * `@syntax` is *foreign*: preserved untouched for whoever owns it, never\n * interpreted here. The library also owns stripping `@syntax` lines before a theory is\n * handed to the engine, which currently rejects annotations it does not\n * know.\n *\n * Attachment rules (checked by the spec builder, not here):\n * - `juxtaposed` attaches to a binary term whose arguments and result\n * share one sort (adjacency of that sort's expressions denotes it);\n * - `elided` attaches to a nullary term (supplied when an argument of\n * its sort is missing, dropped again when printing);\n * - `role` attaches to a `term` or `def`;\n * - everything else is spec-wide and may sit on any statement.\n *\n * The lexicon itself needs no `@syntax` at all: letters are ordinary term\n * declarations, and variables ride the engine's own `@vars` annotation.\n */\n\nimport { type Diagnostic, diagnostic, type Span } from \"../diagnostics.js\";\n\nexport const LINT_NAMES = [\n \"parenthesize-binary-only\",\n \"closed-sentences\",\n] as const;\n\nexport type LintName = (typeof LINT_NAMES)[number];\n\n/** A capture in an elab pattern: `?ts:tm+` — name, class, quantifier. */\nexport interface RuleCapture {\n readonly kind: \"capture\";\n readonly name: string;\n /** A sort name; a leaf whose sort coerces into it matches. */\n readonly class: string;\n readonly quantifier: \"\" | \"+\" | \"?\";\n}\n\nexport interface RuleLiteral {\n readonly kind: \"literal\";\n readonly token: string;\n}\n\nexport type RulePatternElement = RuleCapture | RuleLiteral;\n\n/** A capture reference in an elab template: `?ts` or joined `?ts,*`. */\nexport interface RuleReference {\n readonly kind: \"reference\";\n readonly name: string;\n /** For a `+` capture, the token to join repeats with; null joins bare. */\n readonly separator: string | null;\n}\n\nexport type RuleTemplateElement = RuleLiteral | RuleReference;\n\nexport interface ElabRule {\n readonly inputOnly: boolean;\n readonly pattern: readonly RulePatternElement[];\n readonly span: Span;\n readonly template: readonly RuleTemplateElement[];\n}\n\nexport type SyntaxAnnotation =\n | {\n readonly kind: \"assoc-none\";\n readonly prec: number;\n }\n | {\n readonly kind: \"brackets\";\n readonly pairs: readonly (readonly [string, string])[];\n }\n | {\n readonly kind: \"display-drop-outer-parens\";\n }\n | {\n readonly kind: \"display-rotate-brackets\";\n readonly pairs: readonly (readonly [string, string])[];\n }\n | {\n /** A bidirectional token rule: elaborate in, delaborate out. */\n readonly kind: \"elab\";\n readonly rule: ElabRule;\n }\n | {\n /** Supplied when an argument of its sort is missing; drops on print. */\n readonly kind: \"elided\";\n }\n | {\n /** Adjacency of this combiner's sort denotes it — `Fxy`, `ab`. */\n readonly kind: \"juxtaposed\";\n }\n | {\n readonly kind: \"lint\";\n readonly name: LintName;\n }\n | {\n readonly kind: \"role\";\n readonly role: string;\n };\n\nconst TEMPLATES: Record<string, string> = {\n syntax_unknown_subcommand: \"unknown @syntax subcommand {subcommand}\",\n syntax_bad_flag: \"@syntax {flag} takes no arguments\",\n syntax_bad_brackets:\n \"bracket pairs come as: <open> <close> [<open> <close>…]\",\n syntax_bad_assoc_none: \"@syntax assoc-none wants one precedence number\",\n syntax_unknown_lint: \"unknown lint {name}; known lints: {known}\",\n syntax_bad_display:\n \"@syntax display wants drop-outer-parens or rotate-brackets <pairs…>\",\n syntax_bad_elab:\n \"@syntax elab wants: elab $ <pattern> $ => $ <template> $ [input-only]\",\n syntax_bad_pattern_element: \"cannot read pattern element {element}\",\n syntax_bad_template_element: \"cannot read template element {element}\",\n syntax_bad_role: \"@syntax role wants one role name\",\n};\n\nfunction fail(\n id: string,\n params: Record<string, string>,\n span: Span,\n): { annotation: null; diagnostic: Diagnostic } {\n const template = TEMPLATES[id] ?? id;\n return {\n annotation: null,\n diagnostic: diagnostic(id, template, params, span),\n };\n}\n\nfunction ok(annotation: SyntaxAnnotation): {\n annotation: SyntaxAnnotation;\n diagnostic: null;\n} {\n return { annotation, diagnostic: null };\n}\n\nexport type SyntaxAnnotationResult =\n | { readonly annotation: SyntaxAnnotation; readonly diagnostic: null }\n | { readonly annotation: null; readonly diagnostic: Diagnostic };\n\nfunction parsePairs(\n words: readonly string[],\n): (readonly [string, string])[] | null {\n if (words.length === 0 || words.length % 2 !== 0) {\n return null;\n }\n\n const pairs: (readonly [string, string])[] = [];\n\n for (let i = 0; i < words.length; i += 2) {\n const open = words[i];\n const close = words[i + 1];\n\n if (open === undefined || close === undefined || open === close) {\n return null;\n }\n\n pairs.push([open, close]);\n }\n\n return pairs;\n}\n\nconst CAPTURE =\n /^\\?([A-Za-z_][A-Za-z0-9_]*):([A-Za-z_][A-Za-z0-9_]*)([+?]?)$/;\nconst REFERENCE = /^\\?([A-Za-z_][A-Za-z0-9_]*)(?:(.)\\*)?$/;\n\nfunction parsePattern(text: string): readonly RulePatternElement[] | string {\n const elements: RulePatternElement[] = [];\n\n for (const word of text.split(/\\s+/).filter((w) => w.length > 0)) {\n if (word.startsWith(\"?\")) {\n const match = CAPTURE.exec(word);\n\n if (match === null) {\n return word;\n }\n\n elements.push({\n kind: \"capture\",\n name: match[1] ?? \"\",\n class: match[2] ?? \"\",\n quantifier: (match[3] ?? \"\") as \"\" | \"+\" | \"?\",\n });\n continue;\n }\n\n elements.push({ kind: \"literal\", token: word });\n }\n\n return elements;\n}\n\nfunction parseTemplate(\n text: string,\n): readonly RuleTemplateElement[] | string {\n const elements: RuleTemplateElement[] = [];\n\n for (const word of text.split(/\\s+/).filter((w) => w.length > 0)) {\n if (word.startsWith(\"?\")) {\n const match = REFERENCE.exec(word);\n\n if (match === null) {\n return word;\n }\n\n elements.push({\n kind: \"reference\",\n name: match[1] ?? \"\",\n separator: match[2] ?? null,\n });\n continue;\n }\n\n elements.push({ kind: \"literal\", token: word });\n }\n\n return elements;\n}\n\nconst ELAB = /^\\$(.*?)\\$\\s*=>\\s*\\$(.*?)\\$\\s*(input-only)?\\s*$/s;\n\n/**\n * Parse one annotation payload (the text after `--|`). Returns null for a\n * foreign annotation — anything that does not begin `@syntax`.\n */\nexport function parseSyntaxAnnotation(\n text: string,\n span: Span,\n): SyntaxAnnotationResult | null {\n const trimmed = text.trim();\n\n if (!trimmed.startsWith(\"@syntax\")) {\n return null;\n }\n\n const rest = trimmed.slice(\"@syntax\".length).trim();\n const words = rest.split(/\\s+/).filter((w) => w.length > 0);\n const subcommand = words[0];\n\n switch (subcommand) {\n case \"juxtaposed\":\n case \"elided\": {\n if (words.length !== 1) {\n return fail(\"syntax_bad_flag\", { flag: subcommand }, span);\n }\n\n return ok({ kind: subcommand });\n }\n\n case \"brackets\": {\n const pairs = parsePairs(words.slice(1));\n\n if (pairs === null) {\n return fail(\"syntax_bad_brackets\", {}, span);\n }\n\n return ok({ kind: \"brackets\", pairs });\n }\n\n case \"assoc-none\": {\n const number = words[1];\n\n if (\n words.length !== 2 ||\n number === undefined ||\n !/^\\d+$/.test(number)\n ) {\n return fail(\"syntax_bad_assoc_none\", {}, span);\n }\n\n return ok({ kind: \"assoc-none\", prec: Number.parseInt(number, 10) });\n }\n\n case \"lint\": {\n const name = words[1];\n\n if (\n words.length !== 2 ||\n name === undefined ||\n !(LINT_NAMES as readonly string[]).includes(name)\n ) {\n return fail(\n \"syntax_unknown_lint\",\n { name: name ?? \"\", known: LINT_NAMES.join(\", \") },\n span,\n );\n }\n\n return ok({ kind: \"lint\", name: name as LintName });\n }\n\n case \"display\": {\n if (words[1] === \"drop-outer-parens\" && words.length === 2) {\n return ok({ kind: \"display-drop-outer-parens\" });\n }\n\n if (words[1] === \"rotate-brackets\") {\n const pairs = parsePairs(words.slice(2));\n\n if (pairs !== null) {\n return ok({ kind: \"display-rotate-brackets\", pairs });\n }\n }\n\n return fail(\"syntax_bad_display\", {}, span);\n }\n\n case \"elab\": {\n const match = ELAB.exec(rest.slice(\"elab\".length).trim());\n\n if (match === null) {\n return fail(\"syntax_bad_elab\", {}, span);\n }\n\n const pattern = parsePattern(match[1] ?? \"\");\n\n if (typeof pattern === \"string\") {\n return fail(\"syntax_bad_pattern_element\", { element: pattern }, span);\n }\n\n const template = parseTemplate(match[2] ?? \"\");\n\n if (typeof template === \"string\") {\n return fail(\n \"syntax_bad_template_element\",\n { element: template },\n span,\n );\n }\n\n return ok({\n kind: \"elab\",\n rule: {\n inputOnly: match[3] === \"input-only\",\n pattern,\n span,\n template,\n },\n });\n }\n\n case \"role\": {\n const role = words[1];\n\n if (words.length !== 2 || role === undefined) {\n return fail(\"syntax_bad_role\", {}, span);\n }\n\n return ok({ kind: \"role\", role });\n }\n\n default:\n return fail(\n \"syntax_unknown_subcommand\",\n { subcommand: subcommand ?? \"(none)\" },\n span,\n );\n }\n}\n"]}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The MM0 file-level lexer, per the upstream specification (mm0.md) as
3
+ * summarized in Aufbau's manual (appendix-grammars.md):
4
+ *
5
+ * lexeme ::= symbol | identifier | number | math-string
6
+ * symbol ::= '*' | '.' | ':' | ';' | '(' | ')' | '>' | '{' | '}'
7
+ * | '=' | '_'
8
+ * identifier ::= [a-zA-Z_][a-zA-Z0-9_]*
9
+ * number ::= 0 | [1-9][0-9]*
10
+ * math-string ::= '$' [^$]* '$'
11
+ *
12
+ * `--` starts a line comment; `--|` starts an annotation line, which this
13
+ * lexer surfaces as a token of its own so the statement parser can attach it
14
+ * to the statement that follows. This lexer reads *statements*; the contents
15
+ * of math strings are scanned later, by the layer that owns them.
16
+ */
17
+ import type { Span } from "../diagnostics.js";
18
+ export type TokenKind = "annotation" | "identifier" | "math" | "number" | "symbol";
19
+ export interface FileToken {
20
+ readonly kind: TokenKind;
21
+ readonly span: Span;
22
+ /**
23
+ * The token's content: the symbol or identifier text, the digits of a
24
+ * number, a math string's interior (without the dollar signs), or an
25
+ * annotation line's payload (without the leading `--|`).
26
+ */
27
+ readonly text: string;
28
+ }
29
+ export interface LexError {
30
+ readonly position: number;
31
+ readonly id: "unterminated_math" | "unexpected_character";
32
+ }
33
+ export interface LexResult {
34
+ readonly tokens: readonly FileToken[];
35
+ readonly errors: readonly LexError[];
36
+ }
37
+ export declare function lexFile(source: string): LexResult;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The MM0 file-level lexer, per the upstream specification (mm0.md) as
3
+ * summarized in Aufbau's manual (appendix-grammars.md):
4
+ *
5
+ * lexeme ::= symbol | identifier | number | math-string
6
+ * symbol ::= '*' | '.' | ':' | ';' | '(' | ')' | '>' | '{' | '}'
7
+ * | '=' | '_'
8
+ * identifier ::= [a-zA-Z_][a-zA-Z0-9_]*
9
+ * number ::= 0 | [1-9][0-9]*
10
+ * math-string ::= '$' [^$]* '$'
11
+ *
12
+ * `--` starts a line comment; `--|` starts an annotation line, which this
13
+ * lexer surfaces as a token of its own so the statement parser can attach it
14
+ * to the statement that follows. This lexer reads *statements*; the contents
15
+ * of math strings are scanned later, by the layer that owns them.
16
+ */
17
+ const SYMBOLS = new Set([
18
+ "*",
19
+ ".",
20
+ ":",
21
+ ";",
22
+ "(",
23
+ ")",
24
+ ">",
25
+ "{",
26
+ "}",
27
+ "=",
28
+ "_",
29
+ ]);
30
+ function isIdentStart(ch) {
31
+ return /[A-Za-z_]/.test(ch);
32
+ }
33
+ function isIdentPart(ch) {
34
+ return /[A-Za-z0-9_]/.test(ch);
35
+ }
36
+ export function lexFile(source) {
37
+ const tokens = [];
38
+ const errors = [];
39
+ let i = 0;
40
+ while (i < source.length) {
41
+ const ch = source[i];
42
+ if (ch === undefined) {
43
+ break;
44
+ }
45
+ if (/\s/.test(ch)) {
46
+ i += 1;
47
+ continue;
48
+ }
49
+ if (ch === "-" && source[i + 1] === "-") {
50
+ const lineEnd = source.indexOf("\n", i);
51
+ const end = lineEnd === -1 ? source.length : lineEnd;
52
+ if (source[i + 2] === "|") {
53
+ tokens.push({
54
+ kind: "annotation",
55
+ span: { start: i, end },
56
+ text: source.slice(i + 3, end).trim(),
57
+ });
58
+ }
59
+ i = end;
60
+ continue;
61
+ }
62
+ if (ch === "$") {
63
+ const close = source.indexOf("$", i + 1);
64
+ if (close === -1) {
65
+ errors.push({ position: i, id: "unterminated_math" });
66
+ i = source.length;
67
+ continue;
68
+ }
69
+ tokens.push({
70
+ kind: "math",
71
+ span: { start: i, end: close + 1 },
72
+ text: source.slice(i + 1, close),
73
+ });
74
+ i = close + 1;
75
+ continue;
76
+ }
77
+ if (isIdentStart(ch)) {
78
+ let end = i + 1;
79
+ while (end < source.length) {
80
+ const next = source[end];
81
+ if (next === undefined || !isIdentPart(next)) {
82
+ break;
83
+ }
84
+ end += 1;
85
+ }
86
+ // A lone `_` is the symbol, not an identifier.
87
+ const text = source.slice(i, end);
88
+ tokens.push({
89
+ kind: text === "_" ? "symbol" : "identifier",
90
+ span: { start: i, end },
91
+ text,
92
+ });
93
+ i = end;
94
+ continue;
95
+ }
96
+ if (/[0-9]/.test(ch)) {
97
+ let end = i + 1;
98
+ while (end < source.length && /[0-9]/.test(source[end] ?? "")) {
99
+ end += 1;
100
+ }
101
+ tokens.push({
102
+ kind: "number",
103
+ span: { start: i, end },
104
+ text: source.slice(i, end),
105
+ });
106
+ i = end;
107
+ continue;
108
+ }
109
+ if (SYMBOLS.has(ch)) {
110
+ tokens.push({
111
+ kind: "symbol",
112
+ span: { start: i, end: i + 1 },
113
+ text: ch,
114
+ });
115
+ i += 1;
116
+ continue;
117
+ }
118
+ errors.push({ position: i, id: "unexpected_character" });
119
+ i += 1;
120
+ }
121
+ return { tokens, errors };
122
+ }
123
+ //# sourceMappingURL=lex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lex.js","sourceRoot":"","sources":["../../src/reader/lex.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAgCH,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC;IACtB,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;IACH,GAAG;CACJ,CAAC,CAAC;AAEH,SAAS,YAAY,CAAC,EAAU;IAC9B,OAAO,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,WAAW,CAAC,EAAU;IAC7B,OAAO,cAAc,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,MAAc;IACpC,MAAM,MAAM,GAAgB,EAAE,CAAC;IAC/B,MAAM,MAAM,GAAe,EAAE,CAAC;IAC9B,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;QACzB,MAAM,EAAE,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QAErB,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;YACrB,MAAM;QACR,CAAC;QAED,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC;YAClB,CAAC,IAAI,CAAC,CAAC;YACP,SAAS;QACX,CAAC;QAED,IA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B,CAAC,CAAC;YACH,CAAC,GAAG,GAAG,CAAC;YACR,SAAS;QACX,CAAC;QAED,IAAI,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC;YACpB,MAAM,CAAC,IAAI,CAAC;gBACV,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE;gBAC9B,IAAI,EAAE,EAAE;aACT,CAAC,CAAC;YACH,CAAC,IAAI,CAAC,CAAC;YACP,SAAS;QACX,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,EAAE,sBAAsB,EAAE,CAAC,CAAC;QACzD,CAAC,IAAI,CAAC,CAAC;IACT,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["/**\n * The MM0 file-level lexer, per the upstream specification (mm0.md) as\n * summarized in Aufbau's manual (appendix-grammars.md):\n *\n * lexeme ::= symbol | identifier | number | math-string\n * symbol ::= '*' | '.' | ':' | ';' | '(' | ')' | '>' | '{' | '}'\n * | '=' | '_'\n * identifier ::= [a-zA-Z_][a-zA-Z0-9_]*\n * number ::= 0 | [1-9][0-9]*\n * math-string ::= '$' [^$]* '$'\n *\n * `--` starts a line comment; `--|` starts an annotation line, which this\n * lexer surfaces as a token of its own so the statement parser can attach it\n * to the statement that follows. This lexer reads *statements*; the contents\n * of math strings are scanned later, by the layer that owns them.\n */\n\nimport type { Span } from \"../diagnostics.js\";\n\nexport type TokenKind =\n | \"annotation\"\n | \"identifier\"\n | \"math\"\n | \"number\"\n | \"symbol\";\n\nexport interface FileToken {\n readonly kind: TokenKind;\n readonly span: Span;\n /**\n * The token's content: the symbol or identifier text, the digits of a\n * number, a math string's interior (without the dollar signs), or an\n * annotation line's payload (without the leading `--|`).\n */\n readonly text: string;\n}\n\nexport interface LexError {\n readonly position: number;\n readonly id: \"unterminated_math\" | \"unexpected_character\";\n}\n\nexport interface LexResult {\n readonly tokens: readonly FileToken[];\n readonly errors: readonly LexError[];\n}\n\nconst SYMBOLS = new Set([\n \"*\",\n \".\",\n \":\",\n \";\",\n \"(\",\n \")\",\n \">\",\n \"{\",\n \"}\",\n \"=\",\n \"_\",\n]);\n\nfunction isIdentStart(ch: string): boolean {\n return /[A-Za-z_]/.test(ch);\n}\n\nfunction isIdentPart(ch: string): boolean {\n return /[A-Za-z0-9_]/.test(ch);\n}\n\nexport function lexFile(source: string): LexResult {\n const tokens: FileToken[] = [];\n const errors: LexError[] = [];\n let i = 0;\n\n while (i < source.length) {\n const ch = source[i];\n\n if (ch === undefined) {\n break;\n }\n\n if (/\\s/.test(ch)) {\n i += 1;\n continue;\n }\n\n if (ch === \"-\" && source[i + 1] === \"-\") {\n const lineEnd = source.indexOf(\"\\n\", i);\n const end = lineEnd === -1 ? source.length : lineEnd;\n\n if (source[i + 2] === \"|\") {\n tokens.push({\n kind: \"annotation\",\n span: { start: i, end },\n text: source.slice(i + 3, end).trim(),\n });\n }\n\n i = end;\n continue;\n }\n\n if (ch === \"$\") {\n const close = source.indexOf(\"$\", i + 1);\n\n if (close === -1) {\n errors.push({ position: i, id: \"unterminated_math\" });\n i = source.length;\n continue;\n }\n\n tokens.push({\n kind: \"math\",\n span: { start: i, end: close + 1 },\n text: source.slice(i + 1, close),\n });\n i = close + 1;\n continue;\n }\n\n if (isIdentStart(ch)) {\n let end = i + 1;\n\n while (end < source.length) {\n const next = source[end];\n if (next === undefined || !isIdentPart(next)) {\n break;\n }\n end += 1;\n }\n\n // A lone `_` is the symbol, not an identifier.\n const text = source.slice(i, end);\n tokens.push({\n kind: text === \"_\" ? \"symbol\" : \"identifier\",\n span: { start: i, end },\n text,\n });\n i = end;\n continue;\n }\n\n if (/[0-9]/.test(ch)) {\n let end = i + 1;\n\n while (end < source.length && /[0-9]/.test(source[end] ?? \"\")) {\n end += 1;\n }\n\n tokens.push({\n kind: \"number\",\n span: { start: i, end },\n text: source.slice(i, end),\n });\n i = end;\n continue;\n }\n\n if (SYMBOLS.has(ch)) {\n tokens.push({\n kind: \"symbol\",\n span: { start: i, end: i + 1 },\n text: ch,\n });\n i += 1;\n continue;\n }\n\n errors.push({ position: i, id: \"unexpected_character\" });\n i += 1;\n }\n\n return { tokens, errors };\n}\n"]}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * From parsed statements to a `Spec` — the library's central object: the
3
+ * signature, notations, coercions, and `@syntax` surface metadata of one
4
+ * logical system, validated.
5
+ *
6
+ * Validation here is about the spec being *coherent* (token conflicts,
7
+ * dangling names, non-invertible elab rules); whether the theory proves
8
+ * anything is the engine's business, and axiom bodies pass through opaque.
9
+ */
10
+ import { type Diagnostic, type Span } from "../diagnostics.js";
11
+ import { type ElabRule, type LintName } from "./annotations.js";
12
+ import { type Annotation, type Binder, type NotationLiteral, type Precedence, type Statement } from "./statements.js";
13
+ export interface SortInfo {
14
+ readonly foreignAnnotations: readonly Annotation[];
15
+ readonly modifiers: readonly string[];
16
+ readonly name: string;
17
+ readonly span: Span;
18
+ /**
19
+ * The sort's variable tokens, read from the engine's own `@vars`
20
+ * annotation (which stays in `foreignAnnotations` untouched — it is the
21
+ * engine's, we only listen in). These are the surface lexicon's
22
+ * identifiers of this sort; whether a quantifier can bind them falls
23
+ * out of the quantifiers' binder sorts, not from here.
24
+ */
25
+ readonly vars: readonly string[];
26
+ }
27
+ export interface TermInfo {
28
+ readonly binders: readonly Binder[];
29
+ /** `@syntax elided`: supplied when an argument of its sort is missing. */
30
+ readonly elided: boolean;
31
+ readonly foreignAnnotations: readonly Annotation[];
32
+ /** True when this came from a `def` rather than a `term`. */
33
+ readonly isDef: boolean;
34
+ /** `@syntax juxtaposed`: adjacency of its sort's leaves denotes it. */
35
+ readonly juxtaposed: boolean;
36
+ readonly name: string;
37
+ readonly returnSort: string;
38
+ readonly roles: readonly string[];
39
+ readonly span: Span;
40
+ }
41
+ export interface CoercionInfo {
42
+ readonly from: string;
43
+ readonly name: string;
44
+ readonly span: Span;
45
+ readonly to: string;
46
+ }
47
+ export type NotationInfo = {
48
+ readonly form: "general";
49
+ /** The notation statement's own binders, which its variables name. */
50
+ readonly binders: readonly Binder[];
51
+ readonly literals: readonly NotationLiteral[];
52
+ readonly span: Span;
53
+ readonly term: string;
54
+ } | {
55
+ readonly form: "simple";
56
+ readonly fixity: "infixl" | "infixr" | "prefix";
57
+ readonly prec: Precedence;
58
+ readonly span: Span;
59
+ readonly term: string;
60
+ readonly token: string;
61
+ };
62
+ export interface Spec {
63
+ readonly assocNone: ReadonlySet<number>;
64
+ readonly coercions: readonly CoercionInfo[];
65
+ readonly delimiters: {
66
+ readonly left: ReadonlySet<string>;
67
+ readonly right: ReadonlySet<string>;
68
+ };
69
+ readonly display: {
70
+ readonly dropOuterParens: boolean;
71
+ readonly rotateBrackets: readonly (readonly [string, string])[] | null;
72
+ };
73
+ /** Always starts with the built-in `("(", ")")` pair. */
74
+ readonly groupingPairs: readonly (readonly [string, string])[];
75
+ readonly lints: readonly LintName[];
76
+ /** In declaration order; the last notation for a term is canonical. */
77
+ readonly notations: readonly NotationInfo[];
78
+ readonly elabRules: readonly ElabRule[];
79
+ readonly sorts: ReadonlyMap<string, SortInfo>;
80
+ /** Every statement, in order, annotations intact — full fidelity. */
81
+ readonly statements: readonly Statement[];
82
+ readonly terms: ReadonlyMap<string, TermInfo>;
83
+ }
84
+ export interface SpecParse {
85
+ readonly diagnostics: readonly Diagnostic[];
86
+ readonly spec: Spec;
87
+ }
88
+ export declare function parseSpec(source: string): SpecParse;