@aufbau/syntax 0.0.1 → 0.0.2

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/CHANGELOG.md CHANGED
@@ -1,6 +1,48 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.0.2 — 2026-08-24
4
+
5
+ **Breaking: student input is segmented by declared delimiters, not by the
6
+ vocabulary.** 0.0.1 cut input up with character-level maximal munch over
7
+ the declared tokens and lexicon names, which made segmentation depend on
8
+ what the spec happened to contain — so declaring a term could silently
9
+ re-read a string that already parsed. Appending `term ab: tm;` to the
10
+ Magnus spec turned `Fab` from `F` of `a` and `b` into `F` of `ab`, and the
11
+ printer spelled the new tree back as `Fab`, so no round trip could see it.
12
+ Segmentation is now MM0's own tokenizer rule over a delimiter set the spec
13
+ declares, fixed before anything is looked up.
14
+
15
+ **What a 0.0.1 spec must add.** Tight textbook notation is now an explicit
16
+ opt-in: a spec that declares no `@syntax delimiter` is read under the
17
+ theory's own `delimiter` statement alone, where input is whitespace- and
18
+ bracket-separated, so `~~P` and `AxF(x)` stop parsing. Declare the letters
19
+ and the operator spellings the language glues — the three specs in
20
+ `specs/` show the shape, and `docs/authoring-a-spec.md` covers the choice
21
+ this forces (a spec with letter delimiters has one-character letters; a
22
+ spec without them has multi-character names and spaced adjacency; no spec
23
+ has both).
24
+
25
+ - `@syntax delimiter` (`docs/syntax-annotations.md`) declares the surface
26
+ set, in both of MM0's forms, unioned with the file's own `delimiter`
27
+ statement, and generalized so that an entry may be any string — `∧`,
28
+ `<->` — where the engine's `[256]bool` table holds only single bytes.
29
+ - Three authoring-time checks: `delimiter_unknown` and
30
+ `delimiter_unreachable_name` are errors, `delimiter_token_not_delimited`
31
+ is advice. `Diagnostic` therefore gained a `severity`, and a caller that
32
+ treated every diagnostic as fatal should now filter on it.
33
+ - A chunk nothing can be classified as is reported whole — the new
34
+ `unrecognized_chunk` diagnostic — rather than by its first character.
35
+ - The property the rewrite exists to buy is under test
36
+ (`tests/monotonicity.test.ts`): vocabulary growth either leaves every
37
+ existing reading identical or is refused at the declaration, never both
38
+ parses and means something else. One consequence worth knowing: a spec
39
+ that declares all 52 letters and spends all 52 as lexicon names — as all
40
+ three examples do — is closed to any further name containing a letter.
41
+
42
+ Also: a Nix development shell (`nix develop`, or `direnv allow`), carrying
43
+ the toolchain CI runs with.
44
+
45
+ ## 0.0.1 — 2026-08-24
4
46
 
5
47
  Initial development. The layer stack is complete and tested end to end:
6
48
 
@@ -30,18 +72,18 @@ Initial development. The layer stack is complete and tested end to end:
30
72
  publishes from `main`, stable publishes from a `v1.2.3` tag, both with npm
31
73
  provenance. See `docs/releasing.md`.
32
74
 
33
- Replaced before any release: the original `@syntax family` letter-schema
34
- mechanism (letter ranges, subscript lexing, template elaboration,
35
- combiner discovery by shape). The lexicon is now ordinary MM0 — declared
36
- terms plus the engine's `@vars` pools — with two per-term annotations,
37
- `elided` and `juxtaposed`, carrying what the declarations cannot say.
38
- Deliberate casualties: subscripted atoms (`x_1`, `P0`; the vocabulary is
39
- finite) and one-letter-two-kinds (bare `P` is now the seq-taking
40
- declaration applied to the elided empty sequence, so trees read
75
+ Replaced before this first release: the original `@syntax family`
76
+ letter-schema mechanism (letter ranges, subscript lexing, template
77
+ elaboration, combiner discovery by shape). The lexicon is now ordinary
78
+ MM0 — declared terms plus the engine's `@vars` pools — with two per-term
79
+ annotations, `elided` and `juxtaposed`, carrying what the declarations
80
+ cannot say. Deliberate casualties: subscripted atoms (`x_1`, `P0`; the
81
+ vocabulary is finite) and one-letter-two-kinds (bare `P` is now the
82
+ seq-taking declaration applied to the elided empty sequence, so trees read
41
83
  `P(snil)`).
42
84
 
43
- Also renamed before any release: `@syntax rewrite` is now `@syntax elab`.
44
- The engine's `@rewrite` marks directed rules over *terms* for proof-search
45
- normalization, and theories carrying both annotations read badly; this
46
- layer only ever rewrites tokens, elaborating surface spelling on the way
47
- in and delaborating on the way out.
85
+ Also renamed before this first release: `@syntax rewrite` is now `@syntax
86
+ elab`. The engine's `@rewrite` marks directed rules over *terms* for
87
+ proof-search normalization, and theories carrying both annotations read
88
+ badly; this layer only ever rewrites tokens, elaborating surface spelling
89
+ on the way in and delaborating on the way out.
package/README.md CHANGED
@@ -11,9 +11,9 @@ plus a small set of `@syntax` annotations in
11
11
  derives from it the two things MM0's own math parser cannot give a logic
12
12
  classroom:
13
13
 
14
- - a **student surface language**: character-level, whitespace-free textbook
15
- notation (`∀xF(x)`, `Fxyz`, `~~P`), alias spellings, per-textbook bracket
16
- and parenthesization conventions;
14
+ - a **student surface language**: tight, whitespace-free textbook notation
15
+ (`∀xF(x)`, `Fxyz`, `~~P`), alias spellings, per-textbook bracket and
16
+ parenthesization conventions;
17
17
  - a **display language**: canonical pretty-printing with the textbook's own
18
18
  conventions (dropped outer parentheses, juxtaposed arguments, rotated
19
19
  brackets).
@@ -31,8 +31,14 @@ One spec file per textbook system; no code per system.
31
31
  `@congr`, …) pass through as data — except `@vars`, which is read *and*
32
32
  passed through: the engine's variable pools are the surface lexicon's
33
33
  variables.
34
- 2. **Scanner** — character-level maximal munch over the declared tokens and
35
- lexicon names. No whitespace requirement; glue dissolves here.
34
+ 2. **Scanner** — segment, then classify. Chunk boundaries come from the
35
+ declared delimiter set alone (MM0's own tokenizer rule, generalized so
36
+ that a delimiter may be any string — `∧`, `<->` — where the engine's
37
+ byte table holds only single bytes), and *never* from the term or
38
+ notation tables; only afterwards is a chunk looked up, as a token, as a
39
+ lexicon name, or as both. Declaring the letters is what dissolves glue,
40
+ and declaring it is what keeps a later declaration from silently
41
+ re-reading input that already parsed.
36
42
  3. **Elaboration layer** — bidirectional token-pattern rules (`@syntax
37
43
  elab`) for textbook sugar that really is local (`(x)Fx` ⇄ `∀xF(x)`,
38
44
  `(∀x)` ⇄ `∀x`). Regular by design: one pass per rule, spans threaded
@@ -49,12 +55,15 @@ One spec file per textbook system; no code per system.
49
55
 
50
56
  ## Status
51
57
 
52
- Pre-release, but the layer stack is complete and tested end to end: three
58
+ Early, but the layer stack is complete and tested end to end: three
53
59
  example specs (`forallx-calgary-2019`, `forallx-magnus`, `carnap-prop`),
