@aufbau/syntax 0.0.5 → 0.0.6
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 +129 -0
- package/README.md +5 -2
- package/dist/delimiters.d.ts +13 -0
- package/dist/delimiters.js +26 -0
- package/dist/delimiters.js.map +1 -1
- package/dist/elab.d.ts +3 -1
- package/dist/elab.js +49 -5
- package/dist/elab.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/parse.d.ts +28 -14
- package/dist/parse.js +108 -49
- package/dist/parse.js.map +1 -1
- package/dist/print.d.ts +42 -9
- package/dist/print.js +383 -144
- package/dist/print.js.map +1 -1
- package/dist/reader/annotations.d.ts +14 -1
- package/dist/reader/annotations.js +14 -1
- package/dist/reader/annotations.js.map +1 -1
- package/dist/reader/spec.d.ts +47 -0
- package/dist/reader/spec.js +175 -41
- package/dist/reader/spec.js.map +1 -1
- package/dist/reader/statements.d.ts +18 -2
- package/dist/reader/statements.js +54 -16
- package/dist/reader/statements.js.map +1 -1
- package/dist/scan.d.ts +3 -2
- package/dist/scan.js +1 -0
- package/dist/scan.js.map +1 -1
- package/dist/unfold.d.ts +23 -0
- package/dist/unfold.js +131 -0
- package/dist/unfold.js.map +1 -0
- package/dist/vocabulary.d.ts +9 -0
- package/dist/vocabulary.js +21 -5
- package/dist/vocabulary.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,134 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.0.6 — 2026-10-18
|
|
6
|
+
|
|
7
|
+
**Elab rules a text cannot use cost nothing.** A rule with a literal the
|
|
8
|
+
text does not contain cannot match, so both directions now skip its pass.
|
|
9
|
+
Output is unchanged; a forallx UBC formula, with two hundred subscript
|
|
10
|
+
rules, reads and prints in about a tenth of a millisecond, down from 3–20.
|
|
11
|
+
|
|
12
|
+
**An elab literal may be a delimiter.** `delimiter_unknown` no longer
|
|
13
|
+
refuses an entry that only an elab rule reads — a pattern literal, or the
|
|
14
|
+
template literal of a rule delaboration runs — so `$ ?t:tm ' $` can fire
|
|
15
|
+
on an unspaced `x'` once `'` delimits.
|
|
16
|
+
|
|
17
|
+
**Defs unfold.** `unfoldDefinitions(language, term)` replaces every `def`
|
|
18
|
+
application with its definiens, the def's binders filled by the arguments,
|
|
19
|
+
so a consumer comparing terms by shape sees what the engine sees: `a ≠ b`
|
|
20
|
+
and `¬ a = b` are one formula. A dot-dummy an argument also names is
|
|
21
|
+
renamed from its sort's `@vars` pool rather than capturing it, and a term
|
|
22
|
+
with no def in it comes back as the same object. `TermInfo.definition`
|
|
23
|
+
carries the definiens it reads.
|
|
24
|
+
|
|
25
|
+
**Display resets where the sort changes.** Under `drop-outer-parens` a
|
|
26
|
+
formula is now outermost wherever the constructor above it returns
|
|
27
|
+
another sort, not only at the top of the printed term, so a signed row
|
|
28
|
+
prints as the book writes it: `𝕋 A ∧ B`, not `𝕋(A ∧ B)`, and a sequent
|
|
29
|
+
`A ∧ B; C ⊢ D`. An operator of the formula's own sort keeps the pair
|
|
30
|
+
(`𝔽 ¬(A ∧ B)`), and the precedence check still brackets whatever would
|
|
31
|
+
not read back bare. A notation that changes sort is spaced as a
|
|
32
|
+
connective is — `𝕋 A`, `1.1 𝔽 □A`, `Γ ⊢ A`, and `a = b`, which was
|
|
33
|
+
`a=b`. And a notation token declared a delimiter on one side only hugs
|
|
34
|
+
that side and stands off the other: a right-only comma prints `R(a, b)`.
|
|
35
|
+
|
|
36
|
+
**A rule's `@fallback` is data.** `RuleInfo.fallback` names the rule the
|
|
37
|
+
engine retries a failed application with, read from the engine's own
|
|
38
|
+
`@fallback` annotation, which stays foreign — `@vars` was the one such
|
|
39
|
+
annotation the reader listened in on, and this is the second. The reader
|
|
40
|
+
checks what the engine would: one per rule (`fallback_duplicate`), naming
|
|
41
|
+
an earlier axiom or theorem (`fallback_unknown`), so a chain always ends.
|
|
42
|
+
A consumer showing ∧E as both its axioms no longer has to match
|
|
43
|
+
annotation text.
|
|
44
|
+
|
|
45
|
+
**Printing then parsing is the identity, for every term.** Display text
|
|
46
|
+
used to set its pieces tight whatever the delimiters said, so under a spec
|
|
47
|
+
without letter delimiters `∀x Cube(x)` printed as `∀xCube(x)` — one chunk
|
|
48
|
+
`xCube` to its own reader. Every seam now goes through `adjoin` (exported
|
|
49
|
+
from the delimiter module): tight where the reader's delimiters cut
|
|
50
|
+
anyway, a space where they would not. Engine text uses the same rule with
|
|
51
|
+
the theory's delimiters, which subsumes the old grouping-spacing special
|
|
52
|
+
case. Delaboration joins its output the same way.
|
|
53
|
+
|
|
54
|
+
Display parentheses are now exactly what the parser needs, read from its
|
|
55
|
+
own precedence table (`generalParts` shares the general-notation slots
|
|
56
|
+
with the printer): a piece stands bare when its head binds as tight as
|
|
57
|
+
the slot reads and nothing open on its right edge would take in the next
|
|
58
|
+
operator. Before, only connectives were ever parenthesized, so
|
|
59
|
+
`(1 + 0) * 0` printed as `1 + 0 * 0` in any theory with term-level
|
|
60
|
+
arithmetic. Also fixed on the way: a bound variable in display
|
|
61
|
+
application prints bare (`sb x(t)(p)`, which is what the reader takes),
|
|
62
|
+
a right-nested juxtaposed argument keeps its brackets rather than
|
|
63
|
+
flattening into the left-nested `Rxyz`, and `drop-outer-parens` drops the
|
|
64
|
+
connective's own pair rather than slicing any text that happened to
|
|
65
|
+
start with `(`.
|
|
66
|
+
|
|
67
|
+
The one term display text cannot spell is an `@syntax elided` term
|
|
68
|
+
anywhere but where the reader supplies it — `F(snil,b)` — and there
|
|
69
|
+
`printTerm` now throws `UnprintableTermError` rather than write `snil`,
|
|
70
|
+
which Calgary cannot read back and Magnus would glue into three more
|
|
71
|
+
arguments. Engine text spells it by name, as before.
|
|
72
|
+
|
|
73
|
+
`tests/round-trip.test.ts` holds the law over random well-sorted terms on
|
|
74
|
+
every spec and every corpus file, in both modes.
|
|
75
|
+
|
|
76
|
+
**The math-string parser reads all of MM0's application syntax.** A
|
|
77
|
+
constructor applied by name — `S x`, `pair a b`, `succ (succ x)` — reads
|
|
78
|
+
as `expression(1024) → FUNC expression(max){n}`, exactly as the engine
|
|
79
|
+
reads it; before, an argument had to be bracketed (`S(x)`), and a
|
|
80
|
+
two-place term with no notation could only be written `pair(a)(b)`. Every
|
|
81
|
+
term is now a lexicon name — one with a notation, one with bound binders
|
|
82
|
+
(`sb x t p`, `all x p`) — with the bound slots filled positionally by a
|
|
83
|
+
variable. The declared surface shapes keep precedence: an `@syntax
|
|
84
|
+
elided` sort still reads a bare letter as the elision, `@syntax
|
|
85
|
+
juxtaposed` still glues. `delimiter_unreachable_name` now fires only for
|
|
86
|
+
a term whose name is its only spelling.
|
|
87
|
+
|
|
88
|
+
**The statement reader takes the rest of the grammar**: `input`/`output`
|
|
89
|
+
statements (carried as `InOutStatement`, uninterpreted), the arrow sugar
|
|
90
|
+
on a `def` (`DefStatement.returnChain` replaces `returnType`), a def's
|
|
91
|
+
dot-dummies excluded from its arity (they are variables of the
|
|
92
|
+
definiens, never arguments — `def le {.k: nat} (a b: nat)` takes an
|
|
93
|
+
`infixl`), and sorts and terms as separate namespaces (`sort nat` beside
|
|
94
|
+
`def nat`, as in peano.mm0).
|
|
95
|
+
|
|
96
|
+
**Dead tokens.** A notation token the delimiters cut through (`/\` in a
|
|
97
|
+
file whose `[x/t]` makes `/` a delimiter) is reported as a
|
|
98
|
+
`delimiter_splits_token` warning — mm0.md forbids it, the engine cannot
|
|
99
|
+
read it either — and the printer no longer chooses it as the canonical
|
|
100
|
+
spelling. Engine-mode printing also spaces its grouping (`F ( a )`) for a
|
|
101
|
+
theory that declares no delimiters at all, since there `(a)` is one
|
|
102
|
+
token, and writes a bound binder's variable bare.
|
|
103
|
+
|
|
104
|
+
**An MM0 corpus** under `tests/fixtures/mm0/` — the upstream examples
|
|
105
|
+
(peano, set, hol, mm0.mm0, x86) and the Aufbau repository's theories —
|
|
106
|
+
now gates all of this: every math string parses, round-trips through
|
|
107
|
+
engine printing, and compiles with the Aufbau compiler to byte-identical
|
|
108
|
+
MMB with the original text.
|
|
109
|
+
|
|
110
|
+
**`@syntax role` may sit on a rule** (`RuleInfo.roles`, symmetric with
|
|
111
|
+
sorts and terms). A calculus can now say which of its axioms is the
|
|
112
|
+
assumption rule — `role assumption` beside `alias AS` — so a proof editor
|
|
113
|
+
reads that off the spec instead of taking it per exercise or guessing
|
|
114
|
+
from a spelling. Uninterpreted here, as every role is. `role_target` now
|
|
115
|
+
reads "a sort, a term, or a rule".
|
|
116
|
+
|
|
117
|
+
**A rule can carry the names a proof cites it by.** A new per-rule
|
|
118
|
+
`@syntax alias <name>…` annotation, attached to an `axiom` or a
|
|
119
|
+
`theorem`. MM0 identifiers are ASCII, so a textbook's `∧I` was never
|
|
120
|
+
going to be the axiom's own name; the alias is the surface name for the
|
|
121
|
+
rule, as a notation is the surface spelling of a term, and it is a
|
|
122
|
+
whitespace-free token by construction — the shape a citation has wherever
|
|
123
|
+
a proof line is read. `Spec` gains `rules` (every axiom and theorem, keyed
|
|
124
|
+
by name, with a `RuleInfo` carrying its `aliases`) and `ruleAliases`, the
|
|
125
|
+
inverted map that is the whole consumer contract:
|
|
126
|
+
`spec.ruleAliases.get(cited) ?? cited` is what to hand the engine. The
|
|
127
|
+
library resolves nothing itself. The reader refuses an alias that is any
|
|
128
|
+
rule's name (`alias_is_rule_name`), one another rule already claimed
|
|
129
|
+
(`alias_duplicate`), and — new — a second declaration of one rule name
|
|
130
|
+
(`duplicate_declaration`), which the engine refuses too.
|
|
131
|
+
|
|
3
132
|
## 0.0.5
|
|
4
133
|
|
|
5
134
|
**Free-standing adjacency.** `@syntax juxtaposed` is now read in its full
|
package/README.md
CHANGED
|
@@ -26,7 +26,8 @@ One spec file per textbook system; no code per system.
|
|
|
26
26
|
## The layer stack
|
|
27
27
|
|
|
28
28
|
1. **Statement reader** — parses the MM0 statement grammar (sorts, terms,
|
|
29
|
-
|
|
29
|
+
definitions, axioms and theorems, notations, coercions, delimiters,
|
|
30
|
+
input/output) and `--|` annotations into a `Spec`.
|
|
30
31
|
`@syntax` annotations are understood structurally; all others (`@acui`,
|
|
31
32
|
`@congr`, …) pass through as data — except `@vars`, which is read *and*
|
|
32
33
|
passed through: the engine's variable pools are the surface lexicon's
|
|
@@ -59,7 +60,9 @@ One spec file per textbook system; no code per system.
|
|
|
59
60
|
Early, but the layer stack is complete and tested end to end: three
|
|
60
61
|
example specs (`forallx-calgary-2019`, `forallx-magnus`, `carnap-prop`),
|
|
61
62
|
a behavioral corpus transcribed from the parsers this library replaces,
|
|
62
|
-
round-trip
|
|
63
|
+
a round-trip law for both print modes checked over random terms on every
|
|
64
|
+
spec and corpus file (`tests/round-trip.test.ts`), an acceptance test in
|
|
65
|
+
which the real
|
|
63
66
|
Aufbau compiler parses this library's engine output and certifies it
|
|
64
67
|
tree-identical to hand-written spellings (`tests/engine-align.test.ts`),
|
|
65
68
|
and a monotonicity suite pinning the property the delimiter design exists
|
package/dist/delimiters.d.ts
CHANGED
|
@@ -48,3 +48,16 @@ export declare function segment(text: string, rules: DelimiterRules): string[];
|
|
|
48
48
|
* happens before anything knows the name exists.
|
|
49
49
|
*/
|
|
50
50
|
export declare function isReachableChunk(name: string, rules: DelimiterRules): boolean;
|
|
51
|
+
/**
|
|
52
|
+
* `left` then `right`, written so the text segments into exactly `left`'s
|
|
53
|
+
* chunks followed by `right`'s: tight where the delimiters already cut at
|
|
54
|
+
* the seam, and with one space where they would not. Under letter
|
|
55
|
+
* delimiters `∀` and `x` and `Cube(x)` set tight as `∀xCube(x)`; without
|
|
56
|
+
* them that is one chunk `xCube`, and the seam gets its space —
|
|
57
|
+
* `∀x Cube(x)`.
|
|
58
|
+
*
|
|
59
|
+
* This is what makes printing total: a space always separates, since no
|
|
60
|
+
* delimiter contains whitespace, so whatever the two pieces are, the
|
|
61
|
+
* result reads back as both of them.
|
|
62
|
+
*/
|
|
63
|
+
export declare function adjoin(left: string, right: string, rules: DelimiterRules): string;
|
package/dist/delimiters.js
CHANGED
|
@@ -94,4 +94,30 @@ export function segment(text, rules) {
|
|
|
94
94
|
export function isReachableChunk(name, rules) {
|
|
95
95
|
return name.length > 0 && chunkAt(name, 0, rules) === name;
|
|
96
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* `left` then `right`, written so the text segments into exactly `left`'s
|
|
99
|
+
* chunks followed by `right`'s: tight where the delimiters already cut at
|
|
100
|
+
* the seam, and with one space where they would not. Under letter
|
|
101
|
+
* delimiters `∀` and `x` and `Cube(x)` set tight as `∀xCube(x)`; without
|
|
102
|
+
* them that is one chunk `xCube`, and the seam gets its space —
|
|
103
|
+
* `∀x Cube(x)`.
|
|
104
|
+
*
|
|
105
|
+
* This is what makes printing total: a space always separates, since no
|
|
106
|
+
* delimiter contains whitespace, so whatever the two pieces are, the
|
|
107
|
+
* result reads back as both of them.
|
|
108
|
+
*/
|
|
109
|
+
export function adjoin(left, right, rules) {
|
|
110
|
+
if (left.length === 0 ||
|
|
111
|
+
right.length === 0 ||
|
|
112
|
+
/\s$/.test(left) ||
|
|
113
|
+
/^\s/.test(right)) {
|
|
114
|
+
return left + right;
|
|
115
|
+
}
|
|
116
|
+
const tight = left + right;
|
|
117
|
+
const apart = [...segment(left, rules), ...segment(right, rules)];
|
|
118
|
+
const together = segment(tight, rules);
|
|
119
|
+
const same = together.length === apart.length &&
|
|
120
|
+
together.every((chunk, index) => chunk === apart[index]);
|
|
121
|
+
return same ? tight : `${left} ${right}`;
|
|
122
|
+
}
|
|
97
123
|
//# sourceMappingURL=delimiters.js.map
|
package/dist/delimiters.js.map
CHANGED
|
@@ -1 +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,G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AQ,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"]}
|
|
1
|
+
{"version":3,"file":"delimiters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AAI,KAAK,EAAE,CAAC;AAC3C,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\n/**\n * `left` then `right`, written so the text segments into exactly `left`'s\n * chunks followed by `right`'s: tight where the delimiters already cut at\n * the seam, and with one space where they would not. Under letter\n * delimiters `∀` and `x` and `Cube(x)` set tight as `∀xCube(x)`; without\n * them that is one chunk `xCube`, and the seam gets its space —\n * `∀x Cube(x)`.\n *\n * This is what makes printing total: a space always separates, since no\n * delimiter contains whitespace, so whatever the two pieces are, the\n * result reads back as both of them.\n */\nexport function adjoin(\n left: string,\n right: string,\n rules: DelimiterRules,\n): string {\n if (\n left.length === 0 ||\n right.length === 0 ||\n /\\s$/.test(left) ||\n /^\\s/.test(right)\n ) {\n return left + right;\n }\n\n const tight = left + right;\n const apart = [...segment(left, rules), ...segment(right, rules)];\n const together = segment(tight, rules);\n const same =\n together.length === apart.length &&\n together.every((chunk, index) => chunk === apart[index]);\n\n return same ? tight : `${left} ${right}`;\n}\n"]}
|
package/dist/elab.d.ts
CHANGED
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
*
|
|
14
14
|
* Backward (delaboration, after the display printer): the same rules run
|
|
15
15
|
* inverted — template as pattern, pattern as replacement — in reverse
|
|
16
|
-
* declaration order, joined tight
|
|
16
|
+
* declaration order, joined as tight as the delimiters allow (a space only
|
|
17
|
+
* at a seam that would otherwise run two chunks together, as the printer
|
|
18
|
+
* does), skipping `input-only` rules. A linear
|
|
17
19
|
* rule is a lens: the Quine rule `( ?x:var ) => ∀ ?x` read backward *is*
|
|
18
20
|
* the display convention that writes `∀x` as `(x)`.
|
|
19
21
|
*
|
package/dist/elab.js
CHANGED
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
*
|
|
14
14
|
* Backward (delaboration, after the display printer): the same rules run
|
|
15
15
|
* inverted — template as pattern, pattern as replacement — in reverse
|
|
16
|
-
* declaration order, joined tight
|
|
16
|
+
* declaration order, joined as tight as the delimiters allow (a space only
|
|
17
|
+
* at a seam that would otherwise run two chunks together, as the printer
|
|
18
|
+
* does), skipping `input-only` rules. A linear
|
|
17
19
|
* rule is a lens: the Quine rule `( ?x:var ) => ∀ ?x` read backward *is*
|
|
18
20
|
* the display convention that writes `∀x` as `(x)`.
|
|
19
21
|
*
|
|
@@ -42,6 +44,7 @@
|
|
|
42
44
|
* genuinely both `∀x` and A-applied-to-x; there, juxtaposition has to be a
|
|
43
45
|
* parser behavior (`@syntax juxtaposed`), as it is for Magnus.
|
|
44
46
|
*/
|
|
47
|
+
import { adjoin } from "./delimiters.js";
|
|
45
48
|
const NO_SCOPE = new Map();
|
|
46
49
|
function nameMatchesSort(lang, reading, sort) {
|
|
47
50
|
if (reading.ref.kind === "var") {
|
|
@@ -126,7 +129,7 @@ function matchRule(lang, pattern, text, position, scope) {
|
|
|
126
129
|
}
|
|
127
130
|
return { captures, end: at };
|
|
128
131
|
}
|
|
129
|
-
function emitTemplate(template, captures, matchStart, originOf, separator) {
|
|
132
|
+
function emitTemplate(template, captures, matchStart, originOf, separator, rules) {
|
|
130
133
|
const pieces = [];
|
|
131
134
|
for (const element of template) {
|
|
132
135
|
if (element.kind === "literal") {
|
|
@@ -144,7 +147,7 @@ function emitTemplate(template, captures, matchStart, originOf, separator) {
|
|
|
144
147
|
let text = "";
|
|
145
148
|
const origin = [];
|
|
146
149
|
pieces.forEach((piece, index) => {
|
|
147
|
-
if (index > 0 &&
|
|
150
|
+
if (index > 0 && needsSpace(text, piece.text, separator, rules)) {
|
|
148
151
|
text += " ";
|
|
149
152
|
origin.push(originOf(piece.start));
|
|
150
153
|
}
|
|
@@ -155,14 +158,53 @@ function emitTemplate(template, captures, matchStart, originOf, separator) {
|
|
|
155
158
|
});
|
|
156
159
|
return { text, origin };
|
|
157
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Whether `right` needs a space after `left`: always when spaced, and when
|
|
163
|
+
* tight only where the two would otherwise run together — see
|
|
164
|
+
* {@link adjoin}.
|
|
165
|
+
*/
|
|
166
|
+
function needsSpace(left, right, separator, rules) {
|
|
167
|
+
if (separator === " ") {
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
return adjoin(left, right, rules).length > left.length + right.length;
|
|
171
|
+
}
|
|
158
172
|
/** One pass of one rule, in the given direction. */
|
|
159
173
|
function applyRule(lang, text, origin, pattern, template, separator, scope) {
|
|
174
|
+
// A literal matches a whole chunk, and a chunk is a slice of the text, so
|
|
175
|
+
// a rule with a literal the text does not contain cannot match anywhere.
|
|
176
|
+
// A pass that matches nothing returns its input unchanged, so skipping it
|
|
177
|
+
// is exact — and it makes the many rules a given text cannot use (UBC's
|
|
178
|
+
// two hundred subscripts) nearly free.
|
|
179
|
+
if (pattern.some((element) => element.kind === "literal" && !text.includes(element.token))) {
|
|
180
|
+
return { text, origin };
|
|
181
|
+
}
|
|
160
182
|
const originOf = (index) => origin[index] ?? origin[origin.length - 1] ?? 0;
|
|
161
183
|
let out = "";
|
|
162
184
|
const outOrigin = [];
|
|
163
185
|
let position = 0;
|
|
186
|
+
// Set after a replacement: the seams on either side of emitted text are
|
|
187
|
+
// new, and tight output checks them. Copied text meets copied text at a
|
|
188
|
+
// seam the source already had, which reads as it did.
|
|
189
|
+
let fresh = false;
|
|
190
|
+
// A seam in tight output that would run two chunks together gets a
|
|
191
|
+
// space, attributed to the character after it.
|
|
192
|
+
const seam = (next, at) => {
|
|
193
|
+
if (fresh &&
|
|
194
|
+
separator === "" &&
|
|
195
|
+
needsSpace(out, next, separator, lang.scanner.rules)) {
|
|
196
|
+
out += " ";
|
|
197
|
+
outOrigin.push(at);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
164
200
|
const copy = (from, to) => {
|
|
165
|
-
|
|
201
|
+
const end = Math.min(to, text.length);
|
|
202
|
+
if (end <= from) {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
seam(text.slice(from, end), originOf(from));
|
|
206
|
+
fresh = false;
|
|
207
|
+
for (let i = from; i < end; i += 1) {
|
|
166
208
|
out += text[i];
|
|
167
209
|
outOrigin.push(originOf(i));
|
|
168
210
|
}
|
|
@@ -176,7 +218,9 @@ function applyRule(lang, text, origin, pattern, template, separator, scope) {
|
|
|
176
218
|
}
|
|
177
219
|
const match = matchRule(lang, pattern, text, point.start, scope);
|
|
178
220
|
if (match !== null && match.end > point.start) {
|
|
179
|
-
const emitted = emitTemplate(template, match.captures, point.start, originOf, separator);
|
|
221
|
+
const emitted = emitTemplate(template, match.captures, point.start, originOf, separator, lang.scanner.rules);
|
|
222
|
+
fresh = true;
|
|
223
|
+
seam(emitted.text, emitted.origin[0] ?? originOf(point.start));
|
|
180
224
|
out += emitted.text;
|
|
181
225
|
outOrigin.push(...emitted.origin);
|
|
182
226
|
position = match.end;
|
package/dist/elab.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"elab.js","sourceRoot":"","sources":["../src/elab.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAWH,MAAM,QAAQ,GAAU,IAAI,GAAG,EAAE,CAAC;AA2BlC,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,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACvE,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,IAAI,CAAC,UAAU,KAAK,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CACnB,IAAqB,EACrB,IAAY,EACZ,QAAgB,EAChB,KAAa,EACb,KAAY;IAEZ,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CA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E,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,EACF,QAAQ,CACT,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 chunk 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. A\n * literal matches a whole chunk, which need not be declared vocabulary at\n * all: the layer exists to accept surface forms the MM0 grammar rejects.\n * It is deliberately regular — nesting facts belong to the parser.\n *\n * **The three commitments.** What an author has to reason about is that\n * this layer decides, and the parser then inherits the decision as fact —\n * the parser backtracks over ambiguity, but only over what reaches it.\n *\n * - *Leftmost*: the first match at the earliest scan point wins, and the\n * span it consumed is replaced and never re-examined.\n * - *Greedy*: a `+` capture takes the maximum it can and never gives one\n * back to let the rest of the pattern match.\n * - *One sweep per rule*, in declaration order, so a later rule sees\n * what earlier rules emitted, and never the other way round.\n *\n * The hazard those three add up to: a rule may eat a span that had another\n * reading. Prefer patterns anchored by a leading literal — a spelling the\n * author chose — over capture-initial ones, which fire wherever the sorts\n * line up. The dialect where even that is not enough is one with both\n * letter-spelled quantifiers and juxtaposed predication, where `Ax` is\n * genuinely both `∀x` and A-applied-to-x; there, juxtaposition has to be a\n * parser behavior (`@syntax juxtaposed`), as it is for Magnus.\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, Scope } from \"./scan.js\";\n\nconst NO_SCOPE: Scope = new Map();\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 scope: Scope,\n): { captured: Captured; end: number } | null {\n const point = lang.scanner.at(text, position, scope);\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 scope: Scope,\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, scope);\n\n // A literal matches the *chunk*, declared vocabulary or not. Elab\n // exists to accept surface forms the MM0 grammar rejects — the Quine\n // rule makes `(x)` mean something no declaration mentions — so\n // constraining its pieces to declared tokens would be a half-measure\n // with nothing behind it. Anchoring is unaffected: the chunk's\n // boundaries were fixed by the delimiters before any lookup.\n //\n // A chunk the enclosing theorem *binds* is the one exception. Elab is\n // a surface convenience the engine knows nothing about — Calgary's\n // `A x` for `∀ x` is not a spelling of anything inside a math string —\n // so a binder named `A` displaces it exactly as it displaces the\n // lexicon's `A`, and for the same reason: inside that theorem, `A` is\n // the metavariable and nothing else. Without this a bound name is\n // eaten before it is ever classified, and the scope never gets a say.\n if (point.chunk !== element.token || scope.has(point.chunk)) {\n return null;\n }\n\n at = point.start + point.chunk.length;\n continue;\n }\n\n const taken: Captured[] = [];\n const first = matchCapture(lang, text, at, element.class, scope);\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, scope);\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, scope);\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 scope: Scope,\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, scope);\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, scope);\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(\n lang: SurfaceLanguage,\n text: string,\n scope: Scope = NO_SCOPE,\n): 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 scope,\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 *\n * No scope, deliberately. Engine mode does not delaborate — it is the whole\n * output path a schematic theorem's text takes — so threading one here\n * would buy nothing today and cost `printTerm` a parameter. A display\n * printer that has to re-sugar a metavariable correctly is the point at\n * which to add it.\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 NO_SCOPE,\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"]}
|
|
1
|
+
{"version":3,"file":"elab.js","sourceRoot":"","sources":["../src/elab.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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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,EACF,QAAQ,CACT,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 chunk 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 as tight as the delimiters allow (a space only\n * at a seam that would otherwise run two chunks together, as the printer\n * does), 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. A\n * literal matches a whole chunk, which need not be declared vocabulary at\n * all: the layer exists to accept surface forms the MM0 grammar rejects.\n * It is deliberately regular — nesting facts belong to the parser.\n *\n * **The three commitments.** What an author has to reason about is that\n * this layer decides, and the parser then inherits the decision as fact —\n * the parser backtracks over ambiguity, but only over what reaches it.\n *\n * - *Leftmost*: the first match at the earliest scan point wins, and the\n * span it consumed is replaced and never re-examined.\n * - *Greedy*: a `+` capture takes the maximum it can and never gives one\n * back to let the rest of the pattern match.\n * - *One sweep per rule*, in declaration order, so a later rule sees\n * what earlier rules emitted, and never the other way round.\n *\n * The hazard those three add up to: a rule may eat a span that had another\n * reading. Prefer patterns anchored by a leading literal — a spelling the\n * author chose — over capture-initial ones, which fire wherever the sorts\n * line up. The dialect where even that is not enough is one with both\n * letter-spelled quantifiers and juxtaposed predication, where `Ax` is\n * genuinely both `∀x` and A-applied-to-x; there, juxtaposition has to be a\n * parser behavior (`@syntax juxtaposed`), as it is for Magnus.\n */\n\nimport { adjoin, type DelimiterRules } from \"./delimiters.js\";\nimport type { SurfaceLanguage } from \"./parse.js\";\nimport type {\n ElabRule,\n RuleCapture,\n RuleLiteral,\n RuleTemplateElement,\n} from \"./reader/annotations.js\";\nimport type { Reading, Scope } from \"./scan.js\";\n\nconst NO_SCOPE: Scope = new Map();\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 scope: Scope,\n): { captured: Captured; end: number } | null {\n const point = lang.scanner.at(text, position, scope);\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 scope: Scope,\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, scope);\n\n // A literal matches the *chunk*, declared vocabulary or not. Elab\n // exists to accept surface forms the MM0 grammar rejects — the Quine\n // rule makes `(x)` mean something no declaration mentions — so\n // constraining its pieces to declared tokens would be a half-measure\n // with nothing behind it. Anchoring is unaffected: the chunk's\n // boundaries were fixed by the delimiters before any lookup.\n //\n // A chunk the enclosing theorem *binds* is the one exception. Elab is\n // a surface convenience the engine knows nothing about — Calgary's\n // `A x` for `∀ x` is not a spelling of anything inside a math string —\n // so a binder named `A` displaces it exactly as it displaces the\n // lexicon's `A`, and for the same reason: inside that theorem, `A` is\n // the metavariable and nothing else. Without this a bound name is\n // eaten before it is ever classified, and the scope never gets a say.\n if (point.chunk !== element.token || scope.has(point.chunk)) {\n return null;\n }\n\n at = point.start + point.chunk.length;\n continue;\n }\n\n const taken: Captured[] = [];\n const first = matchCapture(lang, text, at, element.class, scope);\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, scope);\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, scope);\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 rules: DelimiterRules,\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 && needsSpace(text, piece.text, separator, rules)) {\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/**\n * Whether `right` needs a space after `left`: always when spaced, and when\n * tight only where the two would otherwise run together — see\n * {@link adjoin}.\n */\nfunction needsSpace(\n left: string,\n right: string,\n separator: \" \" | \"\",\n rules: DelimiterRules,\n): boolean {\n if (separator === \" \") {\n return true;\n }\n\n return adjoin(left, right, rules).length > left.length + right.length;\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 scope: Scope,\n): Elaborated {\n // A literal matches a whole chunk, and a chunk is a slice of the text, so\n // a rule with a literal the text does not contain cannot match anywhere.\n // A pass that matches nothing returns its input unchanged, so skipping it\n // is exact — and it makes the many rules a given text cannot use (UBC's\n // two hundred subscripts) nearly free.\n if (\n pattern.some(\n (element) =>\n element.kind === \"literal\" && !text.includes(element.token),\n )\n ) {\n return { text, origin };\n }\n\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 // Set after a replacement: the seams on either side of emitted text are\n // new, and tight output checks them. Copied text meets copied text at a\n // seam the source already had, which reads as it did.\n let fresh = false;\n\n // A seam in tight output that would run two chunks together gets a\n // space, attributed to the character after it.\n const seam = (next: string, at: number): void => {\n if (\n fresh &&\n separator === \"\" &&\n needsSpace(out, next, separator, lang.scanner.rules)\n ) {\n out += \" \";\n outOrigin.push(at);\n }\n };\n\n const copy = (from: number, to: number): void => {\n const end = Math.min(to, text.length);\n\n if (end <= from) {\n return;\n }\n\n seam(text.slice(from, end), originOf(from));\n fresh = false;\n\n for (let i = from; i < end; 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, scope);\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, scope);\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 lang.scanner.rules,\n );\n\n fresh = true;\n seam(emitted.text, emitted.origin[0] ?? originOf(point.start));\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(\n lang: SurfaceLanguage,\n text: string,\n scope: Scope = NO_SCOPE,\n): 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 scope,\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 *\n * No scope, deliberately. Engine mode does not delaborate — it is the whole\n * output path a schematic theorem's text takes — so threading one here\n * would buy nothing today and cost `printTerm` a parameter. A display\n * printer that has to re-sugar a metavariable correctly is the point at\n * which to add it.\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 NO_SCOPE,\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
|
@@ -4,15 +4,15 @@
|
|
|
4
4
|
* The public API grows stage by stage; see the README for the layer stack.
|
|
5
5
|
*/
|
|
6
6
|
export type { DelimiterRules, DelimiterSet } from "./delimiters.js";
|
|
7
|
-
export { chunkAt, delimiterRules, isReachableChunk, segment, } from "./delimiters.js";
|
|
7
|
+
export { adjoin, chunkAt, delimiterRules, isReachableChunk, segment, } from "./delimiters.js";
|
|
8
8
|
export type { Diagnostic, Severity, Span } from "./diagnostics.js";
|
|
9
9
|
export { boundVariableBinders, stripSyntaxAnnotations } from "./engine.js";
|
|
10
10
|
export type { ParseFailure, ParseMode, ParseResult, ParseSuccess, } from "./parse.js";
|
|
11
11
|
export { SurfaceLanguage } from "./parse.js";
|
|
12
12
|
export type { PrintMode } from "./print.js";
|
|
13
|
-
export { printTerm } from "./print.js";
|
|
13
|
+
export { printTerm, UnprintableTermError } from "./print.js";
|
|
14
14
|
export type { ElabRule, LintName, OperandRelation, RuleCapture, RuleLiteral, RulePatternElement, RuleReference, RuleTemplateElement, SyntaxAnnotation, } from "./reader/annotations.js";
|
|
15
|
-
export type { CoercionInfo, NotationInfo, SortInfo, Spec, SpecParse, TermInfo, } from "./reader/spec.js";
|
|
15
|
+
export type { CoercionInfo, Definition, NotationInfo, RuleInfo, SortInfo, Spec, SpecParse, TermInfo, } from "./reader/spec.js";
|
|
16
16
|
export { parseSpec } from "./reader/spec.js";
|
|
17
17
|
export type { Annotation, AssertStatement, Binder, CoercionStatement, DefStatement, DelimiterStatement, GenNotationStatement, MathString, NotationLiteral, Precedence, SimpleNotationStatement, SortStatement, Statement, StatementParse, TermStatement, TypeRef, } from "./reader/statements.js";
|
|
18
18
|
export { parseStatements } from "./reader/statements.js";
|
|
@@ -20,5 +20,6 @@ export type { Reading, ScanPoint, Scope } from "./scan.js";
|
|
|
20
20
|
export { Scanner } from "./scan.js";
|
|
21
21
|
export type { AppTerm, Fixity, Term, VariableTerm } from "./term.js";
|
|
22
22
|
export { walkTerm } from "./term.js";
|
|
23
|
+
export { unfoldDefinitions } from "./unfold.js";
|
|
23
24
|
export type { NameRef, Vocabulary } from "./vocabulary.js";
|
|
24
25
|
export { surfaceVocabulary } from "./vocabulary.js";
|
package/dist/index.js
CHANGED
|
@@ -3,13 +3,14 @@
|
|
|
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
|
+
export { adjoin, chunkAt, delimiterRules, isReachableChunk, segment, } from "./delimiters.js";
|
|
7
7
|
export { boundVariableBinders, stripSyntaxAnnotations } from "./engine.js";
|
|
8
8
|
export { SurfaceLanguage } from "./parse.js";
|
|
9
|
-
export { printTerm } from "./print.js";
|
|
9
|
+
export { printTerm, UnprintableTermError } from "./print.js";
|
|
10
10
|
export { parseSpec } from "./reader/spec.js";
|
|
11
11
|
export { parseStatements } from "./reader/statements.js";
|
|
12
12
|
export { Scanner } from "./scan.js";
|
|
13
13
|
export { walkTerm } from "./term.js";
|
|
14
|
+
export { unfoldDefinitions } from "./unfold.js";
|
|
14
15
|
export { surfaceVocabulary } from "./vocabulary.js";
|
|
15
16
|
//# 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,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;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EACL,MAAM,EACN,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,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAsB7D,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;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,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 adjoin,\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, UnprintableTermError } from \"./print.js\";\nexport type {\n ElabRule,\n LintName,\n OperandRelation,\n RuleCapture,\n RuleLiteral,\n RulePatternElement,\n RuleReference,\n RuleTemplateElement,\n SyntaxAnnotation,\n} from \"./reader/annotations.js\";\nexport type {\n CoercionInfo,\n Definition,\n NotationInfo,\n RuleInfo,\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, Scope } from \"./scan.js\";\nexport { Scanner } from \"./scan.js\";\nexport type { AppTerm, Fixity, Term, VariableTerm } from \"./term.js\";\nexport { walkTerm } from \"./term.js\";\nexport { unfoldDefinitions } from \"./unfold.js\";\nexport type { NameRef, Vocabulary } from \"./vocabulary.js\";\nexport { surfaceVocabulary } from \"./vocabulary.js\";\n"]}
|
package/dist/parse.d.ts
CHANGED
|
@@ -18,12 +18,14 @@
|
|
|
18
18
|
* 4. **Lints** — the closed set of post-parse checks
|
|
19
19
|
* (`parenthesize-binary-only`, `closed-sentences`).
|
|
20
20
|
*
|
|
21
|
-
*
|
|
22
|
-
* (
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
21
|
+
* Constructor application is MM0's own production, `expression(1024) →
|
|
22
|
+
* FUNC expression(max){n}` — `S x`, `pair a b`, `succ (succ x)` — with
|
|
23
|
+
* two surface-side supersets in front of it: a lexicon name applied to
|
|
24
|
+
* bracketed arguments (`S(x)`, `R(a,b)`), or elided-bare, or glued to
|
|
25
|
+
* juxtaposed arguments, counts as `expression(max)`, so a textbook's
|
|
26
|
+
* `F(a)` can sit anywhere an atom can. A token that is both a notation
|
|
27
|
+
* and a lexicon name (Calgary's `A`) is disambiguated by backtracking,
|
|
28
|
+
* notation reading first.
|
|
27
29
|
*
|
|
28
30
|
* mm0.md's slot-precedence rules are used exactly: a prefix notation's
|
|
29
31
|
* intermediate arguments parse at max and its last at the notation's
|
|
@@ -37,6 +39,7 @@ import type { NotationInfo, Spec, TermInfo } from "./reader/spec.js";
|
|
|
37
39
|
import type { Binder } from "./reader/statements.js";
|
|
38
40
|
import { Scanner, type Scope } from "./scan.js";
|
|
39
41
|
import type { Term } from "./term.js";
|
|
42
|
+
export declare function precNum(prec: number | "max"): number;
|
|
40
43
|
interface PrefixEntry {
|
|
41
44
|
readonly kind: "prefix";
|
|
42
45
|
readonly info: TermInfo;
|
|
@@ -48,23 +51,34 @@ interface InfixEntry {
|
|
|
48
51
|
readonly prec: number;
|
|
49
52
|
readonly fixity: "infixl" | "infixr";
|
|
50
53
|
}
|
|
51
|
-
interface GeneralSlot {
|
|
54
|
+
export interface GeneralSlot {
|
|
52
55
|
readonly binder: Binder;
|
|
53
56
|
/** Index into the term's binder list this slot fills. */
|
|
54
57
|
readonly index: number;
|
|
55
58
|
readonly prec: number;
|
|
56
59
|
}
|
|
60
|
+
export type GeneralPart = {
|
|
61
|
+
readonly kind: "constant";
|
|
62
|
+
readonly token: string;
|
|
63
|
+
} | {
|
|
64
|
+
readonly kind: "slot";
|
|
65
|
+
readonly slot: GeneralSlot;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* A general notation after its head, as the parser reads it: constants to
|
|
69
|
+
* expect and slots to parse, each slot at mm0.md's P(lits, q) — max before
|
|
70
|
+
* a variable, p+1 before a constant of precedence p, and q (the head
|
|
71
|
+
* precedence) when it is the trailing slot. The printer reads the same
|
|
72
|
+
* table, so what it decides needs no parentheses is what this parses.
|
|
73
|
+
*/
|
|
74
|
+
export declare function generalParts(notation: NotationInfo & {
|
|
75
|
+
readonly form: "general";
|
|
76
|
+
}, headPrec: number | "max"): readonly GeneralPart[];
|
|
57
77
|
interface GeneralEntry {
|
|
58
78
|
readonly kind: "general";
|
|
59
79
|
readonly info: TermInfo;
|
|
60
80
|
/** Interleaved constants (to expect) and slots (to parse), head dropped. */
|
|
61
|
-
readonly parts: readonly
|
|
62
|
-
readonly kind: "constant";
|
|
63
|
-
readonly token: string;
|
|
64
|
-
} | {
|
|
65
|
-
readonly kind: "slot";
|
|
66
|
-
readonly slot: GeneralSlot;
|
|
67
|
-
})[];
|
|
81
|
+
readonly parts: readonly GeneralPart[];
|
|
68
82
|
}
|
|
69
83
|
type HeadEntry = GeneralEntry | PrefixEntry;
|
|
70
84
|
export interface ParseSuccess {
|