@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/dist/print.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"print.js","sourceRoot":"","sources":["../src/print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAMvC,MAAM,UAAU,SAAS,CACvB,IAAqB,EACrB,IAAU,EACV,OAAkB,SAAS;IAE3B,IAAI,OAAO,GAAG,MAAM,CAAC,IAAI,EAAE,IAA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AC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAED,4EAA4E;AAC5E,SAAS,OAAO,CACd,IAAqB,EACrB,IAAsB,EACtB,IAAe;IAEf,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAE1C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,sEAAsE;QACtE,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,uEAAuE;IACvE,gDAAgD;IAChD,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACrC,MAAM,IAAI,GACR,MAAM,CAAC,IAAI,KAAK,UAAU;QAC1B,CAAC,MAAM,CAAC,IAAI,KAAK,KAAK;YACpB,MAAM,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC;YACxB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC;QAChD,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAE3B,OAAO,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,QAAQ,GAAG,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * The printer: a term tree back to text, in one of two modes.\n *\n * **Display** is what a reader sees, in the textbook's own conventions:\n * the canonical spelling of each constructor (the last-declared notation,\n * Aufbau's rule), *full* parenthesization of sentential connectives with\n * the outermost pair optionally dropped (`@syntax display\n * drop-outer-parens`) — Carnap's convention, not minimal-parens — spaces\n * around connectives, everything else set tight (`¬P`, `∀x`, `a=b`,\n * `R(a,b)`).\n *\n * **Engine** is what the Aufbau compiler's own math parser reads: the same\n * canonical spellings, every token whitespace-separated, every compound\n * operand parenthesized, and coercion wrappers omitted (the engine\n * re-inserts them). Lexicon names print as constructor application —\n * `F ((x , y))`, `P (snil)` — which is valid at any slot once\n * parenthesized, and elided arguments are written out in full.\n *\n * Display mode presumes the spec's term-level infixes (identity, argument\n * commas) bind tighter than its prefixes, as every textbook's do; a spec\n * violating that should print through engine mode. The round-trip law —\n * parsing a printed term yields the same tree — is enforced by test for\n * both modes.\n */\n\nimport { delaborate } from \"./elab.js\";\nimport type { SurfaceLanguage } from \"./parse.js\";\nimport type { Term } from \"./term.js\";\n\nexport type PrintMode = \"display\" | \"engine\";\n\nexport function printTerm(\n lang: SurfaceLanguage,\n term: Term,\n mode: PrintMode = \"display\",\n): string {\n let printed = render(lang, term, mode);\n\n if (\n mode === \"display\" &&\n lang.spec.display.dropOuterParens &&\n printed.startsWith(\"(\") &&\n printed.endsWith(\")\")\n ) {\n printed = printed.slice(1, -1);\n }\n\n if (mode === \"display\" && lang.spec.elabRules.length > 0) {\n printed = delaborate(lang, printed);\n }\n\n return printed;\n}\n\nfunction render(lang: SurfaceLanguage, term: Term, mode: PrintMode): string {\n if (term.kind === \"variable\") {\n return term.name;\n }\n\n // Coercions are the parser's bookkeeping; both readers re-derive them.\n if (term.args.length === 1 && lang.coercionNames.has(term.term)) {\n const inner = term.args[0];\n\n if (inner !== undefined) {\n return render(lang, inner, mode);\n }\n }\n\n const notation = lang.canonical.get(term.term);\n\n if (notation === undefined) {\n return renderApplication(lang, term, mode);\n }\n\n if (notation.form === \"simple\" && notation.fixity !== \"prefix\") {\n const left = operand(lang, term.args[0], mode);\n const right = operand(lang, term.args[1], mode);\n\n if (mode === \"engine\") {\n return `(${left} ${notation.token} ${right})`;\n }\n\n const connective = lang.isConnective(term.term);\n\n // A juxtaposed combiner displays as nothing when it can: `abc` for\n // `mul(mul(a,b),c)`. An operand is parenthesized when its own\n // printed form rebinds below what its slot re-parses at — which\n // covers nesting against the associativity (`a*(bc)`) and, just as\n // fatally, a loose prefix whose body would swallow what follows\n // (`(λxx)·y`, where bare `λxxy` reads the `y` into the body). Then\n // the pieces glue when both can, and the visible token steps back in\n // when either cannot; either way the display form reparses to the\n // same tree. A *connective* combiner is left to the full-paren\n // convention below, which is already stable; invisibly glued\n // formulas would be unreadable anyway.\n if (!connective && lang.spec.terms.get(term.term)?.juxtaposed === true) {\n const prec = typeof notation.prec === \"number\" ? notation.prec : 0;\n const slot = (piece: string, arg: Term | undefined, at: number) =>\n arg !== undefined && printedPrec(lang, arg) < at\n ? `(${piece})`\n : piece;\n const l = slot(\n left,\n term.args[0],\n notation.fixity === \"infixl\" ? prec : prec + 1,\n );\n const r = slot(\n right,\n term.args[1],\n notation.fixity === \"infixl\" ? prec + 1 : prec,\n );\n\n return glueablePiece(lang, l) && glueablePiece(lang, r)\n ? `${l}${r}`\n : `${l}${notation.token}${r}`;\n }\n\n // Connectives are spaced and self-parenthesized (the full-paren\n // convention); term-level infixes close up and stand bare.\n return connective\n ? `(${left} ${notation.token} ${right})`\n : `${left}${notation.token}${right}`;\n }\n\n if (notation.form === \"simple\") {\n const args = term.args.map((arg) => operand(lang, arg, mode));\n\n return mode === \"engine\"\n ? `(${[notation.token, ...args].join(\" \")})`\n : `${notation.token}${args.join(\"\")}`;\n }\n\n // General notation: constants and binder slots, in literal order.\n const pieces: string[] = [];\n\n for (const literal of notation.literals) {\n if (literal.kind === \"constant\") {\n pieces.push(literal.token);\n continue;\n }\n\n const index = notation.binders.findIndex(\n (binder) => binder.name === literal.name,\n );\n const arg = term.args[index];\n\n if (arg !== undefined) {\n pieces.push(operand(lang, arg, mode));\n }\n }\n\n if (mode === \"engine\") {\n return term.args.length === 0\n ? pieces.join(\" \")\n : `(${pieces.join(\" \")})`;\n }\n\n return pieces.join(\"\");\n}\n\n/**\n * A term with no notation prints as application — the lexicon's shape.\n * Display elides an `@syntax elided` argument (bare `P`), flattens a\n * juxtaposed argument into glued leaves (`Rxy`), and otherwise sets each\n * argument in its own parentheses (`R(a,b)`, the comma coming from the\n * argument's own notation). Engine mode writes application in full —\n * `P (snil)`, `R ((x , y))` — which the compiler reads at expression(max).\n */\nfunction renderApplication(\n lang: SurfaceLanguage,\n term: Term & { kind: \"app\" },\n mode: PrintMode,\n): string {\n if (term.args.length === 0) {\n return term.term;\n }\n\n if (mode === \"engine\") {\n const args = term.args.map((arg) => {\n const rendered = render(lang, arg, mode);\n\n return rendered.startsWith(\"(\") ? rendered : `(${rendered})`;\n });\n\n return [term.term, ...args].join(\" \");\n }\n\n const sole = term.args.length === 1 ? term.args[0] : undefined;\n\n if (sole !== undefined) {\n const bare = uncoerced(lang, sole);\n const elided = lang.elidedOf.get(sole.sort);\n\n if (\n elided !== undefined &&\n bare.kind === \"app\" &&\n bare.term === elided.name\n ) {\n return term.term;\n }\n\n const combiner = lang.juxtaposedOf.get(sole.sort);\n\n if (combiner !== undefined) {\n const leaves: string[] = [];\n const flatten = (node: Term): void => {\n const at = uncoerced(lang, node);\n\n if (at.kind === \"app\" && at.term === combiner.name) {\n for (const inner of at.args) {\n flatten(inner);\n }\n\n return;\n }\n\n leaves.push(render(lang, at, mode));\n };\n\n flatten(sole);\n\n // Glue only when every leaf is itself glueable — a single token the\n // parser would consume back. A compound element falls back to the\n // parenthesized form.\n const simple = leaves.every((leaf) => glueablePiece(lang, leaf));\n\n if (simple) {\n return `${term.term}${leaves.join(\"\")}`;\n }\n }\n }\n\n const args = term.args\n .map((arg) => `(${render(lang, arg, mode)})`)\n .join(\"\");\n\n return `${term.term}${args}`;\n}\n\n/**\n * The precedence at which a term's display form rebinds when it is\n * re-parsed: its canonical notation's, or the general notation's head\n * precedence. Self-delimiting forms — variables, lexicon names (which\n * print as `F(x)`-style application), and connectives (which print\n * self-parenthesized) — never rebind, and answer infinity.\n */\nfunction printedPrec(lang: SurfaceLanguage, term: Term): number {\n const bare = uncoerced(lang, term);\n\n if (bare.kind === \"variable\") {\n return Number.POSITIVE_INFINITY;\n }\n\n const notation = lang.canonical.get(bare.term);\n\n if (notation === undefined || lang.isConnective(bare.term)) {\n return Number.POSITIVE_INFINITY;\n }\n\n const prec =\n notation.form === \"general\"\n ? notation.literals[0]?.kind === \"constant\"\n ? notation.literals[0].prec\n : \"max\"\n : notation.prec;\n\n return prec === \"max\" ? Number.POSITIVE_INFINITY : prec;\n}\n\n/**\n * Whether a printed piece can stand glued against another: no whitespace\n * and no brackets, so the delimiters re-cut the concatenation into the\n * same chunks the pieces were printed from.\n */\nfunction glueablePiece(lang: SurfaceLanguage, piece: string): boolean {\n return (\n !/\\s/.test(piece) &&\n !lang.spec.groupingPairs.flat().some((g) => piece.includes(g))\n );\n}\n\n/** The term with any coercion wrappers peeled off — what actually prints. */\nfunction uncoerced(lang: SurfaceLanguage, term: Term): Term {\n let at = term;\n\n while (\n at.kind === \"app\" &&\n at.args.length === 1 &&\n lang.coercionNames.has(at.term)\n ) {\n const inner = at.args[0];\n\n if (inner === undefined) {\n break;\n }\n\n at = inner;\n }\n\n return at;\n}\n\n/** An argument position: parenthesize what would not survive re-parsing. */\nfunction operand(\n lang: SurfaceLanguage,\n term: Term | undefined,\n mode: PrintMode,\n): string {\n if (term === undefined) {\n return \"\";\n }\n\n const rendered = render(lang, term, mode);\n\n if (mode === \"display\") {\n // Connectives arrive self-parenthesized; everything else stands bare.\n return rendered;\n }\n\n // Engine mode: any unparenthesized compound gets parentheses, so every\n // operand is expression(max) and fits any slot.\n const bearer = uncoerced(lang, term);\n const bare =\n bearer.kind === \"variable\" ||\n (bearer.kind === \"app\" &&\n bearer.args.length === 0 &&\n lang.canonical.get(bearer.term) === undefined) ||\n rendered.startsWith(\"(\");\n\n return bare ? rendered : `(${rendered})`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"print.js","sourceRoot":"","sources":["../src/print.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,OAAO,EAAE,MAAM,EAAuB,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAwB,MAAM,YAAY,CAAC;AAKz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AG,CAAC,EAAE,CAAC,IAAI,CAAC,EAC/B,CAAC;QACD,MAAM,KAAK,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAEzB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,MAAM;QACR,CAAC;QAED,EAAE,GAAG,KAAK,CAAC;IACb,CAAC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["/**\n * The printer: a term tree back to text, in one of two modes.\n *\n * **Display** is what a reader sees, in the textbook's own conventions:\n * the canonical spelling of each constructor (the last-declared notation,\n * Aufbau's rule), *full* parenthesization of sentential connectives with\n * the outermost pair optionally dropped (`@syntax display\n * drop-outer-parens`) — Carnap's convention, not minimal-parens. A formula\n * is outermost wherever the sort changes above it, not only at the top:\n * `𝕋 A ∧ B`, `A ∧ B ⊢ C`. Connectives are spaced, and so is a notation\n * that takes its operands to another sort (`a = b`, `𝕋 A`); everything\n * else is set tight (`¬P`, `∀x`, `R(a,b)`). A notation token declared a\n * delimiter on one side only hugs that side and stands off the other, so\n * a right-only `,` writes `a, b`.\n *\n * **Engine** is what the Aufbau compiler's own math parser reads: the same\n * canonical spellings, every token whitespace-separated, every compound\n * operand parenthesized, and coercion wrappers omitted (the engine\n * re-inserts them). Lexicon names print as constructor application —\n * `F ((x , y))`, `P (snil)` — which is valid at any slot once\n * parenthesized, and elided arguments are written out in full.\n *\n * Parentheses beyond the connectives' own are exactly the ones the parser\n * needs, decided from its own precedence tables: a piece stands bare in a\n * slot when its head binds at least as tight as the slot reads, and when\n * nothing on its right edge would swallow the operator after it — the\n * `(λx.x)·y` that bare would read the `y` into the body. So `1 + 0 * 0`\n * prints as such, and `(1 + 0) * 0` keeps its pair.\n *\n * The round-trip law — parsing a printed term, in the same mode, yields\n * the same tree — holds for every term, and is enforced by test over\n * generated terms in both modes. Its segmentation half is structural:\n * every seam between two printed pieces goes through {@link adjoin},\n * which sets them tight only where the reader's delimiters would cut\n * there anyway, and spaces them where it would not. \"Tight\" is the\n * display convention, not a promise — under a spec with no letter\n * delimiters `∀x Cube(x)` keeps its space, because `∀xCube(x)` would read\n * `xCube` as one chunk.\n */\n\nimport { adjoin, type DelimiterRules } from \"./delimiters.js\";\nimport { delaborate } from \"./elab.js\";\nimport { generalParts, precNum, type SurfaceLanguage } from \"./parse.js\";\nimport type { Term } from \"./term.js\";\n\nexport type PrintMode = \"display\" | \"engine\";\n\n/**\n * A term display text cannot spell. The one such term is an `@syntax\n * elided` term standing anywhere but where the reader supplies it —\n * `R(snil,a)` — which has no surface spelling at all: written by name it\n * either fails to read (`snil` is four letters to Calgary) or, worse,\n * reads as something else (Magnus glues the letters into arguments). The\n * printer refuses rather than write text that does not read back as the\n * term. Engine text can always spell it, by name.\n */\nexport class UnprintableTermError extends Error {\n readonly term: string;\n\n constructor(term: string) {\n super(\n `${term} is elided wherever it is read, so display text has no way to write it here`,\n );\n this.name = \"UnprintableTermError\";\n this.term = term;\n }\n}\n\n/**\n * `term` as text in `mode`, which parses back in the same mode to the same\n * term. Display mode throws {@link UnprintableTermError} for the one shape\n * it cannot spell; engine mode is total.\n */\nexport function printTerm(\n lang: SurfaceLanguage,\n term: Term,\n mode: PrintMode = \"display\",\n): string {\n const printer: Printer = {\n lang,\n mode,\n // Each mode is read back by its own scanner, so each is set against\n // that scanner's delimiters: the surface set for display, the\n // theory's own for engine text (where `(a)` is one chunk to a theory\n // that never declares `(`).\n rules: mode === \"display\" ? lang.scanner.rules : lang.engineScanner.rules,\n };\n if (mode === \"engine\") {\n return engine(printer, term);\n }\n\n const printed = display(printer, term, lang.spec.display.dropOuterParens);\n\n return lang.spec.elabRules.length > 0\n ? delaborate(lang, printed.text)\n : printed.text;\n}\n\ninterface Printer {\n readonly lang: SurfaceLanguage;\n readonly mode: PrintMode;\n readonly rules: DelimiterRules;\n}\n\n/** Pieces set as tight as the reader's delimiters allow. */\nfunction tight(printer: Printer, ...pieces: readonly string[]): string {\n return pieces.reduce((left, right) => adjoin(left, right, printer.rules));\n}\n\n/** Pieces set one space apart — always safe, and the connective style. */\nfunction spaced(...pieces: readonly string[]): string {\n return pieces.filter((piece) => piece.length > 0).join(\" \");\n}\n\n/** One piece of a display notation: an operand's text, or its own token. */\ninterface Piece {\n readonly text: string;\n readonly token: boolean;\n}\n\nfunction operand(text: string): Piece {\n return { text, token: false };\n}\n\nfunction token(text: string): Piece {\n return { text, token: true };\n}\n\n/**\n * A display notation's pieces in order, its seams spaced when `apart` and\n * otherwise as tight as the delimiters allow. A token the surface\n * delimiters list on one side only decides its own seams instead: a\n * right-only token breaks before itself, so it hugs what precedes it and\n * stands off what follows (`a, b`); a left-only one is the mirror. That is\n * the declaration read as layout, and it holds in a spec whose letters are\n * delimiters too, where `a,b` would read back just as well.\n */\nfunction setPieces(\n printer: Printer,\n pieces: readonly Piece[],\n apart: boolean,\n): string {\n let text = \"\";\n let previous: Piece | null = null;\n\n for (const piece of pieces) {\n if (piece.text.length === 0) {\n continue;\n }\n\n if (previous === null) {\n text = piece.text;\n previous = piece;\n continue;\n }\n\n const after = previous.token ? oneSide(printer, previous.text) : null;\n const before = piece.token ? oneSide(printer, piece.text) : null;\n const space =\n after === \"right\" || before === \"left\"\n ? true\n : after === \"left\" || before === \"right\"\n ? false\n : apart;\n\n // A space never joins two chunks, so only the tight seam needs adjoin.\n text = space\n ? `${text} ${piece.text}`\n : adjoin(text, piece.text, printer.rules);\n previous = piece;\n }\n\n return text;\n}\n\n/** The one side `text` is a delimiter on, or null for both or neither. */\nfunction oneSide(printer: Printer, text: string): \"left\" | \"right\" | null {\n const left = printer.rules.left.has(text);\n const right = printer.rules.right.includes(text);\n\n return left === right ? null : left ? \"left\" : \"right\";\n}\n\n/** A piece in the built-in grouping pair. */\nfunction grouped(printer: Printer, inner: string): string {\n return tight(printer, \"(\", inner, \")\");\n}\n\n// ── engine text ──────────────────────────────────────────────────────\n\nfunction engine(printer: Printer, term: Term): string {\n const { lang } = printer;\n\n if (term.kind === \"variable\") {\n return term.name;\n }\n\n // Coercions are the parser's bookkeeping; the engine re-derives them.\n const inner = coerced(lang, term);\n\n if (inner !== null) {\n return engine(printer, inner);\n }\n\n const notation = lang.canonical.get(term.term);\n\n // A term with no notation is written as application in full —\n // `P (snil)`, `R ((x , y))` — which the compiler reads at\n // expression(max).\n if (notation === undefined) {\n if (term.args.length === 0) {\n return term.term;\n }\n\n const binders = lang.spec.terms.get(term.term)?.binders ?? [];\n const args = term.args.map((arg, at) => {\n const rendered = engine(printer, arg);\n\n // A bound binder's argument is a variable and must stand bare: the\n // engine wants a name in that slot, not a group around one.\n if (binders[at]?.binds === true) {\n return rendered;\n }\n\n return rendered.startsWith(\"(\") ? rendered : grouped(printer, rendered);\n });\n\n return spaced(term.term, ...args);\n }\n\n if (notation.form === \"simple\") {\n const args = term.args.map((arg) => engineOperand(printer, arg));\n\n return notation.fixity === \"prefix\"\n ? grouped(printer, spaced(notation.token, ...args))\n : grouped(\n printer,\n spaced(args[0] ?? \"\", notation.token, args[1] ?? \"\"),\n );\n }\n\n // General notation: constants and binder slots, in literal order.\n const pieces = notation.literals.map((literal) => {\n if (literal.kind === \"constant\") {\n return literal.token;\n }\n\n const index = notation.binders.findIndex(\n (binder) => binder.name === literal.name,\n );\n\n return engineOperand(printer, term.args[index]);\n });\n\n return term.args.length === 0\n ? spaced(...pieces)\n : grouped(printer, spaced(...pieces));\n}\n\n/**\n * An engine operand: any unparenthesized compound gets parentheses, so\n * every operand is expression(max) and fits any slot.\n */\nfunction engineOperand(printer: Printer, term: Term | undefined): string {\n if (term === undefined) {\n return \"\";\n }\n\n const { lang } = printer;\n const rendered = engine(printer, term);\n const bearer = uncoerced(lang, term);\n const bare =\n bearer.kind === \"variable\" ||\n (bearer.kind === \"app\" &&\n bearer.args.length === 0 &&\n lang.canonical.get(bearer.term) === undefined) ||\n rendered.startsWith(\"(\");\n\n return bare ? rendered : grouped(printer, rendered);\n}\n\n// ── display ──────────────────────────────────────────────────────────\n\nconst TIGHTEST = Number.POSITIVE_INFINITY;\n\n/** mm0.md: bare constructor application is `expression(1024)`. */\nconst APPLICATION_PRECEDENCE = 1024;\n\n/**\n * A piece of display text, with the two facts about it its context needs,\n * both in the parser's own precedence numbers.\n */\ninterface Printed {\n readonly text: string;\n /** It stands bare in a slot read at `min` exactly when `head >= min`. */\n readonly head: number;\n /**\n * The loosest slot still open at its right edge: an operator of\n * precedence `o` written straight after it is read *into* it when\n * `o >= tail`. Infinite when the right edge is closed — a bracket, a\n * name, a constant.\n */\n readonly tail: number;\n}\n\nfunction atom(text: string): Printed {\n return { text, head: TIGHTEST, tail: TIGHTEST };\n}\n\n/**\n * A piece set in a slot the parser reads at `min`, with an operator of\n * precedence `next` (or nothing) written after it: bare when it re-reads\n * as itself there, parenthesized when it would not.\n */\nfunction fit(\n printer: Printer,\n piece: Printed,\n min: number,\n next: number | null,\n): Printed {\n return piece.head >= min && (next === null || next < piece.tail)\n ? piece\n : atom(grouped(printer, piece.text));\n}\n\n/**\n * `outer` is true, under `@syntax display drop-outer-parens`, for the whole\n * printed term and for a term the sort changes above ({@link outermost}):\n * the one pair a connective would wrap itself in is left off. Coercions\n * pass it through, since they print as what they wrap.\n */\nfunction display(printer: Printer, term: Term, outer = false): Printed {\n const { lang } = printer;\n\n if (term.kind === \"variable\") {\n return atom(term.name);\n }\n\n // Coercions are the parser's bookkeeping; the reader re-derives them.\n const inner = coerced(lang, term);\n\n if (inner !== null) {\n return display(printer, inner, outer);\n }\n\n const notation = lang.canonical.get(term.term);\n\n if (notation === undefined) {\n return displayApplication(printer, term);\n }\n\n const binders = lang.spec.terms.get(term.term)?.binders ?? [];\n\n if (notation.form === \"simple\" && notation.fixity !== \"prefix\") {\n const prec = precNum(notation.prec);\n const leftMin = notation.fixity === \"infixl\" ? prec : prec + 1;\n const rightMin = notation.fixity === \"infixl\" ? prec + 1 : prec;\n const connective = lang.isConnective(term.term);\n // A connective's operands are compounds of its own sort, which keep\n // their brackets under it: that is the full-paren convention.\n const outerAt = (at: number): boolean =>\n !connective && outermost(printer, term, term.args[at]);\n const left = fitArg(printer, term.args[0], leftMin, prec, outerAt(0));\n const right = fitArg(printer, term.args[1], rightMin, null, outerAt(1));\n const tail = Math.min(rightMin, right.tail);\n const pieces = [\n operand(left.text),\n token(notation.token),\n operand(right.text),\n ];\n\n // Connectives are spaced and self-parenthesized (the full-paren\n // convention), bar the outermost under drop-outer-parens.\n if (connective) {\n const text = setPieces(printer, pieces, true);\n\n return outer\n ? { text, head: prec, tail }\n : atom(grouped(printer, text));\n }\n\n // A juxtaposed combiner displays as nothing when both sides are\n // single glue operands: `abc` for `mul(mul(a,b),c)`. The adjacency\n // arc is its operator written invisibly, at the same precedence, so\n // the slots above hold for it too; a compound side (`a*(bc)`) brings\n // the visible token back.\n const glued =\n lang.spec.terms.get(term.term)?.juxtaposed === true &&\n glueablePiece(lang, left.text) &&\n glueablePiece(lang, right.text);\n const text = glued\n ? tight(printer, left.text, right.text)\n : setPieces(printer, pieces, changesSort(lang, term.term));\n\n return { text, head: prec, tail };\n }\n\n if (notation.form === \"simple\") {\n // mm0.md: a prefix notation's intermediate arguments read at max,\n // its last at the notation's own precedence.\n const prec = precNum(notation.prec);\n const pieces: Piece[] = [token(notation.token)];\n let tail = TIGHTEST;\n\n term.args.forEach((arg, at) => {\n if (binders[at]?.binds === true) {\n pieces.push(operand(display(printer, arg).text));\n tail = TIGHTEST;\n return;\n }\n\n const min = at === term.args.length - 1 ? prec : TIGHTEST;\n const piece = fit(\n printer,\n display(printer, arg, outermost(printer, term, arg)),\n min,\n null,\n );\n\n pieces.push(operand(piece.text));\n tail = Math.min(min, piece.tail);\n });\n\n return {\n text: setPieces(printer, pieces, changesSort(lang, term.term)),\n head: prec,\n tail,\n };\n }\n\n const first = notation.literals[0];\n\n if (first?.kind !== \"constant\") {\n return displayApplication(printer, term);\n }\n\n // General notation: the head, then the parser's own slots in order.\n const pieces: Piece[] = [token(first.token)];\n let tail = TIGHTEST;\n\n for (const part of generalParts(notation, first.prec)) {\n if (part.kind === \"constant\") {\n pieces.push(token(part.token));\n tail = TIGHTEST;\n continue;\n }\n\n const arg = term.args[part.slot.index];\n\n if (arg === undefined) {\n continue;\n }\n\n if (part.slot.binder.binds) {\n pieces.push(operand(display(printer, arg).text));\n tail = TIGHTEST;\n continue;\n }\n\n const piece = fit(\n printer,\n display(printer, arg, outermost(printer, term, arg)),\n part.slot.prec,\n null,\n );\n\n pieces.push(operand(piece.text));\n tail = Math.min(part.slot.prec, piece.tail);\n }\n\n return {\n text: setPieces(printer, pieces, changesSort(lang, term.term)),\n head: precNum(first.prec),\n tail,\n };\n}\n\nfunction fitArg(\n printer: Printer,\n arg: Term | undefined,\n min: number,\n next: number | null,\n outer: boolean,\n): Printed {\n return arg === undefined\n ? { text: \"\", head: TIGHTEST, tail: TIGHTEST }\n : fit(printer, display(printer, arg, outer), min, next);\n}\n\n/**\n * Whether `arg`, under `parent`, is the outermost formula of its sort:\n * under drop-outer-parens a connective leaves off its own pair wherever\n * the sort changes above it, as it does at the top — `𝕋 A ∧ B`, `A ∧ B ⊢\n * C`. Read through coercions, which change sort without printing. Safe\n * for the same reason the top is: {@link fit} still brackets a compound\n * that would not read back bare in its slot.\n */\nfunction outermost(\n printer: Printer,\n parent: Term & { kind: \"app\" },\n arg: Term | undefined,\n): boolean {\n return (\n arg !== undefined &&\n printer.lang.spec.display.dropOuterParens &&\n uncoerced(printer.lang, arg).sort !== parent.sort\n );\n}\n\n/**\n * Whether `name` takes its operands to another sort, returning none of\n * theirs: `=` from terms to a formula, `𝕋` from a formula to a row, `⊢`\n * from a context and a formula to a judgement. Its display is spaced, as\n * a connective's is; `¬`, `∀x` and `,` stay tight.\n */\nfunction changesSort(lang: SurfaceLanguage, name: string): boolean {\n const info = lang.spec.terms.get(name);\n\n if (info === undefined) {\n return false;\n }\n\n const sorts = info.binders\n .filter((binder) => !binder.binds)\n .map((binder) => (\"sort\" in binder.type ? binder.type.sort : \"\"));\n\n return sorts.length > 0 && !sorts.includes(info.returnSort);\n}\n\n/**\n * A term with no notation prints as application — the lexicon's shape.\n * Display elides an `@syntax elided` argument (bare `P`), flattens a\n * juxtaposed argument into glued leaves (`Rxy`), and otherwise sets each\n * argument in its own parentheses (`R(a,b)`, the comma coming from the\n * argument's own notation) — except a bound binder's variable, which the\n * reader takes bare (`sb x(t)(p)`), as MM0 application does.\n */\nfunction displayApplication(\n printer: Printer,\n term: Term & { kind: \"app\" },\n): Printed {\n const { lang } = printer;\n\n if (term.args.length === 0) {\n // Its one place is the sole argument of a name, which is elided\n // below before it ever gets here.\n if (lang.spec.terms.get(term.term)?.elided === true) {\n throw new UnprintableTermError(term.term);\n }\n\n return atom(term.term);\n }\n\n const sole = term.args.length === 1 ? term.args[0] : undefined;\n\n if (sole !== undefined) {\n const bare = uncoerced(lang, sole);\n const elided = lang.elidedOf.get(sole.sort);\n\n if (\n elided !== undefined &&\n bare.kind === \"app\" &&\n bare.term === elided.name\n ) {\n return atom(term.term);\n }\n\n const combiner = lang.juxtaposedOf.get(sole.sort);\n\n if (combiner !== undefined) {\n // The parser folds glued leaves to the left, so only a left-nested\n // tree flattens back into itself: `Rxyz` is `R((x,y),z)`, and a\n // right operand that is itself a combination keeps its brackets.\n const leaves: string[] = [];\n const flatten = (node: Term): boolean => {\n const at = uncoerced(lang, node);\n\n if (at.kind !== \"app\" || at.term !== combiner.name) {\n leaves.push(display(printer, at).text);\n return true;\n }\n\n const [left, right] = at.args;\n const last = right === undefined ? undefined : uncoerced(lang, right);\n\n if (\n left === undefined ||\n last === undefined ||\n (last.kind === \"app\" && last.term === combiner.name) ||\n !flatten(left)\n ) {\n return false;\n }\n\n leaves.push(display(printer, last).text);\n return true;\n };\n\n // Glue only when every leaf is itself glueable — a single token the\n // parser would consume back. A compound element falls back to the\n // parenthesized form.\n if (\n flatten(sole) &&\n leaves.every((leaf) => glueablePiece(lang, leaf))\n ) {\n return atom(tight(printer, term.term, ...leaves));\n }\n }\n }\n\n const binders = lang.spec.terms.get(term.term)?.binders ?? [];\n const binds = term.args.some((_, at) => binders[at]?.binds === true);\n const pieces = term.args.map((arg, at) =>\n binders[at]?.binds === true\n ? display(printer, arg).text\n : grouped(\n printer,\n display(printer, arg, outermost(printer, term, arg)).text,\n ),\n );\n\n // A name with a bound binder is read as bare application, which a\n // slot tighter than expression(1024) refuses.\n return {\n text: tight(printer, term.term, ...pieces),\n head: binds ? APPLICATION_PRECEDENCE : TIGHTEST,\n tail: TIGHTEST,\n };\n}\n\n/** The argument of a coercion node, or null when it is not one. */\nfunction coerced(\n lang: SurfaceLanguage,\n term: Term & { kind: \"app\" },\n): Term | null {\n return term.args.length === 1 && lang.coercionNames.has(term.term)\n ? (term.args[0] ?? null)\n : null;\n}\n\n/**\n * Whether a printed piece can stand as one glued element — one leaf of\n * `Rxy`, one factor of `abc`: no whitespace and no brackets, so it is a\n * single chunk the adjacency arc takes back whole. Where the seam falls\n * is {@link adjoin}'s business; this is only whether the piece is atomic.\n */\nfunction glueablePiece(lang: SurfaceLanguage, piece: string): boolean {\n return (\n !/\\s/.test(piece) &&\n !lang.spec.groupingPairs.flat().some((g) => piece.includes(g))\n );\n}\n\n/** The term with any coercion wrappers peeled off — what actually prints. */\nfunction uncoerced(lang: SurfaceLanguage, term: Term): Term {\n let at = term;\n\n while (\n at.kind === \"app\" &&\n at.args.length === 1 &&\n lang.coercionNames.has(at.term)\n ) {\n const inner = at.args[0];\n\n if (inner === undefined) {\n break;\n }\n\n at = inner;\n }\n\n return at;\n}\n"]}
|
|
@@ -14,7 +14,10 @@
|
|
|
14
14
|
* share one sort (adjacency of that sort's expressions denotes it);
|
|
15
15
|
* - `elided` attaches to a nullary term (supplied when an argument of
|
|
16
16
|
* its sort is missing, dropped again when printing);
|
|
17
|
-
* - `role` attaches to a `sort`, a `term`,
|
|
17
|
+
* - `role` attaches to a `sort`, a `term`, a `def`, an `axiom`, or a
|
|
18
|
+
* `theorem`;
|
|
19
|
+
* - `alias` attaches to an `axiom` or a `theorem` (the names a proof may
|
|
20
|
+
* cite it by, since the engine's identifiers are ASCII);
|
|
18
21
|
* - everything else is spec-wide and may sit on any statement.
|
|
19
22
|
*
|
|
20
23
|
* The lexicon itself needs no `@syntax` at all: letters are ordinary term
|
|
@@ -51,6 +54,16 @@ export interface ElabRule {
|
|
|
51
54
|
readonly template: readonly RuleTemplateElement[];
|
|
52
55
|
}
|
|
53
56
|
export type SyntaxAnnotation = {
|
|
57
|
+
/**
|
|
58
|
+
* `@syntax alias ∧I &I` — further names a proof may cite this rule
|
|
59
|
+
* by. MM0 identifiers are ASCII, so a textbook's `∧I` can never be
|
|
60
|
+
* the axiom's own name; the aliases are surface names for it, one
|
|
61
|
+
* whitespace-free token each, resolved by a consumer before the
|
|
62
|
+
* citation reaches the engine.
|
|
63
|
+
*/
|
|
64
|
+
readonly kind: "alias";
|
|
65
|
+
readonly names: readonly string[];
|
|
66
|
+
} | {
|
|
54
67
|
readonly kind: "brackets";
|
|
55
68
|
readonly pairs: readonly (readonly [string, string])[];
|
|
56
69
|
} | {
|
|
@@ -14,7 +14,10 @@
|
|
|
14
14
|
* share one sort (adjacency of that sort's expressions denotes it);
|
|
15
15
|
* - `elided` attaches to a nullary term (supplied when an argument of
|
|
16
16
|
* its sort is missing, dropped again when printing);
|
|
17
|
-
* - `role` attaches to a `sort`, a `term`,
|
|
17
|
+
* - `role` attaches to a `sort`, a `term`, a `def`, an `axiom`, or a
|
|
18
|
+
* `theorem`;
|
|
19
|
+
* - `alias` attaches to an `axiom` or a `theorem` (the names a proof may
|
|
20
|
+
* cite it by, since the engine's identifiers are ASCII);
|
|
18
21
|
* - everything else is spec-wide and may sit on any statement.
|
|
19
22
|
*
|
|
20
23
|
* The lexicon itself needs no `@syntax` at all: letters are ordinary term
|
|
@@ -44,6 +47,7 @@ const TEMPLATES = {
|
|
|
44
47
|
syntax_bad_pattern_element: "cannot read pattern element {element}",
|
|
45
48
|
syntax_bad_template_element: "cannot read template element {element}",
|
|
46
49
|
syntax_bad_role: "@syntax role wants one role name",
|
|
50
|
+
syntax_bad_alias: "@syntax alias wants one or more names",
|
|
47
51
|
};
|
|
48
52
|
function fail(id, params, span) {
|
|
49
53
|
const template = TEMPLATES[id] ?? id;
|
|
@@ -230,6 +234,15 @@ export function parseSyntaxAnnotation(text, span) {
|
|
|
230
234
|
}
|
|
231
235
|
return ok({ kind: "role", role });
|
|
232
236
|
}
|
|
237
|
+
case "alias": {
|
|
238
|
+
// Whitespace-split, so an alias is one token by construction: that
|
|
239
|
+
// is the shape a proof line's citation has anywhere it is read.
|
|
240
|
+
const names = words.slice(1);
|
|
241
|
+
if (names.length === 0) {
|
|
242
|
+
return fail("syntax_bad_alias", {}, span);
|
|
243
|
+
}
|
|
244
|
+
return ok({ kind: "alias", names });
|
|
245
|
+
}
|
|
233
246
|
default:
|
|
234
247
|
return fail("syntax_unknown_subcommand", { subcommand: subcommand ?? "(none)" }, span);
|
|
235
248
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"annotations.js","sourceRoot":"","sources":["../../src/reader/annotations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAmB,UAAU,EAAa,MAAM,mBAAmB,CAAC;AAE3E,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,0BAA0B;IAC1B,kBAAkB;CACV,CAAC;AAsHX,MAAM,iBAAiB,GAA+B;IACpD,OAAO;IACP,KAAK;IACL,MAAM;CACP,CAAC;AAEF,MAAM,SAAS,GAA2B;IACxC,yBAAyB,EAAE,yCAAyC;IACpE,eAAe,EAAE,mCAAmC;IACpD,qBAAqB,EACnB,+DAA+D;IACjE,iBAAiB,EAAE,8CAA8C;IACjE,mBAAmB,EACjB,yDAAyD;IAC3D,mBAAmB,EAAE,2CAA2C;IAChE,kBAAkB,EAChB,qEAAqE;IACvE,oBAAoB,EAClB,0FAA0F;IAC5F,sBAAsB,EAAE,mDAAmD;IAC3E,eAAe,EACb,uEAAuE;IACzE,0BAA0B,EAAE,uCAAuC;IACnE,2B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["/**\n * The `@syntax` annotation vocabulary — the \"little extra metadata\" that\n * turns an MM0 theory into a full surface-language spec.\n *\n * Annotations ride MM0's `--|` doc-comment channel, the same one Aufbau uses\n * for `@acui`, `@congr`, `@rewrite`, and the rest. Anything that is not\n * `@syntax` is *foreign*: preserved untouched for whoever owns it, never\n * interpreted here. The library also owns stripping `@syntax` lines before a theory is\n * handed to the engine, which currently rejects annotations it does not\n * know.\n *\n * Attachment rules (checked by the spec builder, not here):\n * - `juxtaposed` attaches to a binary term whose arguments and result\n * share one sort (adjacency of that sort's expressions denotes it);\n * - `elided` attaches to a nullary term (supplied when an argument of\n * its sort is missing, dropped again when printing);\n * - `role` attaches to a `sort`, a `term`, or a `def`;\n * - everything else is spec-wide and may sit on any statement.\n *\n * The lexicon itself needs no `@syntax` at all: letters are ordinary term\n * declarations, and variables ride the engine's own `@vars` annotation.\n */\n\nimport { type Diagnostic, diagnostic, type Span } from \"../diagnostics.js\";\n\nexport const LINT_NAMES = [\n \"parenthesize-binary-only\",\n \"closed-sentences\",\n] as const;\n\nexport type LintName = (typeof LINT_NAMES)[number];\n\n/** A capture in an elab pattern: `?ts:tm+` — name, class, quantifier. */\nexport interface RuleCapture {\n readonly kind: \"capture\";\n readonly name: string;\n /** A sort name; a leaf whose sort coerces into it matches. */\n readonly class: string;\n readonly quantifier: \"\" | \"+\" | \"?\";\n}\n\nexport interface RuleLiteral {\n readonly kind: \"literal\";\n readonly token: string;\n}\n\nexport type RulePatternElement = RuleCapture | RuleLiteral;\n\n/** A capture reference in an elab template: `?ts` or joined `?ts,*`. */\nexport interface RuleReference {\n readonly kind: \"reference\";\n readonly name: string;\n /** For a `+` capture, the token to join repeats with; null joins bare. */\n readonly separator: string | null;\n}\n\nexport type RuleTemplateElement = RuleLiteral | RuleReference;\n\nexport interface ElabRule {\n readonly inputOnly: boolean;\n readonly pattern: readonly RulePatternElement[];\n readonly span: Span;\n readonly template: readonly RuleTemplateElement[];\n}\n\nexport type SyntaxAnnotation =\n | {\n readonly kind: \"brackets\";\n readonly pairs: readonly (readonly [string, string])[];\n }\n | {\n readonly kind: \"display-drop-outer-parens\";\n }\n | {\n readonly kind: \"display-rotate-brackets\";\n readonly pairs: readonly (readonly [string, string])[];\n }\n | {\n /** A bidirectional token rule: elaborate in, delaborate out. */\n readonly kind: \"elab\";\n readonly rule: ElabRule;\n }\n | {\n /**\n * Surface delimiters: where a chunk of *student* input ends. Same\n * shape and same meaning as MM0's own `delimiter` statement, and\n * unioned with it — but an entry may be any string, not just a single\n * byte, so `∧` and `<->` can self-delimit where the engine's\n * byte table cannot hold them.\n */\n readonly kind: \"delimiter\";\n readonly left: readonly string[];\n readonly right: readonly string[];\n }\n | {\n /** Supplied when an argument of its sort is missing; drops on print. */\n readonly kind: \"elided\";\n }\n | {\n /** Adjacency of this combiner's sort denotes it — `Fxy`, `ab`. */\n readonly kind: \"juxtaposed\";\n /**\n * `@syntax juxtaposed compound`: a parenthesized group may stand as\n * a glue operand in argument position (`F(x)(y)`, `(lambda x)a`),\n * not just a single self-delimiting token. Opt-in, because under a\n * variadic sequence with an elided unit the group is already\n * spoken for — it is parenthesized application.\n */\n readonly compound: boolean;\n }\n | {\n readonly kind: \"lint\";\n readonly name: LintName;\n }\n | {\n /**\n * `@syntax forbid chain mix nest` — which unbracketed operands this\n * connective refuses. Unlisted permits, so an unmarked term refuses\n * nothing, which is the ordinary reading.\n */\n readonly kind: \"forbid\";\n readonly relations: readonly OperandRelation[];\n }\n | {\n readonly kind: \"role\";\n readonly role: string;\n };\n\n/**\n * How an unbracketed connective operand sits under the connective above it.\n *\n * The three cases are exhaustive. Precedence climbing parses an operand of\n * an operator at `p` with `min ≥ p` and admits only operators at\n * `prec ≥ min`, so an unbracketed operand's own operator is never *looser*\n * than its parent's; and a same-rung operand can only fall on the\n * associative side, the other side parsing at `p + 1`. There is no fourth\n * relation to name.\n */\nexport type OperandRelation =\n /** The same term repeated: `A ∧ B ∧ C`. */\n | \"chain\"\n /** A different term on the same rung: `A ∧ B ∨ C`. */\n | \"mix\"\n /** A term on a tighter rung: `A → B ∧ C`. */\n | \"nest\";\n\nconst OPERAND_RELATIONS: readonly OperandRelation[] = [\n \"chain\",\n \"mix\",\n \"nest\",\n];\n\nconst TEMPLATES: Record<string, string> = {\n syntax_unknown_subcommand: \"unknown @syntax subcommand {subcommand}\",\n syntax_bad_flag: \"@syntax {flag} takes no arguments\",\n syntax_bad_juxtaposed:\n \"@syntax juxtaposed takes nothing, or the single flag compound\",\n syntax_bad_forbid: \"@syntax forbid wants one or more of: {known}\",\n syntax_bad_brackets:\n \"bracket pairs come as: <open> <close> [<open> <close>…]\",\n syntax_unknown_lint: \"unknown lint {name}; known lints: {known}\",\n syntax_bad_display:\n \"@syntax display wants drop-outer-parens or rotate-brackets <pairs…>\",\n syntax_bad_delimiter:\n \"@syntax delimiter wants: delimiter $ <entries…> $, or delimiter $ <left…> $ $ <right…> $\",\n syntax_empty_delimiter: \"a @syntax delimiter math string must list entries\",\n syntax_bad_elab:\n \"@syntax elab wants: elab $ <pattern> $ => $ <template> $ [input-only]\",\n syntax_bad_pattern_element: \"cannot read pattern element {element}\",\n syntax_bad_template_element: \"cannot read template element {element}\",\n syntax_bad_role: \"@syntax role wants one role name\",\n};\n\nfunction fail(\n id: string,\n params: Record<string, string>,\n span: Span,\n): { annotation: null; diagnostic: Diagnostic } {\n const template = TEMPLATES[id] ?? id;\n return {\n annotation: null,\n diagnostic: diagnostic(id, template, params, span),\n };\n}\n\nfunction ok(annotation: SyntaxAnnotation): {\n annotation: SyntaxAnnotation;\n diagnostic: null;\n} {\n return { annotation, diagnostic: null };\n}\n\nexport type SyntaxAnnotationResult =\n | { readonly annotation: SyntaxAnnotation; readonly diagnostic: null }\n | { readonly annotation: null; readonly diagnostic: Diagnostic };\n\nfunction parsePairs(\n words: readonly string[],\n): (readonly [string, string])[] | null {\n if (words.length === 0 || words.length % 2 !== 0) {\n return null;\n }\n\n const pairs: (readonly [string, string])[] = [];\n\n for (let i = 0; i < words.length; i += 2) {\n const open = words[i];\n const close = words[i + 1];\n\n if (open === undefined || close === undefined || open === close) {\n return null;\n }\n\n pairs.push([open, close]);\n }\n\n return pairs;\n}\n\nconst CAPTURE =\n /^\\?([A-Za-z_][A-Za-z0-9_]*):([A-Za-z_][A-Za-z0-9_]*)([+?]?)$/;\nconst REFERENCE = /^\\?([A-Za-z_][A-Za-z0-9_]*)(?:(.)\\*)?$/;\n\nfunction parsePattern(text: string): readonly RulePatternElement[] | string {\n const elements: RulePatternElement[] = [];\n\n for (const word of text.split(/\\s+/).filter((w) => w.length > 0)) {\n if (word.startsWith(\"?\")) {\n const match = CAPTURE.exec(word);\n\n if (match === null) {\n return word;\n }\n\n elements.push({\n kind: \"capture\",\n name: match[1] ?? \"\",\n class: match[2] ?? \"\",\n quantifier: (match[3] ?? \"\") as \"\" | \"+\" | \"?\",\n });\n continue;\n }\n\n elements.push({ kind: \"literal\", token: word });\n }\n\n return elements;\n}\n\nfunction parseTemplate(\n text: string,\n): readonly RuleTemplateElement[] | string {\n const elements: RuleTemplateElement[] = [];\n\n for (const word of text.split(/\\s+/).filter((w) => w.length > 0)) {\n if (word.startsWith(\"?\")) {\n const match = REFERENCE.exec(word);\n\n if (match === null) {\n return word;\n }\n\n elements.push({\n kind: \"reference\",\n name: match[1] ?? \"\",\n separator: match[2] ?? null,\n });\n continue;\n }\n\n elements.push({ kind: \"literal\", token: word });\n }\n\n return elements;\n}\n\nconst ELAB = /^\\$(.*?)\\$\\s*=>\\s*\\$(.*?)\\$\\s*(input-only)?\\s*$/s;\n\n/** `$ … $`, or `$ left… $ $ right… $` — MM0's own two shapes. */\nconst DELIMITER = /^\\$([^$]*)\\$(?:\\s*\\$([^$]*)\\$)?\\s*$/;\n\n/**\n * Every entry written out, one at a time. There is deliberately no range\n * shorthand: a spike of `A-Z`-style ranges read `<->` as the range `<`…`>`\n * and silently turned one delimiter into three. A declaration that decides\n * how input is cut up is worth its verbosity.\n */\nfunction delimiterEntries(text: string): string[] {\n return text.split(/\\s+/).filter((entry) => entry.length > 0);\n}\n\n/**\n * Parse one annotation payload (the text after `--|`). Returns null for a\n * foreign annotation — anything that does not begin `@syntax`.\n */\nexport function parseSyntaxAnnotation(\n text: string,\n span: Span,\n): SyntaxAnnotationResult | null {\n const trimmed = text.trim();\n\n if (!trimmed.startsWith(\"@syntax\")) {\n return null;\n }\n\n const rest = trimmed.slice(\"@syntax\".length).trim();\n const words = rest.split(/\\s+/).filter((w) => w.length > 0);\n const subcommand = words[0];\n\n switch (subcommand) {\n case \"juxtaposed\": {\n if (words.length === 1) {\n return ok({ kind: \"juxtaposed\", compound: false });\n }\n\n if (words.length === 2 && words[1] === \"compound\") {\n return ok({ kind: \"juxtaposed\", compound: true });\n }\n\n return fail(\"syntax_bad_juxtaposed\", {}, span);\n }\n\n case \"elided\": {\n if (words.length !== 1) {\n return fail(\"syntax_bad_flag\", { flag: subcommand }, span);\n }\n\n return ok({ kind: subcommand });\n }\n\n case \"forbid\": {\n const relations = words.slice(1);\n\n if (\n relations.length === 0 ||\n !relations.every((relation): relation is OperandRelation =>\n (OPERAND_RELATIONS as readonly string[]).includes(relation),\n )\n ) {\n return fail(\n \"syntax_bad_forbid\",\n { known: OPERAND_RELATIONS.join(\", \") },\n span,\n );\n }\n\n return ok({ kind: \"forbid\", relations });\n }\n\n case \"brackets\": {\n const pairs = parsePairs(words.slice(1));\n\n if (pairs === null) {\n return fail(\"syntax_bad_brackets\", {}, span);\n }\n\n return ok({ kind: \"brackets\", pairs });\n }\n\n case \"delimiter\": {\n const match = DELIMITER.exec(rest.slice(\"delimiter\".length).trim());\n\n if (match === null) {\n return fail(\"syntax_bad_delimiter\", {}, span);\n }\n\n const first = delimiterEntries(match[1] ?? \"\");\n const second =\n match[2] === undefined ? null : delimiterEntries(match[2]);\n\n if (first.length === 0 || second?.length === 0) {\n return fail(\"syntax_empty_delimiter\", {}, span);\n }\n\n // One list means both sides, as in MM0.\n return ok({ kind: \"delimiter\", left: first, right: second ?? first });\n }\n\n case \"lint\": {\n const name = words[1];\n\n if (\n words.length !== 2 ||\n name === undefined ||\n !(LINT_NAMES as readonly string[]).includes(name)\n ) {\n return fail(\n \"syntax_unknown_lint\",\n { name: name ?? \"\", known: LINT_NAMES.join(\", \") },\n span,\n );\n }\n\n return ok({ kind: \"lint\", name: name as LintName });\n }\n\n case \"display\": {\n if (words[1] === \"drop-outer-parens\" && words.length === 2) {\n return ok({ kind: \"display-drop-outer-parens\" });\n }\n\n if (words[1] === \"rotate-brackets\") {\n const pairs = parsePairs(words.slice(2));\n\n if (pairs !== null) {\n return ok({ kind: \"display-rotate-brackets\", pairs });\n }\n }\n\n return fail(\"syntax_bad_display\", {}, span);\n }\n\n case \"elab\": {\n const match = ELAB.exec(rest.slice(\"elab\".length).trim());\n\n if (match === null) {\n return fail(\"syntax_bad_elab\", {}, span);\n }\n\n const pattern = parsePattern(match[1] ?? \"\");\n\n if (typeof pattern === \"string\") {\n return fail(\"syntax_bad_pattern_element\", { element: pattern }, span);\n }\n\n const template = parseTemplate(match[2] ?? \"\");\n\n if (typeof template === \"string\") {\n return fail(\n \"syntax_bad_template_element\",\n { element: template },\n span,\n );\n }\n\n return ok({\n kind: \"elab\",\n rule: {\n inputOnly: match[3] === \"input-only\",\n pattern,\n span,\n template,\n },\n });\n }\n\n case \"role\": {\n const role = words[1];\n\n if (words.length !== 2 || role === undefined) {\n return fail(\"syntax_bad_role\", {}, span);\n }\n\n return ok({ kind: \"role\", role });\n }\n\n default:\n return fail(\n \"syntax_unknown_subcommand\",\n { subcommand: subcommand ?? \"(none)\" },\n span,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"annotations.js","sourceRoot":"","sources":["../../src/reader/annotations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAmB,UAAU,EAAa,MAAM,mBAAmB,CAAC;AAE3E,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,0BAA0B;IAC1B,kBAA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AM,CAAC,CAAC,CAAC;YACZ,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YAEtB,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;gBAC7C,OAAO,IAAI,CAAC,iBAAiB,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;YAC3C,CAAC;YAED,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACpC,CAAC;QAED,KAAK,OAAO,CAAC,CAAC,CAAC;YACb,mEAAmE;YACnE,gEAAgE;YAChE,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE7B,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACvB,OAAO,IAAI,CAAC,kBAAkB,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;YAC5C,CAAC;YAED,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QACtC,CAAC;QAED;YACE,OAAO,IAAI,CACT,2BAA2B,EAC3B,EAAE,UAAU,EAAE,UAAU,IAAI,QAAQ,EAAE,EACtC,IAAI,CACL,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["/**\n * The `@syntax` annotation vocabulary — the \"little extra metadata\" that\n * turns an MM0 theory into a full surface-language spec.\n *\n * Annotations ride MM0's `--|` doc-comment channel, the same one Aufbau uses\n * for `@acui`, `@congr`, `@rewrite`, and the rest. Anything that is not\n * `@syntax` is *foreign*: preserved untouched for whoever owns it, never\n * interpreted here. The library also owns stripping `@syntax` lines before a theory is\n * handed to the engine, which currently rejects annotations it does not\n * know.\n *\n * Attachment rules (checked by the spec builder, not here):\n * - `juxtaposed` attaches to a binary term whose arguments and result\n * share one sort (adjacency of that sort's expressions denotes it);\n * - `elided` attaches to a nullary term (supplied when an argument of\n * its sort is missing, dropped again when printing);\n * - `role` attaches to a `sort`, a `term`, a `def`, an `axiom`, or a\n * `theorem`;\n * - `alias` attaches to an `axiom` or a `theorem` (the names a proof may\n * cite it by, since the engine's identifiers are ASCII);\n * - everything else is spec-wide and may sit on any statement.\n *\n * The lexicon itself needs no `@syntax` at all: letters are ordinary term\n * declarations, and variables ride the engine's own `@vars` annotation.\n */\n\nimport { type Diagnostic, diagnostic, type Span } from \"../diagnostics.js\";\n\nexport const LINT_NAMES = [\n \"parenthesize-binary-only\",\n \"closed-sentences\",\n] as const;\n\nexport type LintName = (typeof LINT_NAMES)[number];\n\n/** A capture in an elab pattern: `?ts:tm+` — name, class, quantifier. */\nexport interface RuleCapture {\n readonly kind: \"capture\";\n readonly name: string;\n /** A sort name; a leaf whose sort coerces into it matches. */\n readonly class: string;\n readonly quantifier: \"\" | \"+\" | \"?\";\n}\n\nexport interface RuleLiteral {\n readonly kind: \"literal\";\n readonly token: string;\n}\n\nexport type RulePatternElement = RuleCapture | RuleLiteral;\n\n/** A capture reference in an elab template: `?ts` or joined `?ts,*`. */\nexport interface RuleReference {\n readonly kind: \"reference\";\n readonly name: string;\n /** For a `+` capture, the token to join repeats with; null joins bare. */\n readonly separator: string | null;\n}\n\nexport type RuleTemplateElement = RuleLiteral | RuleReference;\n\nexport interface ElabRule {\n readonly inputOnly: boolean;\n readonly pattern: readonly RulePatternElement[];\n readonly span: Span;\n readonly template: readonly RuleTemplateElement[];\n}\n\nexport type SyntaxAnnotation =\n | {\n /**\n * `@syntax alias ∧I &I` — further names a proof may cite this rule\n * by. MM0 identifiers are ASCII, so a textbook's `∧I` can never be\n * the axiom's own name; the aliases are surface names for it, one\n * whitespace-free token each, resolved by a consumer before the\n * citation reaches the engine.\n */\n readonly kind: \"alias\";\n readonly names: readonly string[];\n }\n | {\n readonly kind: \"brackets\";\n readonly pairs: readonly (readonly [string, string])[];\n }\n | {\n readonly kind: \"display-drop-outer-parens\";\n }\n | {\n readonly kind: \"display-rotate-brackets\";\n readonly pairs: readonly (readonly [string, string])[];\n }\n | {\n /** A bidirectional token rule: elaborate in, delaborate out. */\n readonly kind: \"elab\";\n readonly rule: ElabRule;\n }\n | {\n /**\n * Surface delimiters: where a chunk of *student* input ends. Same\n * shape and same meaning as MM0's own `delimiter` statement, and\n * unioned with it — but an entry may be any string, not just a single\n * byte, so `∧` and `<->` can self-delimit where the engine's\n * byte table cannot hold them.\n */\n readonly kind: \"delimiter\";\n readonly left: readonly string[];\n readonly right: readonly string[];\n }\n | {\n /** Supplied when an argument of its sort is missing; drops on print. */\n readonly kind: \"elided\";\n }\n | {\n /** Adjacency of this combiner's sort denotes it — `Fxy`, `ab`. */\n readonly kind: \"juxtaposed\";\n /**\n * `@syntax juxtaposed compound`: a parenthesized group may stand as\n * a glue operand in argument position (`F(x)(y)`, `(lambda x)a`),\n * not just a single self-delimiting token. Opt-in, because under a\n * variadic sequence with an elided unit the group is already\n * spoken for — it is parenthesized application.\n */\n readonly compound: boolean;\n }\n | {\n readonly kind: \"lint\";\n readonly name: LintName;\n }\n | {\n /**\n * `@syntax forbid chain mix nest` — which unbracketed operands this\n * connective refuses. Unlisted permits, so an unmarked term refuses\n * nothing, which is the ordinary reading.\n */\n readonly kind: \"forbid\";\n readonly relations: readonly OperandRelation[];\n }\n | {\n readonly kind: \"role\";\n readonly role: string;\n };\n\n/**\n * How an unbracketed connective operand sits under the connective above it.\n *\n * The three cases are exhaustive. Precedence climbing parses an operand of\n * an operator at `p` with `min ≥ p` and admits only operators at\n * `prec ≥ min`, so an unbracketed operand's own operator is never *looser*\n * than its parent's; and a same-rung operand can only fall on the\n * associative side, the other side parsing at `p + 1`. There is no fourth\n * relation to name.\n */\nexport type OperandRelation =\n /** The same term repeated: `A ∧ B ∧ C`. */\n | \"chain\"\n /** A different term on the same rung: `A ∧ B ∨ C`. */\n | \"mix\"\n /** A term on a tighter rung: `A → B ∧ C`. */\n | \"nest\";\n\nconst OPERAND_RELATIONS: readonly OperandRelation[] = [\n \"chain\",\n \"mix\",\n \"nest\",\n];\n\nconst TEMPLATES: Record<string, string> = {\n syntax_unknown_subcommand: \"unknown @syntax subcommand {subcommand}\",\n syntax_bad_flag: \"@syntax {flag} takes no arguments\",\n syntax_bad_juxtaposed:\n \"@syntax juxtaposed takes nothing, or the single flag compound\",\n syntax_bad_forbid: \"@syntax forbid wants one or more of: {known}\",\n syntax_bad_brackets:\n \"bracket pairs come as: <open> <close> [<open> <close>…]\",\n syntax_unknown_lint: \"unknown lint {name}; known lints: {known}\",\n syntax_bad_display:\n \"@syntax display wants drop-outer-parens or rotate-brackets <pairs…>\",\n syntax_bad_delimiter:\n \"@syntax delimiter wants: delimiter $ <entries…> $, or delimiter $ <left…> $ $ <right…> $\",\n syntax_empty_delimiter: \"a @syntax delimiter math string must list entries\",\n syntax_bad_elab:\n \"@syntax elab wants: elab $ <pattern> $ => $ <template> $ [input-only]\",\n syntax_bad_pattern_element: \"cannot read pattern element {element}\",\n syntax_bad_template_element: \"cannot read template element {element}\",\n syntax_bad_role: \"@syntax role wants one role name\",\n syntax_bad_alias: \"@syntax alias wants one or more names\",\n};\n\nfunction fail(\n id: string,\n params: Record<string, string>,\n span: Span,\n): { annotation: null; diagnostic: Diagnostic } {\n const template = TEMPLATES[id] ?? id;\n return {\n annotation: null,\n diagnostic: diagnostic(id, template, params, span),\n };\n}\n\nfunction ok(annotation: SyntaxAnnotation): {\n annotation: SyntaxAnnotation;\n diagnostic: null;\n} {\n return { annotation, diagnostic: null };\n}\n\nexport type SyntaxAnnotationResult =\n | { readonly annotation: SyntaxAnnotation; readonly diagnostic: null }\n | { readonly annotation: null; readonly diagnostic: Diagnostic };\n\nfunction parsePairs(\n words: readonly string[],\n): (readonly [string, string])[] | null {\n if (words.length === 0 || words.length % 2 !== 0) {\n return null;\n }\n\n const pairs: (readonly [string, string])[] = [];\n\n for (let i = 0; i < words.length; i += 2) {\n const open = words[i];\n const close = words[i + 1];\n\n if (open === undefined || close === undefined || open === close) {\n return null;\n }\n\n pairs.push([open, close]);\n }\n\n return pairs;\n}\n\nconst CAPTURE =\n /^\\?([A-Za-z_][A-Za-z0-9_]*):([A-Za-z_][A-Za-z0-9_]*)([+?]?)$/;\nconst REFERENCE = /^\\?([A-Za-z_][A-Za-z0-9_]*)(?:(.)\\*)?$/;\n\nfunction parsePattern(text: string): readonly RulePatternElement[] | string {\n const elements: RulePatternElement[] = [];\n\n for (const word of text.split(/\\s+/).filter((w) => w.length > 0)) {\n if (word.startsWith(\"?\")) {\n const match = CAPTURE.exec(word);\n\n if (match === null) {\n return word;\n }\n\n elements.push({\n kind: \"capture\",\n name: match[1] ?? \"\",\n class: match[2] ?? \"\",\n quantifier: (match[3] ?? \"\") as \"\" | \"+\" | \"?\",\n });\n continue;\n }\n\n elements.push({ kind: \"literal\", token: word });\n }\n\n return elements;\n}\n\nfunction parseTemplate(\n text: string,\n): readonly RuleTemplateElement[] | string {\n const elements: RuleTemplateElement[] = [];\n\n for (const word of text.split(/\\s+/).filter((w) => w.length > 0)) {\n if (word.startsWith(\"?\")) {\n const match = REFERENCE.exec(word);\n\n if (match === null) {\n return word;\n }\n\n elements.push({\n kind: \"reference\",\n name: match[1] ?? \"\",\n separator: match[2] ?? null,\n });\n continue;\n }\n\n elements.push({ kind: \"literal\", token: word });\n }\n\n return elements;\n}\n\nconst ELAB = /^\\$(.*?)\\$\\s*=>\\s*\\$(.*?)\\$\\s*(input-only)?\\s*$/s;\n\n/** `$ … $`, or `$ left… $ $ right… $` — MM0's own two shapes. */\nconst DELIMITER = /^\\$([^$]*)\\$(?:\\s*\\$([^$]*)\\$)?\\s*$/;\n\n/**\n * Every entry written out, one at a time. There is deliberately no range\n * shorthand: a spike of `A-Z`-style ranges read `<->` as the range `<`…`>`\n * and silently turned one delimiter into three. A declaration that decides\n * how input is cut up is worth its verbosity.\n */\nfunction delimiterEntries(text: string): string[] {\n return text.split(/\\s+/).filter((entry) => entry.length > 0);\n}\n\n/**\n * Parse one annotation payload (the text after `--|`). Returns null for a\n * foreign annotation — anything that does not begin `@syntax`.\n */\nexport function parseSyntaxAnnotation(\n text: string,\n span: Span,\n): SyntaxAnnotationResult | null {\n const trimmed = text.trim();\n\n if (!trimmed.startsWith(\"@syntax\")) {\n return null;\n }\n\n const rest = trimmed.slice(\"@syntax\".length).trim();\n const words = rest.split(/\\s+/).filter((w) => w.length > 0);\n const subcommand = words[0];\n\n switch (subcommand) {\n case \"juxtaposed\": {\n if (words.length === 1) {\n return ok({ kind: \"juxtaposed\", compound: false });\n }\n\n if (words.length === 2 && words[1] === \"compound\") {\n return ok({ kind: \"juxtaposed\", compound: true });\n }\n\n return fail(\"syntax_bad_juxtaposed\", {}, span);\n }\n\n case \"elided\": {\n if (words.length !== 1) {\n return fail(\"syntax_bad_flag\", { flag: subcommand }, span);\n }\n\n return ok({ kind: subcommand });\n }\n\n case \"forbid\": {\n const relations = words.slice(1);\n\n if (\n relations.length === 0 ||\n !relations.every((relation): relation is OperandRelation =>\n (OPERAND_RELATIONS as readonly string[]).includes(relation),\n )\n ) {\n return fail(\n \"syntax_bad_forbid\",\n { known: OPERAND_RELATIONS.join(\", \") },\n span,\n );\n }\n\n return ok({ kind: \"forbid\", relations });\n }\n\n case \"brackets\": {\n const pairs = parsePairs(words.slice(1));\n\n if (pairs === null) {\n return fail(\"syntax_bad_brackets\", {}, span);\n }\n\n return ok({ kind: \"brackets\", pairs });\n }\n\n case \"delimiter\": {\n const match = DELIMITER.exec(rest.slice(\"delimiter\".length).trim());\n\n if (match === null) {\n return fail(\"syntax_bad_delimiter\", {}, span);\n }\n\n const first = delimiterEntries(match[1] ?? \"\");\n const second =\n match[2] === undefined ? null : delimiterEntries(match[2]);\n\n if (first.length === 0 || second?.length === 0) {\n return fail(\"syntax_empty_delimiter\", {}, span);\n }\n\n // One list means both sides, as in MM0.\n return ok({ kind: \"delimiter\", left: first, right: second ?? first });\n }\n\n case \"lint\": {\n const name = words[1];\n\n if (\n words.length !== 2 ||\n name === undefined ||\n !(LINT_NAMES as readonly string[]).includes(name)\n ) {\n return fail(\n \"syntax_unknown_lint\",\n { name: name ?? \"\", known: LINT_NAMES.join(\", \") },\n span,\n );\n }\n\n return ok({ kind: \"lint\", name: name as LintName });\n }\n\n case \"display\": {\n if (words[1] === \"drop-outer-parens\" && words.length === 2) {\n return ok({ kind: \"display-drop-outer-parens\" });\n }\n\n if (words[1] === \"rotate-brackets\") {\n const pairs = parsePairs(words.slice(2));\n\n if (pairs !== null) {\n return ok({ kind: \"display-rotate-brackets\", pairs });\n }\n }\n\n return fail(\"syntax_bad_display\", {}, span);\n }\n\n case \"elab\": {\n const match = ELAB.exec(rest.slice(\"elab\".length).trim());\n\n if (match === null) {\n return fail(\"syntax_bad_elab\", {}, span);\n }\n\n const pattern = parsePattern(match[1] ?? \"\");\n\n if (typeof pattern === \"string\") {\n return fail(\"syntax_bad_pattern_element\", { element: pattern }, span);\n }\n\n const template = parseTemplate(match[2] ?? \"\");\n\n if (typeof template === \"string\") {\n return fail(\n \"syntax_bad_template_element\",\n { element: template },\n span,\n );\n }\n\n return ok({\n kind: \"elab\",\n rule: {\n inputOnly: match[3] === \"input-only\",\n pattern,\n span,\n template,\n },\n });\n }\n\n case \"role\": {\n const role = words[1];\n\n if (words.length !== 2 || role === undefined) {\n return fail(\"syntax_bad_role\", {}, span);\n }\n\n return ok({ kind: \"role\", role });\n }\n\n case \"alias\": {\n // Whitespace-split, so an alias is one token by construction: that\n // is the shape a proof line's citation has anywhere it is read.\n const names = words.slice(1);\n\n if (names.length === 0) {\n return fail(\"syntax_bad_alias\", {}, span);\n }\n\n return ok({ kind: \"alias\", names });\n }\n\n default:\n return fail(\n \"syntax_unknown_subcommand\",\n { subcommand: subcommand ?? \"(none)\" },\n span,\n );\n }\n}\n"]}
|
package/dist/reader/spec.d.ts
CHANGED
|
@@ -33,6 +33,12 @@ export interface TermInfo {
|
|
|
33
33
|
readonly foreignAnnotations: readonly Annotation[];
|
|
34
34
|
/** True when this came from a `def` rather than a `term`. */
|
|
35
35
|
readonly isDef: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* A def's body: its definiens as engine text, over `binders` and its own
|
|
38
|
+
* dot-dummies. Null for a `term`, and for a def whose definiens the proof
|
|
39
|
+
* file supplies. `unfoldDefinitions` reads it.
|
|
40
|
+
*/
|
|
41
|
+
readonly definition: Definition | null;
|
|
36
42
|
/** `@syntax juxtaposed`: adjacency of its sort's leaves denotes it. */
|
|
37
43
|
readonly juxtaposed: boolean;
|
|
38
44
|
/**
|
|
@@ -52,12 +58,44 @@ export interface TermInfo {
|
|
|
52
58
|
readonly roles: readonly string[];
|
|
53
59
|
readonly span: Span;
|
|
54
60
|
}
|
|
61
|
+
/** A def's definiens and the dot-dummies it binds. */
|
|
62
|
+
export interface Definition {
|
|
63
|
+
readonly dummies: readonly Binder[];
|
|
64
|
+
readonly text: string;
|
|
65
|
+
}
|
|
55
66
|
export interface CoercionInfo {
|
|
56
67
|
readonly from: string;
|
|
57
68
|
readonly name: string;
|
|
58
69
|
readonly span: Span;
|
|
59
70
|
readonly to: string;
|
|
60
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* An axiom or theorem, as far as the surface layer is concerned: a name a
|
|
74
|
+
* proof cites, the `@syntax alias` names it may cite it by instead, and the
|
|
75
|
+
* `@syntax role`s that say what it is for. The statement itself passes
|
|
76
|
+
* through opaque, on `Spec.statements`.
|
|
77
|
+
*/
|
|
78
|
+
export interface RuleInfo {
|
|
79
|
+
/** In declaration order; never contains the rule's own name. */
|
|
80
|
+
readonly aliases: readonly string[];
|
|
81
|
+
/**
|
|
82
|
+
* The rule the engine retries this one with when it fails to apply, read
|
|
83
|
+
* from the engine's own `@fallback` annotation (which stays in
|
|
84
|
+
* `foreignAnnotations` — it is the engine's, we only listen in). Always an
|
|
85
|
+
* earlier rule, so following the chain ends; `null` without one.
|
|
86
|
+
*/
|
|
87
|
+
readonly fallback: string | null;
|
|
88
|
+
readonly foreignAnnotations: readonly Annotation[];
|
|
89
|
+
readonly kind: "axiom" | "theorem";
|
|
90
|
+
readonly name: string;
|
|
91
|
+
/**
|
|
92
|
+
* `@syntax role`: what this rule *is* to a consumer — a proof editor
|
|
93
|
+
* looks for `assumption` to tell the lines that open a hypothesis from
|
|
94
|
+
* the ones that cite a rule. Uninterpreted here, like a term's roles.
|
|
95
|
+
*/
|
|
96
|
+
readonly roles: readonly string[];
|
|
97
|
+
readonly span: Span;
|
|
98
|
+
}
|
|
61
99
|
export type NotationInfo = {
|
|
62
100
|
readonly form: "general";
|
|
63
101
|
/** The notation statement's own binders, which its variables name. */
|
|
@@ -90,6 +128,15 @@ export interface Spec {
|
|
|
90
128
|
/** In declaration order; the last notation for a term is canonical. */
|
|
91
129
|
readonly notations: readonly NotationInfo[];
|
|
92
130
|
readonly elabRules: readonly ElabRule[];
|
|
131
|
+
/**
|
|
132
|
+
* Alias to the rule it names, over every `@syntax alias` in the spec —
|
|
133
|
+
* the one lookup a proof reader needs: `ruleAliases.get(cited) ?? cited`
|
|
134
|
+
* is what to hand the engine. Canonical names are not keys; a name that
|
|
135
|
+
* is not an alias is already the engine's.
|
|
136
|
+
*/
|
|
137
|
+
readonly ruleAliases: ReadonlyMap<string, string>;
|
|
138
|
+
/** Every axiom and theorem, keyed by name. */
|
|
139
|
+
readonly rules: ReadonlyMap<string, RuleInfo>;
|
|
93
140
|
readonly sorts: ReadonlyMap<string, SortInfo>;
|
|
94
141
|
/** Every statement, in order, annotations intact — full fidelity. */
|
|
95
142
|
readonly statements: readonly Statement[];
|