54
60
  a behavioral corpus transcribed from the parsers this library replaces,
55
- round-trip laws for both print modes, and an acceptance test in which the
56
- real Aufbau compiler parses this library's engine output and certifies it
57
- tree-identical to hand-written spellings (`tests/engine-align.test.ts`).
61
+ round-trip laws for both print modes, an acceptance test in which the real
62
+ Aufbau compiler parses this library's engine output and certifies it
63
+ tree-identical to hand-written spellings (`tests/engine-align.test.ts`),
64
+ and a monotonicity suite pinning the property the delimiter design exists
65
+ to buy: declaring vocabulary cannot change how existing input is cut up
66
+ (`tests/monotonicity.test.ts`).
58
67
 
59
68
  ```ts
60
69
  import { parseSpec, printTerm, SurfaceLanguage } from "@aufbau/syntax";
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Segmentation: where one chunk of input ends and the next begins.
3
+ *
4
+ * This is MM0's own tokenizer rule (`MathCursor.readToken` in Aufbau's
5
+ * `src/trusted/parse.zig`) — skip whitespace; consume; break after a *left*
6
+ * delimiter, and before whitespace or a *right* delimiter — generalized in
7
+ * exactly one way: a delimiter is a string rather than a single byte, so
8
+ * `∧`, `->` and `<->` can self-delimit where the engine's `[256]bool` table
9
+ * cannot hold them.
10
+ *
11
+ * The point of keeping it here, apart from the vocabulary: **segmentation
12
+ * never consults the term or notation tables.** A chunk's boundaries come
13
+ * from the delimiter set alone; only afterwards is the chunk classified.
14
+ * That is what MM0 buys by separating `delimiter` from `notation`, and it
15
+ * is what makes declaring a new term unable to silently re-read an existing
16
+ * string.
17
+ *
18
+ * The set is a *parameter*, never a global: engine text is read under the
19
+ * theory's own `delimiter` statement, student input under the wider surface
20
+ * set (see `Spec.surfaceDelimiters`).
21
+ */
22
+ /** Delimiters as declared: a left list and a right list, as in MM0. */
23
+ export interface DelimiterSet {
24
+ readonly left: ReadonlySet<string>;
25
+ readonly right: ReadonlySet<string>;
26
+ }
27
+ /** A delimiter set prepared for matching: longest spelling wins. */
28
+ export interface DelimiterRules {
29
+ /** Every delimiter, longest first — the units a chunk is built from. */
30
+ readonly all: readonly string[];
31
+ readonly left: ReadonlySet<string>;
32
+ /** Right delimiters, longest first: a chunk breaks *before* one. */
33
+ readonly right: readonly string[];
34
+ }
35
+ export declare function delimiterRules(set: DelimiterSet): DelimiterRules;
36
+ /**
37
+ * The chunk starting at `start`, which must be a chunk boundary (the start
38
+ * of the text, or the end of the previous chunk). Leading whitespace is not
39
+ * skipped — `segment` does that.
40
+ */
41
+ export declare function chunkAt(text: string, start: number, rules: DelimiterRules): string;
42
+ /** Every chunk of `text`, in order, with whitespace dropped. */
43
+ export declare function segment(text: string, rules: DelimiterRules): string[];
44
+ /**
45
+ * Whether `name` can ever be read as a single chunk — i.e. whether a student
46
+ * writing it, with space around it, gets it whole. A name that splits is
47
+ * unreachable: no amount of bracketing recovers it, because segmentation
48
+ * happens before anything knows the name exists.
49
+ */
50
+ export declare function isReachableChunk(name: string, rules: DelimiterRules): boolean;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Segmentation: where one chunk of input ends and the next begins.
3
+ *
4
+ * This is MM0's own tokenizer rule (`MathCursor.readToken` in Aufbau's
5
+ * `src/trusted/parse.zig`) — skip whitespace; consume; break after a *left*
6
+ * delimiter, and before whitespace or a *right* delimiter — generalized in
7
+ * exactly one way: a delimiter is a string rather than a single byte, so
8
+ * `∧`, `->` and `<->` can self-delimit where the engine's `[256]bool` table
9
+ * cannot hold them.
10
+ *
11
+ * The point of keeping it here, apart from the vocabulary: **segmentation
12
+ * never consults the term or notation tables.** A chunk's boundaries come
13
+ * from the delimiter set alone; only afterwards is the chunk classified.
14
+ * That is what MM0 buys by separating `delimiter` from `notation`, and it
15
+ * is what makes declaring a new term unable to silently re-read an existing
16
+ * string.
17
+ *
18
+ * The set is a *parameter*, never a global: engine text is read under the
19
+ * theory's own `delimiter` statement, student input under the wider surface
20
+ * set (see `Spec.surfaceDelimiters`).
21
+ */
22
+ export function delimiterRules(set) {
23
+ const longestFirst = (entries) => [...new Set(entries)].sort((a, b) => b.length - a.length);
24
+ return {
25
+ all: longestFirst([...set.left, ...set.right]),
26
+ left: new Set(set.left),
27
+ right: longestFirst(set.right),
28
+ };
29
+ }
30
+ function matchAt(candidates, text, at) {
31
+ for (const candidate of candidates) {
32
+ if (candidate.length > 0 && text.startsWith(candidate, at)) {
33
+ return candidate;
34
+ }
35
+ }
36
+ return null;
37
+ }
38
+ /** One whole code point, so an astral character is never split in half. */
39
+ function codePointAt(text, at) {
40
+ const code = text.codePointAt(at);
41
+ return code === undefined ? (text[at] ?? "") : String.fromCodePoint(code);
42
+ }
43
+ /**
44
+ * The chunk starting at `start`, which must be a chunk boundary (the start
45
+ * of the text, or the end of the previous chunk). Leading whitespace is not
46
+ * skipped — `segment` does that.
47
+ */
48
+ export function chunkAt(text, start, rules) {
49
+ let position = start;
50
+ while (position < text.length) {
51
+ // Always consume something: a delimiter that starts here, else one
52
+ // character. MM0 consumes before it tests, which is what lets a
53
+ // delimiter both open a chunk and close it.
54
+ const unit = matchAt(rules.all, text, position) ?? codePointAt(text, position);
55
+ position += unit.length;
56
+ if (rules.left.has(unit)) {
57
+ break;
58
+ }
59
+ if (position >= text.length || /\s/.test(text[position] ?? "")) {
60
+ break;
61
+ }
62
+ if (matchAt(rules.right, text, position) !== null) {
63
+ break;
64
+ }
65
+ }
66
+ return text.slice(start, position);
67
+ }
68
+ /** Every chunk of `text`, in order, with whitespace dropped. */
69
+ export function segment(text, rules) {
70
+ const chunks = [];
71
+ let position = 0;
72
+ while (position < text.length) {
73
+ if (/\s/.test(text[position] ?? "")) {
74
+ position += 1;
75
+ continue;
76
+ }
77
+ const chunk = chunkAt(text, position, rules);
78
+ // A zero-length chunk would spin; the rule cannot produce one, but the
79
+ // loop should not depend on that.
80
+ if (chunk.length === 0) {
81
+ break;
82
+ }
83
+ chunks.push(chunk);
84
+ position += chunk.length;
85
+ }
86
+ return chunks;
87
+ }
88
+ /**
89
+ * Whether `name` can ever be read as a single chunk — i.e. whether a student
90
+ * writing it, with space around it, gets it whole. A name that splits is
91
+ * unreachable: no amount of bracketing recovers it, because segmentation
92
+ * happens before anything knows the name exists.
93
+ */
94
+ export function isReachableChunk(name, rules) {
95
+ return name.length > 0 && chunkAt(name, 0, rules) === name;
96
+ }
97
+ //# sourceMappingURL=delimiters.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delimiters.js","sourceRoot":"","sources":["../src/delimiters.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAiBH,MAAM,UAAU,cAAc,CAAC,GAAiB;IAC9C,MAAM,YAAY,GAAG,CAAC,OAAyB,EAAY,EAAE,CAC3D,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;IAE5D,OAAO;QACL,GAAG,EAAE,YAAY,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;QAC9C,IAAI,EAAE,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC;QACvB,KAAK,EAAE,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC;KAC/B,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CACd,UAA6B,EAC7B,IAAY,EACZ,EAAU;IAEV,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC,EAAE,CAAC;YAC3D,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,2EAA2E;AAC3E,SAAS,WAAW,CAAC,IAAY,EAAE,EAAU;IAC3C,MAAM,IAAI,GAAG,IAA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,EAAE,CAAC;QAC9B,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YACpC,QAAQ,IAAI,CAAC,CAAC;YACd,SAAS;QACX,CAAC;QAED,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;QAE7C,uEAAuE;QACvE,kCAAkC;QAClC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,MAAM;QACR,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnB,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC;IAC3B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAC9B,IAAY,EACZ,KAAqB;IAErB,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,CAAC,KAAK,IAAI,CAAC;AAC7D,CAAC","sourcesContent":["/**\n * Segmentation: where one chunk of input ends and the next begins.\n *\n * This is MM0's own tokenizer rule (`MathCursor.readToken` in Aufbau's\n * `src/trusted/parse.zig`) — skip whitespace; consume; break after a *left*\n * delimiter, and before whitespace or a *right* delimiter — generalized in\n * exactly one way: a delimiter is a string rather than a single byte, so\n * `∧`, `->` and `<->` can self-delimit where the engine's `[256]bool` table\n * cannot hold them.\n *\n * The point of keeping it here, apart from the vocabulary: **segmentation\n * never consults the term or notation tables.** A chunk's boundaries come\n * from the delimiter set alone; only afterwards is the chunk classified.\n * That is what MM0 buys by separating `delimiter` from `notation`, and it\n * is what makes declaring a new term unable to silently re-read an existing\n * string.\n *\n * The set is a *parameter*, never a global: engine text is read under the\n * theory's own `delimiter` statement, student input under the wider surface\n * set (see `Spec.surfaceDelimiters`).\n */\n\n/** Delimiters as declared: a left list and a right list, as in MM0. */\nexport interface DelimiterSet {\n readonly left: ReadonlySet<string>;\n readonly right: ReadonlySet<string>;\n}\n\n/** A delimiter set prepared for matching: longest spelling wins. */\nexport interface DelimiterRules {\n /** Every delimiter, longest first — the units a chunk is built from. */\n readonly all: readonly string[];\n readonly left: ReadonlySet<string>;\n /** Right delimiters, longest first: a chunk breaks *before* one. */\n readonly right: readonly string[];\n}\n\nexport function delimiterRules(set: DelimiterSet): DelimiterRules {\n const longestFirst = (entries: Iterable<string>): string[] =>\n [...new Set(entries)].sort((a, b) => b.length - a.length);\n\n return {\n all: longestFirst([...set.left, ...set.right]),\n left: new Set(set.left),\n right: longestFirst(set.right),\n };\n}\n\nfunction matchAt(\n candidates: readonly string[],\n text: string,\n at: number,\n): string | null {\n for (const candidate of candidates) {\n if (candidate.length > 0 && text.startsWith(candidate, at)) {\n return candidate;\n }\n }\n\n return null;\n}\n\n/** One whole code point, so an astral character is never split in half. */\nfunction codePointAt(text: string, at: number): string {\n const code = text.codePointAt(at);\n return code === undefined ? (text[at] ?? \"\") : String.fromCodePoint(code);\n}\n\n/**\n * The chunk starting at `start`, which must be a chunk boundary (the start\n * of the text, or the end of the previous chunk). Leading whitespace is not\n * skipped — `segment` does that.\n */\nexport function chunkAt(\n text: string,\n start: number,\n rules: DelimiterRules,\n): string {\n let position = start;\n\n while (position < text.length) {\n // Always consume something: a delimiter that starts here, else one\n // character. MM0 consumes before it tests, which is what lets a\n // delimiter both open a chunk and close it.\n const unit =\n matchAt(rules.all, text, position) ?? codePointAt(text, position);\n position += unit.length;\n\n if (rules.left.has(unit)) {\n break;\n }\n\n if (position >= text.length || /\\s/.test(text[position] ?? \"\")) {\n break;\n }\n\n if (matchAt(rules.right, text, position) !== null) {\n break;\n }\n }\n\n return text.slice(start, position);\n}\n\n/** Every chunk of `text`, in order, with whitespace dropped. */\nexport function segment(text: string, rules: DelimiterRules): string[] {\n const chunks: string[] = [];\n let position = 0;\n\n while (position < text.length) {\n if (/\\s/.test(text[position] ?? \"\")) {\n position += 1;\n continue;\n }\n\n const chunk = chunkAt(text, position, rules);\n\n // A zero-length chunk would spin; the rule cannot produce one, but the\n // loop should not depend on that.\n if (chunk.length === 0) {\n break;\n }\n\n chunks.push(chunk);\n position += chunk.length;\n }\n\n return chunks;\n}\n\n/**\n * Whether `name` can ever be read as a single chunk — i.e. whether a student\n * writing it, with space around it, gets it whole. A name that splits is\n * unreachable: no amount of bracketing recovers it, because segmentation\n * happens before anything knows the name exists.\n */\nexport function isReachableChunk(\n name: string,\n rules: DelimiterRules,\n): boolean {\n return name.length > 0 && chunkAt(name, 0, rules) === name;\n}\n"]}
@@ -11,10 +11,18 @@ export interface Span {
11
11
  readonly start: number;
12
12
  readonly end: number;
13
13
  }
14
+ /**
15
+ * `error` means the thing being described does not work. `warning` means it
16
+ * works but is very likely not what was meant — a spec that only warns is
17
+ * still usable, and a consumer that ignores the distinction still sees a
18
+ * message.
19
+ */
20
+ export type Severity = "error" | "warning";
14
21
  export interface Diagnostic {
15
22
  readonly id: string;
16
23
  readonly message: string;
17
24
  readonly params: Readonly<Record<string, string>>;
25
+ readonly severity: Severity;
18
26
  readonly span: Span;
19
27
  }
20
28
  /**
@@ -23,4 +31,4 @@ export interface Diagnostic {
23
31
  * rather than silently blank.
24
32
  */
25
33
  export declare function fillTemplate(template: string, params: Readonly<Record<string, string>>): string;
26
- export declare function diagnostic(id: string, template: string, params: Readonly<Record<string, string>>, span: Span): Diagnostic;
34
+ export declare function diagnostic(id: string, template: string, params: Readonly<Record<string, string>>, span: Span, severity?: Severity): Diagnostic;
@@ -17,7 +17,13 @@ export function fillTemplate(template, params) {
17
17
  return value === undefined ? hole : value;
18
18
  });
19
19
  }
20
- export function diagnostic(id, template, params, span) {
21
- return { id, message: fillTemplate(template, params), params, span };
20
+ export function diagnostic(id, template, params, span, severity = "error") {
21
+ return {
22
+ id,
23
+ message: fillTemplate(template, params),
24
+ params,
25
+ severity,
26
+ span,
27
+ };
22
28
  }
23
29
  //# sourceMappingURL=diagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../src/diagnostics.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAeH;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAC1B,QAAgB,EAChB,MAAwC;IAExC,OAAO,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAY,EAAE,EAAE;QAC3D,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QAC3B,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IAC5C,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,UAAU,CACxB,EAAU,EACV,QAAgB,EAChB,MAAwC,EACxC,IAAU;IAEV,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;AACvE,CAAC","sourcesContent":["/**\n * Diagnostics carried by every layer of the library.\n *\n * Each diagnostic is structured — a stable id, its parameters, and a source\n * span — so a consumer can reword or translate it. `message` is the id's\n * English template with the parameters filled in, so a consumer that does\n * neither still has something to show.\n */\n\n/** Half-open range of UTF-16 code-unit offsets into the source text. */\nexport interface Span {\n readonly start: number;\n readonly end: number;\n}\n\nexport interface Diagnostic {\n readonly id: string;\n readonly message: string;\n readonly params: Readonly<Record<string, string>>;\n readonly span: Span;\n}\n\n/**\n * Fill `{name}` holes in a template. A hole with no matching parameter is\n * left as written, which makes a mismatched template visible in output\n * rather than silently blank.\n */\nexport function fillTemplate(\n template: string,\n params: Readonly<Record<string, string>>,\n): string {\n return template.replace(/\\{(\\w+)\\}/g, (hole, name: string) => {\n const value = params[name];\n return value === undefined ? hole : value;\n });\n}\n\nexport function diagnostic(\n id: string,\n template: string,\n params: Readonly<Record<string, string>>,\n span: Span,\n): Diagnostic {\n return { id, message: fillTemplate(template, params), params, span };\n}\n"]}
1
+ {"version":3,"file":"diagnostics.js","sourceRoot":"","sources":["../src/diagnostics.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAwBH;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAC1B,QAAgB,EAChB,MAAwC;IAExC,OAAO,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAY,EAAE,EAAE;QAC3D,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QAC3B,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IAC5C,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,UAAU,CACxB,EAAU,EACV,QAAgB,EAChB,MAAwC,EACxC,IAAU,EACV,WAAqB,OAAO;IAE5B,OAAO;QACL,EAAE;QACF,OAAO,EAAE,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC;QACvC,MAAM;QACN,QAAQ;QACR,IAAI;KACL,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Diagnostics carried by every layer of the library.\n *\n * Each diagnostic is structured — a stable id, its parameters, and a source\n * span — so a consumer can reword or translate it. `message` is the id's\n * English template with the parameters filled in, so a consumer that does\n * neither still has something to show.\n */\n\n/** Half-open range of UTF-16 code-unit offsets into the source text. */\nexport interface Span {\n readonly start: number;\n readonly end: number;\n}\n\n/**\n * `error` means the thing being described does not work. `warning` means it\n * works but is very likely not what was meant — a spec that only warns is\n * still usable, and a consumer that ignores the distinction still sees a\n * message.\n */\nexport type Severity = \"error\" | \"warning\";\n\nexport interface Diagnostic {\n readonly id: string;\n readonly message: string;\n readonly params: Readonly<Record<string, string>>;\n readonly severity: Severity;\n readonly span: Span;\n}\n\n/**\n * Fill `{name}` holes in a template. A hole with no matching parameter is\n * left as written, which makes a mismatched template visible in output\n * rather than silently blank.\n */\nexport function fillTemplate(\n template: string,\n params: Readonly<Record<string, string>>,\n): string {\n return template.replace(/\\{(\\w+)\\}/g, (hole, name: string) => {\n const value = params[name];\n return value === undefined ? hole : value;\n });\n}\n\nexport function diagnostic(\n id: string,\n template: string,\n params: Readonly<Record<string, string>>,\n span: Span,\n severity: Severity = \"error\",\n): Diagnostic {\n return {\n id,\n message: fillTemplate(template, params),\n params,\n severity,\n span,\n };\n}\n"]}
package/dist/elab.js CHANGED
@@ -147,9 +147,10 @@ function applyRule(lang, text, origin, pattern, template, separator) {
147
147
  position = match.end;
148
148
  continue;
149
149
  }
150
- // Advance one whole token (the longest reading), staying on
151
- // boundaries; an unrecognized character passes through untouched.
152
- const step = Math.max(1, ...point.readings.map((r) => r.length));
150
+ // Advance one whole chunk, so the pass only ever resumes on a
151
+ // segmentation boundary; a chunk the vocabulary does not recognize
152
+ // passes through untouched.
153
+ const step = Math.max(1, point.chunk.length);
153
154
  copy(point.start, point.start + step);
154
155
  position = point.start + step;
155
156
  }
package/dist/elab.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"elab.js","sourceRoot":"","sources":["../src/elab.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAoCH,SAAS,eAAe,CACtB,IAAqB,EACrB,OAAmC,EACnC,IAAY;IAEZ,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,KAAK,KAAK,EAAE,CAAC;QAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;QAE9B,OAAO,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,IAAI,CAAC;IAC3D,CAAC;IAED,uEAAuE;IACvE,sCAAsC;IACtC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAEnD,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,M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AU,CAAC,IAAqB,EAAE,IAAY;IAC5D,IAAI,OAAO,GAAG,IAAI,CAAC;IAEnB,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC;QACtD,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,SAAS;QACX,CAAC;QAED,MAAM,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC;QAErC,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;YACrB,SAAS;QACX,CAAC;QAED,OAAO,GAAG,SAAS,CACjB,IAAI,EACJ,OAAO,EACP,CAAC,GAAG,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EACrC,OAAO,EACP,aAAa,CAAC,IAAI,CAAC,EACnB,EAAE,CACH,CAAC,IAAI,CAAC;IACT,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,SAAS,CACvB,MAAyB,EACzB,IAAsD;IAEtD,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC;IAC7C,MAAM,GAAG,GACP,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAErE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;AACxB,CAAC","sourcesContent":["/**\n * The bidirectional token-elaboration layer — `@syntax elab` rules.\n *\n * Forward (elaboration, before the parser): each rule makes one\n * left-to-right pass over the text, matching at token boundaries only.\n * Where a rule matches, its template is spliced in — literals in their own\n * spelling, captures copied from the source — separated by spaces so the\n * result re-scans cleanly. No fixpoints: matching resumes *after* each\n * replacement, and rules run in declaration order, so the layer terminates\n * by construction. An origin map carries every emitted offset back to\n * the source, so diagnostics and term spans point at what the writer\n * actually typed.\n *\n * Backward (delaboration, after the display printer): the same rules run\n * inverted — template as pattern, pattern as replacement — in reverse\n * declaration order, joined tight, skipping `input-only` rules. A linear\n * rule is a lens: the Quine rule `( ?x:var ) => ∀ ?x` read backward *is*\n * the display convention that writes `∀x` as `(x)`.\n *\n * Captures match single lexicon names — a `@vars` token or a nullary\n * declared term — whose sort coerces into the capture's named sort. The\n * layer is deliberately regular — nesting facts belong to the parser.\n */\n\nimport type { SurfaceLanguage } from \"./parse.js\";\nimport type {\n ElabRule,\n RuleCapture,\n RuleLiteral,\n RuleTemplateElement,\n} from \"./reader/annotations.js\";\nimport type { Reading } from \"./scan.js\";\n\n/**\n * The matcher's pattern element: the reader's, plus an optional separator\n * on a capture — inverted `?ts,*` references match separator-interleaved\n * repeats (`x , y`), which the forward syntax has no way to write.\n */\ntype MatchElement =\n | RuleLiteral\n | (RuleCapture & { readonly separator?: string | null });\n\nexport interface Elaborated {\n /** For each offset of `text`, the source offset it came from. */\n readonly origin: readonly number[];\n readonly text: string;\n}\n\ninterface Captured {\n readonly start: number;\n readonly text: string;\n}\n\ninterface RuleMatch {\n readonly captures: ReadonlyMap<string, readonly Captured[]>;\n readonly end: number;\n}\n\nfunction nameMatchesSort(\n lang: SurfaceLanguage,\n reading: Reading & { kind: \"name\" },\n sort: string,\n): boolean {\n if (reading.ref.kind === \"var\") {\n const from = reading.ref.sort;\n\n return from === sort || lang.coerce(from, sort) !== null;\n }\n\n // A *leaf* term: nullary, its sort coercing into the named one. A term\n // that takes arguments is not a leaf.\n const info = lang.spec.terms.get(reading.ref.term);\n\n if (info === undefined || info.binders.some((binder) => !binder.binds)) {\n return false;\n }\n\n return (\n info.returnSort === sort || lang.coerce(info.returnSort, sort) !== null\n );\n}\n\nfunction matchCapture(\n lang: SurfaceLanguage,\n text: string,\n position: number,\n klass: string,\n): { captured: Captured; end: number } | null {\n const point = lang.scanner.at(text, position);\n const reading = point.readings.find(\n (r): r is Reading & { kind: \"name\" } =>\n r.kind === \"name\" && nameMatchesSort(lang, r, klass),\n );\n\n if (reading === undefined || reading.kind !== \"name\") {\n return null;\n }\n\n return {\n captured: { start: point.start, text: reading.name },\n end: point.start + reading.length,\n };\n}\n\nfunction matchRule(\n lang: SurfaceLanguage,\n pattern: readonly MatchElement[],\n text: string,\n position: number,\n): RuleMatch | null {\n const captures = new Map<string, Captured[]>();\n let at = position;\n\n for (const element of pattern) {\n if (element.kind === \"literal\") {\n const point = lang.scanner.at(text, at);\n const reading = point.readings.find(\n (r) => r.kind === \"token\" && r.token === element.token,\n );\n\n if (reading === undefined) {\n return null;\n }\n\n at = point.start + reading.length;\n continue;\n }\n\n const taken: Captured[] = [];\n const first = matchCapture(lang, text, at, element.class);\n\n if (first !== null) {\n taken.push(first.captured);\n at = first.end;\n\n if (element.quantifier === \"+\") {\n const separator =\n \"separator\" in element ? (element.separator ?? null) : null;\n\n for (;;) {\n let next = at;\n\n if (separator !== null) {\n const point = lang.scanner.at(text, next);\n const sepReading = point.readings.find(\n (r) => r.kind === \"token\" && r.token === separator,\n );\n\n if (sepReading === undefined) {\n break;\n }\n\n next = point.start + sepReading.length;\n }\n\n const more = matchCapture(lang, text, next, element.class);\n\n if (more === null) {\n break;\n }\n\n taken.push(more.captured);\n at = more.end;\n }\n }\n }\n\n if (taken.length === 0 && element.quantifier !== \"?\") {\n return null;\n }\n\n captures.set(element.name, taken);\n }\n\n return { captures, end: at };\n}\n\ninterface Emission {\n readonly origin: number[];\n readonly text: string;\n}\n\nfunction emitTemplate(\n template: readonly RuleTemplateElement[],\n captures: ReadonlyMap<string, readonly Captured[]>,\n matchStart: number,\n originOf: (index: number) => number,\n separator: \" \" | \"\",\n): Emission {\n const pieces: { text: string; start: number }[] = [];\n\n for (const element of template) {\n if (element.kind === \"literal\") {\n pieces.push({ text: element.token, start: matchStart });\n continue;\n }\n\n const taken = captures.get(element.name) ?? [];\n\n taken.forEach((captured, index) => {\n if (index > 0 && element.separator !== null) {\n pieces.push({ text: element.separator, start: matchStart });\n }\n\n pieces.push({ text: captured.text, start: captured.start });\n });\n }\n\n let text = \"\";\n const origin: number[] = [];\n\n pieces.forEach((piece, index) => {\n if (index > 0 && separator === \" \") {\n text += \" \";\n origin.push(originOf(piece.start));\n }\n\n for (let i = 0; i < piece.text.length; i += 1) {\n origin.push(originOf(piece.start + i));\n }\n\n text += piece.text;\n });\n\n return { text, origin };\n}\n\n/** One pass of one rule, in the given direction. */\nfunction applyRule(\n lang: SurfaceLanguage,\n text: string,\n origin: readonly number[],\n pattern: readonly MatchElement[],\n template: readonly RuleTemplateElement[],\n separator: \" \" | \"\",\n): Elaborated {\n const originOf = (index: number): number =>\n origin[index] ?? origin[origin.length - 1] ?? 0;\n let out = \"\";\n const outOrigin: number[] = [];\n let position = 0;\n\n const copy = (from: number, to: number): void => {\n for (let i = from; i < to && i < text.length; i += 1) {\n out += text[i];\n outOrigin.push(originOf(i));\n }\n };\n\n while (position < text.length) {\n const point = lang.scanner.at(text, position);\n\n copy(position, point.start);\n\n if (point.atEnd) {\n position = text.length;\n break;\n }\n\n const match = matchRule(lang, pattern, text, point.start);\n\n if (match !== null && match.end > point.start) {\n const emitted = emitTemplate(\n template,\n match.captures,\n point.start,\n originOf,\n separator,\n );\n\n out += emitted.text;\n outOrigin.push(...emitted.origin);\n position = match.end;\n continue;\n }\n\n // Advance one whole token (the longest reading), staying on\n // boundaries; an unrecognized character passes through untouched.\n const step = Math.max(1, ...point.readings.map((r) => r.length));\n\n copy(point.start, point.start + step);\n position = point.start + step;\n }\n\n return { text: out, origin: outOrigin };\n}\n\n/** The template read as a pattern: references become captures. */\nfunction invertTemplate(rule: ElabRule): readonly MatchElement[] | null {\n const classes = new Map<string, { class: string; plural: boolean }>();\n\n for (const element of rule.pattern) {\n if (element.kind === \"capture\") {\n classes.set(element.name, {\n class: element.class,\n plural: element.quantifier === \"+\",\n });\n }\n }\n\n const inverted: MatchElement[] = [];\n\n for (const element of rule.template) {\n if (element.kind === \"literal\") {\n inverted.push(element);\n continue;\n }\n\n const known = classes.get(element.name);\n\n if (known === undefined) {\n return null;\n }\n\n inverted.push({\n kind: \"capture\",\n name: element.name,\n class: known.class,\n quantifier: known.plural ? \"+\" : \"\",\n separator: element.separator,\n });\n }\n\n return inverted;\n}\n\n/** The pattern read as a template: captures become plain references. */\nfunction invertPattern(rule: ElabRule): readonly RuleTemplateElement[] {\n return rule.pattern.map((element) =>\n element.kind === \"literal\"\n ? element\n : { kind: \"reference\", name: element.name, separator: null },\n );\n}\n\n/**\n * Apply every elaboration rule forward, in declaration order, returning\n * the elaborated text and the offset map back to the source.\n */\nexport function elaborate(lang: SurfaceLanguage, text: string): Elaborated {\n let current: Elaborated = {\n text,\n origin: [...text].map((_, index) => index),\n };\n\n for (const rule of lang.spec.elabRules) {\n current = applyRule(\n lang,\n current.text,\n current.origin,\n rule.pattern,\n rule.template,\n \" \",\n );\n }\n\n return current;\n}\n\n/**\n * Apply every invertible rule backward over display text, last declared\n * first, joining replacements tight (display is character-level anyway).\n */\nexport function delaborate(lang: SurfaceLanguage, text: string): string {\n let current = text;\n\n for (const rule of [...lang.spec.elabRules].reverse()) {\n if (rule.inputOnly) {\n continue;\n }\n\n const pattern = invertTemplate(rule);\n\n if (pattern === null) {\n continue;\n }\n\n current = applyRule(\n lang,\n current,\n [...current].map((_, index) => index),\n pattern,\n invertPattern(rule),\n \"\",\n ).text;\n }\n\n return current;\n}\n\n/** An elaborated-text span mapped back to source offsets. */\nexport function remapSpan(\n origin: readonly number[],\n span: { readonly start: number; readonly end: number },\n): { start: number; end: number } {\n const last = origin[origin.length - 1] ?? 0;\n const start = origin[span.start] ?? last + 1;\n const end =\n span.end > span.start ? (origin[span.end - 1] ?? last) + 1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AAED,6DAA6D;AAC7D,MAAM,UAAU,SAAS,CACvB,MAAyB,EACzB,IAAsD;IAEtD,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC;IAC7C,MAAM,GAAG,GACP,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAErE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;AACxB,CAAC","sourcesContent":["/**\n * The bidirectional token-elaboration layer — `@syntax elab` rules.\n *\n * Forward (elaboration, before the parser): each rule makes one\n * left-to-right pass over the text, matching at token boundaries only.\n * Where a rule matches, its template is spliced in — literals in their own\n * spelling, captures copied from the source — separated by spaces so the\n * result re-scans cleanly. No fixpoints: matching resumes *after* each\n * replacement, and rules run in declaration order, so the layer terminates\n * by construction. An origin map carries every emitted offset back to\n * the source, so diagnostics and term spans point at what the writer\n * actually typed.\n *\n * Backward (delaboration, after the display printer): the same rules run\n * inverted — template as pattern, pattern as replacement — in reverse\n * declaration order, joined tight, skipping `input-only` rules. A linear\n * rule is a lens: the Quine rule `( ?x:var ) => ∀ ?x` read backward *is*\n * the display convention that writes `∀x` as `(x)`.\n *\n * Captures match single lexicon names — a `@vars` token or a nullary\n * declared term — whose sort coerces into the capture's named sort. The\n * layer is deliberately regular — nesting facts belong to the parser.\n */\n\nimport type { SurfaceLanguage } from \"./parse.js\";\nimport type {\n ElabRule,\n RuleCapture,\n RuleLiteral,\n RuleTemplateElement,\n} from \"./reader/annotations.js\";\nimport type { Reading } from \"./scan.js\";\n\n/**\n * The matcher's pattern element: the reader's, plus an optional separator\n * on a capture — inverted `?ts,*` references match separator-interleaved\n * repeats (`x , y`), which the forward syntax has no way to write.\n */\ntype MatchElement =\n | RuleLiteral\n | (RuleCapture & { readonly separator?: string | null });\n\nexport interface Elaborated {\n /** For each offset of `text`, the source offset it came from. */\n readonly origin: readonly number[];\n readonly text: string;\n}\n\ninterface Captured {\n readonly start: number;\n readonly text: string;\n}\n\ninterface RuleMatch {\n readonly captures: ReadonlyMap<string, readonly Captured[]>;\n readonly end: number;\n}\n\nfunction nameMatchesSort(\n lang: SurfaceLanguage,\n reading: Reading & { kind: \"name\" },\n sort: string,\n): boolean {\n if (reading.ref.kind === \"var\") {\n const from = reading.ref.sort;\n\n return from === sort || lang.coerce(from, sort) !== null;\n }\n\n // A *leaf* term: nullary, its sort coercing into the named one. A term\n // that takes arguments is not a leaf.\n const info = lang.spec.terms.get(reading.ref.term);\n\n if (info === undefined || info.binders.some((binder) => !binder.binds)) {\n return false;\n }\n\n return (\n info.returnSort === sort || lang.coerce(info.returnSort, sort) !== null\n );\n}\n\nfunction matchCapture(\n lang: SurfaceLanguage,\n text: string,\n position: number,\n klass: string,\n): { captured: Captured; end: number } | null {\n const point = lang.scanner.at(text, position);\n const reading = point.readings.find(\n (r): r is Reading & { kind: \"name\" } =>\n r.kind === \"name\" && nameMatchesSort(lang, r, klass),\n );\n\n if (reading === undefined || reading.kind !== \"name\") {\n return null;\n }\n\n return {\n captured: { start: point.start, text: reading.name },\n end: point.start + reading.length,\n };\n}\n\nfunction matchRule(\n lang: SurfaceLanguage,\n pattern: readonly MatchElement[],\n text: string,\n position: number,\n): RuleMatch | null {\n const captures = new Map<string, Captured[]>();\n let at = position;\n\n for (const element of pattern) {\n if (element.kind === \"literal\") {\n const point = lang.scanner.at(text, at);\n const reading = point.readings.find(\n (r) => r.kind === \"token\" && r.token === element.token,\n );\n\n if (reading === undefined) {\n return null;\n }\n\n at = point.start + reading.length;\n continue;\n }\n\n const taken: Captured[] = [];\n const first = matchCapture(lang, text, at, element.class);\n\n if (first !== null) {\n taken.push(first.captured);\n at = first.end;\n\n if (element.quantifier === \"+\") {\n const separator =\n \"separator\" in element ? (element.separator ?? null) : null;\n\n for (;;) {\n let next = at;\n\n if (separator !== null) {\n const point = lang.scanner.at(text, next);\n const sepReading = point.readings.find(\n (r) => r.kind === \"token\" && r.token === separator,\n );\n\n if (sepReading === undefined) {\n break;\n }\n\n next = point.start + sepReading.length;\n }\n\n const more = matchCapture(lang, text, next, element.class);\n\n if (more === null) {\n break;\n }\n\n taken.push(more.captured);\n at = more.end;\n }\n }\n }\n\n if (taken.length === 0 && element.quantifier !== \"?\") {\n return null;\n }\n\n captures.set(element.name, taken);\n }\n\n return { captures, end: at };\n}\n\ninterface Emission {\n readonly origin: number[];\n readonly text: string;\n}\n\nfunction emitTemplate(\n template: readonly RuleTemplateElement[],\n captures: ReadonlyMap<string, readonly Captured[]>,\n matchStart: number,\n originOf: (index: number) => number,\n separator: \" \" | \"\",\n): Emission {\n const pieces: { text: string; start: number }[] = [];\n\n for (const element of template) {\n if (element.kind === \"literal\") {\n pieces.push({ text: element.token, start: matchStart });\n continue;\n }\n\n const taken = captures.get(element.name) ?? [];\n\n taken.forEach((captured, index) => {\n if (index > 0 && element.separator !== null) {\n pieces.push({ text: element.separator, start: matchStart });\n }\n\n pieces.push({ text: captured.text, start: captured.start });\n });\n }\n\n let text = \"\";\n const origin: number[] = [];\n\n pieces.forEach((piece, index) => {\n if (index > 0 && separator === \" \") {\n text += \" \";\n origin.push(originOf(piece.start));\n }\n\n for (let i = 0; i < piece.text.length; i += 1) {\n origin.push(originOf(piece.start + i));\n }\n\n text += piece.text;\n });\n\n return { text, origin };\n}\n\n/** One pass of one rule, in the given direction. */\nfunction applyRule(\n lang: SurfaceLanguage,\n text: string,\n origin: readonly number[],\n pattern: readonly MatchElement[],\n template: readonly RuleTemplateElement[],\n separator: \" \" | \"\",\n): Elaborated {\n const originOf = (index: number): number =>\n origin[index] ?? origin[origin.length - 1] ?? 0;\n let out = \"\";\n const outOrigin: number[] = [];\n let position = 0;\n\n const copy = (from: number, to: number): void => {\n for (let i = from; i < to && i < text.length; i += 1) {\n out += text[i];\n outOrigin.push(originOf(i));\n }\n };\n\n while (position < text.length) {\n const point = lang.scanner.at(text, position);\n\n copy(position, point.start);\n\n if (point.atEnd) {\n position = text.length;\n break;\n }\n\n const match = matchRule(lang, pattern, text, point.start);\n\n if (match !== null && match.end > point.start) {\n const emitted = emitTemplate(\n template,\n match.captures,\n point.start,\n originOf,\n separator,\n );\n\n out += emitted.text;\n outOrigin.push(...emitted.origin);\n position = match.end;\n continue;\n }\n\n // Advance one whole chunk, so the pass only ever resumes on a\n // segmentation boundary; a chunk the vocabulary does not recognize\n // passes through untouched.\n const step = Math.max(1, point.chunk.length);\n\n copy(point.start, point.start + step);\n position = point.start + step;\n }\n\n return { text: out, origin: outOrigin };\n}\n\n/** The template read as a pattern: references become captures. */\nfunction invertTemplate(rule: ElabRule): readonly MatchElement[] | null {\n const classes = new Map<string, { class: string; plural: boolean }>();\n\n for (const element of rule.pattern) {\n if (element.kind === \"capture\") {\n classes.set(element.name, {\n class: element.class,\n plural: element.quantifier === \"+\",\n });\n }\n }\n\n const inverted: MatchElement[] = [];\n\n for (const element of rule.template) {\n if (element.kind === \"literal\") {\n inverted.push(element);\n continue;\n }\n\n const known = classes.get(element.name);\n\n if (known === undefined) {\n return null;\n }\n\n inverted.push({\n kind: \"capture\",\n name: element.name,\n class: known.class,\n quantifier: known.plural ? \"+\" : \"\",\n separator: element.separator,\n });\n }\n\n return inverted;\n}\n\n/** The pattern read as a template: captures become plain references. */\nfunction invertPattern(rule: ElabRule): readonly RuleTemplateElement[] {\n return rule.pattern.map((element) =>\n element.kind === \"literal\"\n ? element\n : { kind: \"reference\", name: element.name, separator: null },\n );\n}\n\n/**\n * Apply every elaboration rule forward, in declaration order, returning\n * the elaborated text and the offset map back to the source.\n */\nexport function elaborate(lang: SurfaceLanguage, text: string): Elaborated {\n let current: Elaborated = {\n text,\n origin: [...text].map((_, index) => index),\n };\n\n for (const rule of lang.spec.elabRules) {\n current = applyRule(\n lang,\n current.text,\n current.origin,\n rule.pattern,\n rule.template,\n \" \",\n );\n }\n\n return current;\n}\n\n/**\n * Apply every invertible rule backward over display text, last declared\n * first, joining replacements tight (display is character-level anyway).\n */\nexport function delaborate(lang: SurfaceLanguage, text: string): string {\n let current = text;\n\n for (const rule of [...lang.spec.elabRules].reverse()) {\n if (rule.inputOnly) {\n continue;\n }\n\n const pattern = invertTemplate(rule);\n\n if (pattern === null) {\n continue;\n }\n\n current = applyRule(\n lang,\n current,\n [...current].map((_, index) => index),\n pattern,\n invertPattern(rule),\n \"\",\n ).text;\n }\n\n return current;\n}\n\n/** An elaborated-text span mapped back to source offsets. */\nexport function remapSpan(\n origin: readonly number[],\n span: { readonly start: number; readonly end: number },\n): { start: number; end: number } {\n const last = origin[origin.length - 1] ?? 0;\n const start = origin[span.start] ?? last + 1;\n const end =\n span.end > span.start ? (origin[span.end - 1] ?? last) + 1 : start;\n\n return { start, end };\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -3,9 +3,11 @@
3
3
  *
4
4
  * The public API grows stage by stage; see the README for the layer stack.
5
5
  */
6
- export type { Diagnostic, Span } from "./diagnostics.js";
6
+ export type { DelimiterRules, DelimiterSet } from "./delimiters.js";
7
+ export { chunkAt, delimiterRules, isReachableChunk, segment, } from "./delimiters.js";
8
+ export type { Diagnostic, Severity, Span } from "./diagnostics.js";
7
9
  export { boundVariableBinders, stripSyntaxAnnotations } from "./engine.js";
8
- export type { ParseFailure, ParseResult, ParseSuccess, } from "./parse.js";
10
+ export type { ParseFailure, ParseMode, ParseResult, ParseSuccess, } from "./parse.js";
9
11
  export { SurfaceLanguage } from "./parse.js";
10
12
  export type { PrintMode } from "./print.js";
11
13
  export { printTerm } from "./print.js";
@@ -14,7 +16,9 @@ export type { CoercionInfo, NotationInfo, SortInfo, Spec, SpecParse, TermInfo, }
14
16
  export { parseSpec } from "./reader/spec.js";
15
17
  export type { Annotation, AssertStatement, Binder, CoercionStatement, DefStatement, DelimiterStatement, GenNotationStatement, MathString, NotationLiteral, Precedence, SimpleNotationStatement, SortStatement, Statement, StatementParse, TermStatement, TypeRef, } from "./reader/statements.js";
16
18
  export { parseStatements } from "./reader/statements.js";
17
- export type { NameRef, Reading, ScanPoint } from "./scan.js";
19
+ export type { Reading, ScanPoint } from "./scan.js";
18
20
  export { Scanner } from "./scan.js";
19
21
  export type { AppTerm, Fixity, Term, VariableTerm } from "./term.js";
20
22
  export { walkTerm } from "./term.js";
23
+ export type { NameRef, Vocabulary } from "./vocabulary.js";
24
+ export { surfaceVocabulary } from "./vocabulary.js";
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * The public API grows stage by stage; see the README for the layer stack.
5
5
  */
6
+ export { chunkAt, delimiterRules, isReachableChunk, segment, } from "./delimiters.js";
6
7
  export { boundVariableBinders, stripSyntaxAnnotations } from "./engine.js";
7
8
  export { SurfaceLanguage } from "./parse.js";
8
9
  export { printTerm } from "./print.js";
@@ -10,4 +11,5 @@ export { parseSpec } from "./reader/spec.js";
10
11
  export { parseStatements } from "./reader/statements.js";
11
12
  export { Scanner } from "./scan.js";
12
13
  export { walkTerm } from "./term.js";
14
+ export { surfaceVocabulary } from "./vocabulary.js";
13
15
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAM3E,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAmBvC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAmB7C,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC","sourcesContent":["/**\n * @aufbau/syntax — surface syntax over MM0.\n *\n * The public API grows stage by stage; see the README for the layer stack.\n */\n\nexport type { Diagnostic, Span } from \"./diagnostics.js\";\nexport { boundVariableBinders, stripSyntaxAnnotations } from \"./engine.js\";\nexport type {\n ParseFailure,\n ParseResult,\n ParseSuccess,\n} from \"./parse.js\";\nexport { SurfaceLanguage } from \"./parse.js\";\nexport type { PrintMode } from \"./print.js\";\nexport { printTerm } from \"./print.js\";\nexport type {\n ElabRule,\n LintName,\n RuleCapture,\n RuleLiteral,\n RulePatternElement,\n RuleReference,\n RuleTemplateElement,\n SyntaxAnnotation,\n} from \"./reader/annotations.js\";\nexport type {\n CoercionInfo,\n NotationInfo,\n SortInfo,\n Spec,\n SpecParse,\n TermInfo,\n} from \"./reader/spec.js\";\nexport { parseSpec } from \"./reader/spec.js\";\nexport type {\n Annotation,\n AssertStatement,\n Binder,\n CoercionStatement,\n DefStatement,\n DelimiterStatement,\n GenNotationStatement,\n MathString,\n NotationLiteral,\n Precedence,\n SimpleNotationStatement,\n SortStatement,\n Statement,\n StatementParse,\n TermStatement,\n TypeRef,\n} from \"./reader/statements.js\";\nexport { parseStatements } from \"./reader/statements.js\";\nexport type { NameRef, Reading, ScanPoint } from \"./scan.js\";\nexport { Scanner } from \"./scan.js\";\nexport type { AppTerm, Fixity, Term, VariableTerm } from \"./term.js\";\nexport { walkTerm } from \"./term.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EACL,OAAO,EACP,cAAc,EACd,gBAAgB,EAChB,OAAO,GACR,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAO3E,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAmBvC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAmB7C,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAErC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC","sourcesContent":["/**\n * @aufbau/syntax — surface syntax over MM0.\n *\n * The public API grows stage by stage; see the README for the layer stack.\n */\n\nexport type { DelimiterRules, DelimiterSet } from \"./delimiters.js\";\nexport {\n chunkAt,\n delimiterRules,\n isReachableChunk,\n segment,\n} from \"./delimiters.js\";\nexport type { Diagnostic, Severity, Span } from \"./diagnostics.js\";\nexport { boundVariableBinders, stripSyntaxAnnotations } from \"./engine.js\";\nexport type {\n ParseFailure,\n ParseMode,\n ParseResult,\n ParseSuccess,\n} from \"./parse.js\";\nexport { SurfaceLanguage } from \"./parse.js\";\nexport type { PrintMode } from \"./print.js\";\nexport { printTerm } from \"./print.js\";\nexport type {\n ElabRule,\n LintName,\n RuleCapture,\n RuleLiteral,\n RulePatternElement,\n RuleReference,\n RuleTemplateElement,\n SyntaxAnnotation,\n} from \"./reader/annotations.js\";\nexport type {\n CoercionInfo,\n NotationInfo,\n SortInfo,\n Spec,\n SpecParse,\n TermInfo,\n} from \"./reader/spec.js\";\nexport { parseSpec } from \"./reader/spec.js\";\nexport type {\n Annotation,\n AssertStatement,\n Binder,\n CoercionStatement,\n DefStatement,\n DelimiterStatement,\n GenNotationStatement,\n MathString,\n NotationLiteral,\n Precedence,\n SimpleNotationStatement,\n SortStatement,\n Statement,\n StatementParse,\n TermStatement,\n TypeRef,\n} from \"./reader/statements.js\";\nexport { parseStatements } from \"./reader/statements.js\";\nexport type { Reading, ScanPoint } from \"./scan.js\";\nexport { Scanner } from \"./scan.js\";\nexport type { AppTerm, Fixity, Term, VariableTerm } from \"./term.js\";\nexport { walkTerm } from \"./term.js\";\nexport type { NameRef, Vocabulary } from \"./vocabulary.js\";\nexport { surfaceVocabulary } from \"./vocabulary.js\";\n"]}
package/dist/parse.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * The surface parser: a faithful port of MM0's operator-precedence math
3
- * parser (mm0.md, "the dynamic parser"), running over the character-level
4
- * scanner instead of MM0's whitespace lexer, with exactly three declared
5
- * extensions beyond the upstream grammar:
3
+ * parser (mm0.md, "the dynamic parser"), running over the delimiter
4
+ * scanner — MM0's own segmentation rule under a wider, declared delimiter
5
+ * set — with exactly three declared extensions beyond the upstream
6
+ * grammar:
6
7
  *
7
8
  * 1. **Grouping pairs** — `expression(max) → open expression(0) close`
8
9
  * for every declared bracket pair, close matching open;
@@ -71,10 +72,20 @@ export interface ParseFailure {
71
72
  readonly diagnostics: readonly Diagnostic[];
72
73
  }
73
74
  export type ParseResult = ParseFailure | ParseSuccess;
75
+ /**
76
+ * Which delimiter set cuts the input up. `surface` is student input, read
77
+ * under the spec's `surfaceDelimiters`; `engine` is this library's own
78
+ * engine-mode emission, read under the theory's own `delimiters` — the
79
+ * counterpart of `printTerm`'s two modes.
80
+ */
81
+ export type ParseMode = "engine" | "surface";
74
82
  /** Everything derived from a Spec that parsing needs, built once. */
75
83
  export declare class SurfaceLanguage {
76
84
  readonly spec: Spec;
85
+ /** Student input: the wide surface delimiter set. */
77
86
  readonly scanner: Scanner;
87
+ /** Engine text: the same vocabulary under the theory's own delimiters. */
88
+ readonly engineScanner: Scanner;
78
89
  readonly heads: Map<string, HeadEntry>;
79
90
  readonly infixes: Map<string, InfixEntry>;
80
91
  readonly closeOf: Map<string, string>;
@@ -103,11 +114,18 @@ export declare class SurfaceLanguage {
103
114
  /**
104
115
  * Parse surface text. `lints: false` skips the spec's refusal
105
116
  * conventions (bracket discipline, chain refusal, closed sentences) —
106
- * for reading text that is grammatical but not surface-idiomatic, such
107
- * as this library's own engine-mode output.
117
+ * for reading text that is grammatical but not surface-idiomatic.
118
+ *
119
+ * `mode: "engine"` reads this library's own engine-mode output instead:
120
+ * the theory's delimiters rather than the surface set, no elaboration,
121
+ * and lints off unless asked for. Engine text is whitespace-separated
122
+ * and fully parenthesized, so it needs no wide delimiter set — and a
123
+ * surface elab rule would misread it, Quine's `( ?x:var )` happily
124
+ * eating the `(x)` inside `(F (x))`.
108
125
  */
109
126
  parse(text: string, options?: {
110
127
  readonly lints?: boolean;
128
+ readonly mode?: ParseMode;
111
129
  }): ParseResult;
112
130
  }
113
131
  export {};