diff --git a/docs/CORRECTNESS.md b/docs/CORRECTNESS.md index a3642eda..6e152b42 100644 --- a/docs/CORRECTNESS.md +++ b/docs/CORRECTNESS.md @@ -96,17 +96,17 @@ interpreter. Where that argument cannot be made for a row, the row says so. | `altMightStart` / `altMightSecond` pruning: a FIRST / SECOND over-approximation, so it can only skip an arm that cannot match | `Guard` first / second, `Dispatch` sections, `Commit` | `guardCond` in each printer | gate `guard-refutation` (every refusal re-run; none unsound) | V | | Ordered choice inside a sequence (`alt`: first match) | `Step alt` (`predictive` when FIRST-disjoint) | `StepLowering.alt` | every list | V | | `*` / `+` stop on an empty iteration; `sep` takes a trailing delimiter | `Step star` / `sep` | `StepLowering.star` / `sep` | lists (`[a, , ...b,]`) | V | -| Zero-width tests: `not(…)`, a keyword-set fast path, `reservableNot` | `Step look` / `ahead` / `aheadCtx` | `StepLowering.look` / `ahead` | `RESERVED_EXPRS`, `conciseBody` rows (`() => { b() {} }.x`) | V | +| Zero-width tests: `not(…)`, a keyword-set fast path, a guard's `when` words | `Step look` / `ahead` / `aheadCtx` | `StepLowering.look` / `ahead` | `RESERVED_EXPRS`, `conciseBody` rows (`() => { b() {} }.x`) | V | | Newline sensitivity: `sameLine` (restricted productions, ASI through `not(sameLine)`) | `Step sameLine`, `PrattRule.postfixSameLine`, `ledSameLine` | `StepLowering.sameLine`, `postfixOp`, `led.sameLine` | `x\n++\ny`, `async\nx => …`, `a ? b : () => {}\n+x;` | V | | `noCommentBefore`, `noMultilineFlowBefore`, indent, markup containers | none: refused loudly (`portable: rd construct … not in scope`; indent and markup grammars throw in `portableIR`) | — | — | R: the refusal is the argument; no portable grammar can contain them | | `[Await]` / `[Yield]`: the context word (`ctxWordOfMode`, `ctxObserves`) | `Step ctx`, `aheadCtx`, `ctxWords` | `StepLowering.ctx` | `CTX_CASES` (generator / async rows) | V | | Contextual keywords: a word is an identifier except where an arm names it | literal steps over the identifier token (`identLike`), `reservableNot` | lexer id plan (`lidOf`) | `RESERVED_EXPRS`, `let;`, `for (async of => {};;)` | V | -| Suppress staging: a `suppress` group stages its set for the next Pratt / leftRec rule call only | `Step suppress`: `_suppressNext = set; body; _suppressNext = 0`; `ledSuppressedIn` | `StepLowering.suppress`, `led.notSuppressed` | `NO_IN_HEADS`, `FOR_HEADS` | V | +| Context equations: a `ctx` group parses its body in `(word & keep) \| set` and puts the word back; a gated led (`LedPrec.when`) is tried only where the word passes | `Step ctx`; `PrattRule.ledWhen` | `StepLowering.ctx`, `led.when` | `NO_IN_HEADS`, `FOR_HEADS` | V | | Pratt NUD: longest match over the NUD arms | `nudOrder`, `nudDispatch`, `nudCommit` | `nudSeq` / `nudLeaf` / `commitSeq` | every expression row | V | | Capped NUD (`capExpr`, an arrow; the `yield` arm): a candidate only when `minBp < capBp`; once it wins, no led | `nudCapped` + `capBp`; the capped flag | `capBelow`; `bpOpen` returns at once when capped | `CAP_PROPAGATION` | V | | Cap propagation through a binary right operand (`a = () => {} \|\| x` rejects) | `binary` lowering | `PrattLowering.binary` | `CAP_PROPAGATION` (`b = a = () => {} \|\| c`) | V | | Cap propagation through a trailing operand: a node whose rightmost child is a self operand at bp 0 that returned capped is capped (`a ? b : () => {} \|\| x`, `[...() => {} \|\| x]` reject) | `ledCapsFromTail`, `nudBracketCapsFromTail`, `nudSeqCapsFromTail`; `NodeCap` | `ledArm(…, capsFromTail)`, `nudSeq` / `commitSeq` with `NodeCap` | `CAP_PROPAGATION` (`a ? b : () => {} ? c : d`, `f(...() => {} \|\| x)`), `REBIND.ts` (`let v = a ? (b) : c => {} \|\| x;`) | V | -| The packrat memo over Pratt / leftRec rules, keyed by (rule, start); bypassed under a suppress set or a re-bind cap; the entry is {node, end, capped} | none: the portable engine has no memo (a re-parse yields the same result) | — | `MONOGRAM_MEMO_VERIFY=1`: every hit is parsed again and must give the recorded end, cap and tree, or the parse throws; run over the tsc conformance corpus, test262 `language/` and CPython `Lib/`: no assertion (2026-11-24) | W: a pure function of (rule, start) outside suppress and cap, and it carries the cap that the only post-call reader (above) reads; the witness re-checks it on any corpus | +| The packrat memo over Pratt / leftRec rules, keyed by (rule, start, the context word it reads); bypassed under a re-bind cap; the entry is {node, end, capped} | none: the portable engine has no memo (a re-parse yields the same result) | — | `MONOGRAM_MEMO_VERIFY=1`: every hit is parsed again and must give the recorded end, cap and tree, or the parse throws; run over the tsc conformance corpus, test262 `language/` and CPython `Lib/`: no assertion (2026-11-24) | W: a pure function of (rule, start) outside suppress and cap, and it carries the cap that the only post-call reader (above) reads; the witness re-checks it on any corpus | | Prefix NUD and `requireAssignTarget` (`++-x` rejects) | `prefix[]` with `requireAssignTarget`, `form` | `nudPrefix` / `commitPrefix` | `++-x`, `++ ++x` | V | | Assignment-target form: an operator node is not a target; a prefix-unary node is not a `noUnaryLhs` operand; the middle-child test applies only to LED-built nodes | `AssignForm`: `ledForm`, `prefix[].form`, `FORM_*` | `binary` (`tgt` / `noUnary`), `postfixOp` | `x = class as {} = 1;`, `-x ** y`, `a + b = c` | V | | Non-op LEDs: the `ledPrecOf` lbp gate, a chain-rhs operand at its level's bp (`in`, `instanceof`) | `ledLbp`, `Step ruleBp` | `led.lbpAbove`, `ruleBp` step | `a == b ? c : d`, `a in b in c` | V | diff --git a/docs/GRAMMAR.md b/docs/GRAMMAR.md index b5d57675..f322c3f2 100644 --- a/docs/GRAMMAR.md +++ b/docs/GRAMMAR.md @@ -171,43 +171,56 @@ every operand position (Python's, [`python.ts`](../python.ts); fixture The body must be a reference to a Pratt rule; anything else is refused by name. -## Contexts: `when` +## Contexts: `params`, `ctx`, `when` A grammar's productions can depend on where they stand: ECMAScript's `[Yield]` and `[Await]` parameters make `yield` and `await` operators inside a generator / async body and identifiers -elsewhere. The context is one word the parser holds; the markers `awaitCtx` / `yieldCtx` / -`asyncGenCtx` / `resetCtx` set it for a body (a function's, an arrow's, a method's: an arrow's -body does not inherit the context unless the arrow is async), and `when(cond, ...items)` makes -the items exist only where the condition holds: +elsewhere, and `[In]` says whether a relational `in` is read (not in a `for` head's first +expression). A grammar declares its parameters with their values at the top level, `ctx(eqs, +...items)` sets (`true`) or clears (`false`) some of them for the items (the others are copied +from the reference's context), and `when(cond, ...items)` makes the items exist only where the +condition holds: ```ts +defineGrammar({ params: { await: false, yield: false, syncFn: false, in: true }, ... }) +arm('generator', 'function', '*', ...nameParts, '(', sep(ctx({ await: false, yield: true, syncFn: true, in: true }, Param), ','), ')', ...), arm('yield_', capExpr('?', when('+yield', 'yield', alt(arm('star', sameLine, '*', $), arm('expr', opt(sameLine, $)))))), right(prefix('!', '~', '+', '-', 'typeof', 'void', 'delete', when('~syncFn', 'await'))), // a gated operator +ledPrec: [{ connector: 'in', sameAs: '<', chainRhs: true, when: '+in' }], // a gated led +arm('classic', ..., opt(ctx({ in: false }, field('initializer', Expr))), ...), // Expression[~In] +['(', ctx({ in: true }, field('first', $), many(',', field('rest', $))), ')'], // ( Expression[+In] ) +const notReservedExpr = not(alt(...reservedWords, when('+await', 'await'), when('+yield', 'yield'))); +template: { open: '`', interpOpen: '${', interpClose: '}', holeCtx: { in: true } }, // ${ Expression[+In] } // function* g() { yield a; }: a YieldExpression. iter = yield();: a call of the identifier yield. +// for (x = (a in b);;): a parenthesised `in`. for (x => x in y;;): no parse (ConciseBody[?In]). ``` -A condition is a conjunction of `+p` / `~p` over the parameters of -[`src/grammar/grammar-utils.ts`](../src/grammar/grammar-utils.ts) `CTX_PARAMS` (`await`, `yield`, `syncFn`); with -no items, `when(cond)` is a zero-width test. tree-sitter, TextMate and Monarch erase the -condition: they render the items everywhere. - -Every engine holds the context as ONE word (step 2): the interpreter, the jsTarget parser and the -portable parsers set it at a context marker for the marker's body and put it back after, and read -it at a `when`, a gated operator and the reserved-word guard (`reservableNot`, whose context words -are `CTX_WORDS`). A rule's parse is a function of its position and of the word masked by the bits -the rule can read (`ctxObserves`, computed once from the grammar: a `when`, a gated operator or the -guard reachable from the rule without a marker in between); that pair is the key of the -interpreter's and jsTarget's packrat memo, and jsTarget's incremental rows carry the masked word -(`rowCtx`) beside the rule, compared by every reuse check. Rules are the grammar's own (no copies -per context). - -**Transition** (declared contexts; step 2 of the design landed): the end state is named boolean -parameters declared by the grammar, set / cleared at a reference (`ctx({p: true}, ...)`), read by -`when`, held as the one word in every engine. Reached: the one word in every engine (the rule fork -is deleted). Owed, each with its step: `in` as a parameter, which needs the set / clear equations -(`ctx(...)` replacing the four markers, which today set the whole word) and deletes `exclude` and -the suppress machinery (step 3); the guard's context words written as `when` items inside it, -deleting `reservableNot` and `CTX_WORDS` (step 3, with `ctx(...)`); TypeScript's contexts (step 4); +A condition is a conjunction of `+p` / `~p` over the grammar's `params`; with no items, +`when(cond)` is a zero-width test. Where `when` stands: an item or an arm, an operator of a +`prefix(...)` level, a led (`LedPrec.when`; an entry with `when` and no `sameAs` / `below` +only gates), and a word of a `not`'s alternation (the reserved-word guard refuses the word only +where the condition holds). A template token's `holeCtx` holds the equations its holes are read +under. Copy is the default: the spec's `[+In]` at a bracket is written where it stands (an +expression in parentheses, brackets, braces, arguments, a template, a conditional's middle operand, +a block, a function's parameters and body). tree-sitter, TextMate and Monarch erase the +conditions: they render the items everywhere (tree-sitter reads `contextFreeView`: no `ctx` +group, no guard word that only a context refuses). + +Every engine holds the context as ONE word, a bit per parameter set where it differs from its +entry value (so the entry word is 0): the interpreter, the jsTarget parser and the portable parsers +set it at a `ctx` group for the group's body and put it back after, and read it at a `when`, a +gated operator or led and the reserved-word guard. A rule's parse is a function of its position +and of the word masked by the bits the rule can read (`ctxObserves`, computed once from the +grammar: a `when`, a gated operator or led or a guard word reachable from the rule, minus the bits +a `ctx` group on the way fixes); that pair is the key of the interpreter's and jsTarget's packrat +memo, and jsTarget's incremental rows carry the masked word (`rowCtx`) beside the rule, compared +by every reuse check. Rules are the grammar's own (no copies per context). + +**Transition** (declared contexts; steps 1-3 of the design landed): the end state is named boolean +parameters declared by the grammar, set / cleared at a reference, read by `when`, held as the one +word in every engine. Reached: the one word in every engine; `[In]` a parameter (`exclude` and its +suppress machinery deleted); `ctx(...)` in place of the four markers; the guard's context words as +`when` items (`reservableNot` deleted). Owed, each with its step: TypeScript's contexts (step 4); the script / module goals: `syncFn` stands in for them (set in a non-async function body, so the top level reads `await` both ways and `await(x)` at the top level is still the operator); the goals step sets `await` in the Module goal's entry word, the gate becomes `when('+await')` and `syncFn` is diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index fea0a9c9..4e882762 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -148,7 +148,7 @@ or duplicated arms. alternatives that can never win (the keyword types shadowed by the identifier arm) and four ambiguities resolved only by arm order. - **Parameterised productions, completed**, as the notation of the specification rather than - per-case engine features: `[In]` (today `exclude('in', …)` at each `for` head site); the + per-case engine features: `[In]` (a declared parameter since contexts step 3: `ctx({ in: false }, …)`); the `[Yield]` / `[Await]` line-break and assignment cases (`function* g() { yield⏎* x; }` parses today); module-level `await`; and "left context" as a parameter (`Decl[±Prefixed]` for the decorator and modifier placement cases owed in `typescript.ts`). diff --git a/docs/TEST262.md b/docs/TEST262.md index c6c7a6ad..1c5e1900 100644 --- a/docs/TEST262.md +++ b/docs/TEST262.md @@ -20,7 +20,7 @@ a test that test262 runs both sloppy and strict, or only in one mode, or as a mo first run's text: `"use strict";` prepended for `onlyStrict`). What depends on the goal or the mode is a class of its own below (`needs-parameter`). -**21773 of 24677 agree (88.2%).** +**21777 of 24677 agree (88.2%).** ## Scoreboard @@ -35,7 +35,7 @@ of its own below (`needs-parameter`). | `directive-prologue` | 62 | 51 | 0 | 11 | 0 | 0 | | `eval-code` | 347 | 347 | 0 | 0 | 0 | 0 | | `export` | 3 | 0 | 3 | 0 | 0 | 0 | -| `expressions` | 11156 | 9110 | 745 | 1297 | 4 | 0 | +| `expressions` | 11156 | 9110 | 748 | 1294 | 4 | 0 | | `function-code` | 217 | 217 | 0 | 0 | 0 | 0 | | `future-reserved-words` | 55 | 29 | 8 | 18 | 0 | 0 | | `global-code` | 42 | 28 | 0 | 14 | 0 | 0 | @@ -60,8 +60,8 @@ of its own below (`needs-parameter`). | `annexB/function-code` | 159 | 159 | 0 | 0 | 0 | 0 | | `annexB/global-code` | 153 | 153 | 0 | 0 | 0 | 0 | | `annexB/literals` | 8 | 8 | 0 | 0 | 0 | 0 | -| `annexB/statements` | 22 | 16 | 0 | 6 | 0 | 0 | -| **total** | **24677** | **20188** | **1585** | **2892** | **12** | **0** | +| `annexB/statements` | 22 | 16 | 1 | 5 | 0 | 0 | +| **total** | **24677** | **20188** | **1589** | **2888** | **12** | **0** | WE-ACCEPT: test262 says SyntaxError, the grammar parses. WE-REJECT: test262 parses, the grammar rejects. @@ -102,13 +102,12 @@ run); where it does not, the rule is outside even its syntactic layer. | `accept/rest-element-shape`: a rest element with an initializer, a trailing comma, or a follower | 345 | 345 | grammar bug: fix | `language/expressions/arrow-function/dflt-params-rest.js`
`language/expressions/class/gen-method-static/rest-params-trailing-comma-early-error.js`
`language/statements/class/dstr/meth-static-dflt-ary-ptrn-rest-not-final-obj.js` | | `accept/await-yield-identifier-reference`: `await` / `yield` as an identifier reference or a label where the context forbids it | 53 | 53 | grammar bug: fix | `language/expressions/assignment/dstr/obj-id-identifier-yield-expr.js`
`language/expressions/class/elements/async-gen-private-method/yield-as-label-identifier.js`
`language/statements/class/async-gen-method-static/yield-as-label-identifier.js` | | `accept/import-export-not-top-level`: an import / export declaration inside a statement or expression | 52 | 52 | grammar bug: fix | `language/module-code/parse-err-decl-pos-export-arrow-function.js`
`language/module-code/parse-err-decl-pos-export-object-method.js`
`language/module-code/parse-err-decl-pos-import-class-expr-meth-gen.js` | -| `accept/for-in-of-initializer`: an initializer in a for-in / for-of head | 32 | 32 | grammar bug: fix | `language/block-scope/syntax/for-in/disallow-initialization-assignment.js`
`language/statements/for-await-of/head-let-init.js`
`language/statements/for-of/head-await-using-init.js` | +| `accept/for-in-of-initializer`: an initializer in a for-in / for-of head | 31 | 31 | grammar bug: fix | `language/block-scope/syntax/for-in/disallow-initialization-assignment.js`
`language/statements/for-await-of/head-let-init.js`
`language/statements/for-of/dstr/var-obj-ptrn-init-err.js` | | `accept/using-binding-pattern`: a binding pattern in a `using` / `await using` declaration list | 7 | 7 | grammar bug: fix | `language/statements/await-using/syntax/await-using-invalid-arraybindingpattern-after-bindingidentifier.js`
`language/statements/await-using/syntax/await-using-invalid-objectbindingpattern.js`
`language/statements/using/syntax/using-invalid-arraybindingpattern.js` | | `accept/declaration-in-statement-position`: a declaration where only a Statement may stand | 6 | 6 | grammar bug: fix | `language/statements/await-using/syntax/with-initializer-case-expression-statement-list.js`
`language/statements/const/syntax/without-initializer-case-expression-statement-list.js`
`language/statements/using/syntax/with-initializer-case-expression-statement-list.js` | | `accept/restricted-production-line-break`: a line break where a production says [no LineTerminator here] | 6 | 6 | grammar bug: fix | `language/asi/S7.9_A4.js`
`language/expressions/arrow-function/syntax/early-errors/asi-restriction-invalid-parenless-parameters.js`
`language/expressions/async-arrow-function/early-errors-arrow-formals-lineterminator.js` | | `accept/coalesce-mixed-with-logical`: `??` mixed with `&&` / `\|\|` without parentheses | 4 | 4 | grammar bug: fix | `language/expressions/coalesce/cannot-chain-head-with-logical-and.js`
`language/expressions/coalesce/cannot-chain-head-with-logical-or.js`
`language/expressions/coalesce/cannot-chain-tail-with-logical-and.js` | | `accept/accessor-parameters`: a getter with a parameter | 3 | 3 | grammar bug: fix | `language/expressions/class/getter-param-dflt.js`
`language/expressions/object/getter-param-dflt.js`
`language/statements/class/getter-param-dflt.js` | -| `accept/in-operator-in-for-init`: `in` inside a for-statement initializer's nested expression | 3 | 3 | grammar bug: fix | `language/expressions/conditional/in-branch-2.js`
`language/expressions/yield/in-iteration-stmt.js`
`language/expressions/yield/star-in-iteration-stmt.js` | | `accept/numeric-literal-lexical`: a numeric literal the lexical grammar does not derive | 3 | 3 | grammar bug: fix | `language/literals/numeric/numeric-separators/numeric-separator-literal-dil-dot-nsl-dd-err.js`
`language/literals/numeric/numeric-separators/numeric-separator-literal-dil-dot-nsl-ep-err.js`
`language/literals/numeric/numeric-separators/numeric-separator-literal-dil-dot-nsl-err.js` | | `accept/switch-statement-outside-clause`: a statement in a switch body before any `case` | 1 | 1 | grammar bug: fix | `language/statements/switch/S12.11_A3_T5.js` | | `accept/strict-mode`: strict mode code | 397 | 397 | needs a parameterised production the engine lacks (roadmap item 4) | `language/arguments-object/10.5-1gs.js`
`language/expressions/function/name-arguments-strict.js`
`language/statements/class/elements/gen-private-method/yield-identifier-spread-strict.js` | @@ -136,7 +135,7 @@ run); where it does not, the rule is outside even its syntactic layer. | verdict | files | |---|---:| -| grammar bug: fix | 515 | +| grammar bug: fix | 511 | | needs a parameterised production the engine lacks (roadmap item 4) | 442 | | early error: a checker over the tree, not the grammar: not built | 1935 | @@ -149,7 +148,6 @@ run); where it does not, the rule is outside even its syntactic layer. - `accept/restricted-production-line-break` — `throw⏎1`, `x⏎=> 1`, `async x⏎=> 1`: the restricted productions forbid the line break, and no ASI applies. - `accept/coalesce-mixed-with-logical` — `0 && 0 ?? true`, `a ?? b || c`: CoalesceExpression's operands are BitwiseORExpressions, so neither side may be a bare `&&` / `||`. - `accept/accessor-parameters` — `get x(a) {}`: a getter's parameter list is `( )`; a setter has exactly one PropertySetParameterList. -- `accept/in-operator-in-for-init` — `for (true ? 0 : 0 in {};;)`: the initializer is an Expression[~In] and ConditionalExpression passes ?In to both branches. - `accept/numeric-literal-lexical` — `1._5`, `1._e1`: the literal is the longest one (`1.`), and an IdentifierStart may not follow it; the token backs up to `1` and lexes `._5` as a member. Refusing the back-up makes these lex errors, after which the portable lexers' relex of an edit before the error keeps it (`x = 1._x;` with `.` inserted: edited rejects, fresh accepts): owed to the lexer lane. - `accept/switch-statement-outside-clause` — `switch (x) { a = 2; case 0: }`: a CaseBlock holds CaseClauses and a DefaultClause only; the grammar's SwitchCase rule has a bare Stmt arm. - `accept/strict-mode` — Valid in sloppy mode, an error in strict code (reserved words `let` / `static` / `implements` / `yield` …, `with`, legacy octal literals and escapes, `delete x`, `eval` / `arguments` as targets or bindings, duplicate parameters, Annex B's `if (x) function f() {}`; class bodies are strict). Without a strict mode switch the grammar accepts the sloppy reading. @@ -239,9 +237,9 @@ declarations, labels, which tsc reports outside its parser; it includes TypeScri | parser | right | of 24677 | on the 20200 valid tests | on the 4477 parse-negative tests | |---|---:|---:|---:|---:| -| `javascript.ts` (interpreter) | 21773 | 88.2% | 20188 (99.9%) | 1585 (35.4%) | +| `javascript.ts` (interpreter) | 21777 | 88.2% | 20188 (99.9%) | 1589 (35.5%) | | acorn 8.16.0 | 24394 | 98.9% | 19926 (98.6%) | 4468 (99.8%) | | tsc 5.9.3 parser | 21391 | 86.7% | 20123 (99.6%) | 1268 (28.3%) | | tsc 5.9.3 parser + binder | 21829 | 88.5% | 19934 (98.7%) | 1895 (42.3%) | -Of the 2892 WE-ACCEPT files, acorn also accepts 0 (in every run), tsc's parser 2529, tsc's parser + binder 1902. +Of the 2888 WE-ACCEPT files, acorn also accepts 0 (in every run), tsc's parser 2528, tsc's parser + binder 1901. diff --git a/docs/decisions/javascript.md b/docs/decisions/javascript.md index 7cdc0855..dae25ed8 100644 --- a/docs/decisions/javascript.md +++ b/docs/decisions/javascript.md @@ -93,7 +93,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `?`: one token: led_question (takes a builder checkpoint: led_question: it can fail after `Expr`) - `instanceof`: one token: led_instanceof (takes a builder checkpoint: led_instanceof: a call of Expr can fail after its operand (an operator that requires an assignment target)) - `in`: one token: led_in (takes a builder checkpoint: led_in: a call of Expr can fail after its operand (an operator that requires an assignment target)) @@ -112,7 +112,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - Expr NUD / array: `opt(Expr)`: by attempt; takes a mark: a call of Expr can fail after its operand (an operator that requires an assignment target) - Expr NUD / array: `opt(Expr)`: by attempt; takes a mark: a call of Expr can fail after its operand (an operator that requires an assignment target) - Expr NUD / paren: `many((',' Expr))`: one token; takes a mark: it can fail after `','` -- Expr NUD / import_: `alt('(' !{'...'} Expr opt(',' opt(!{'...'} Expr opt(…))…`: one token; takes a mark: branch 0: it can fail after `'('`; branch 1: it can fail after `'.'` +- Expr NUD / import_: `alt('(' !{'...'} Expr opt(',' opt(… … …)) ')' \| '.' alt…`: one token; takes a mark: branch 0: it can fail after `'('`; branch 1: it can fail after `'.'` - Expr NUD / import_: `opt(!{'...'} Expr opt(','))`: by attempt; takes a mark: it can fail after `Expr` - Expr NUD / import_: `alt('meta' \| ('defer'\|'source') '(' !{'...'} Expr opt('…`: one token; takes a mark: branch 1: it can fail after `('defer'\|'source')` - Expr NUD / import_: `opt(!{'...'} Expr opt(','))`: by attempt; takes a mark: it can fail after `Expr` @@ -189,9 +189,9 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - longest match: a candidate frame (a mark per new best) at `async`, `function`, `new`, every token of a kind no case names, over ident (#4), newDotTarget (#14), new_ (#16), template (#17), function_ (#20), generator (#21) and 2 more - NewTarget LED (2 connectors, 0 binary operators): - `.`: one token: led_dot - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - one token, no mark: 1 inline choice, 1 star, 1 sep -- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((',' Expr)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` +- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((… …)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` - NewTarget NUD / superMember: `many((',' Expr))`: one token; takes a mark: it can fail after `','` - NewTarget NUD / new_: `opt('(' sep(Expr, ',') ')')`: one token; takes a mark: it can fail after `'('` - NewTarget NUD / new_: `sep(Expr, ',')`: by attempt @@ -218,7 +218,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - ClassHeritage LED (4 connectors, 0 binary operators): - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - one token, no mark: 1 inline choice, 1 star - ClassHeritage NUD / class_: `opt(!{'break'\|'case'\|'catch'\|'class'\|…32} Ident)`: by attempt diff --git a/docs/decisions/javascriptreact.md b/docs/decisions/javascriptreact.md index 54562152..011e7c27 100644 --- a/docs/decisions/javascriptreact.md +++ b/docs/decisions/javascriptreact.md @@ -94,7 +94,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `?`: one token: led_question (takes a builder checkpoint: led_question: it can fail after `Expr`) - `instanceof`: one token: led_instanceof (takes a builder checkpoint: led_instanceof: a call of Expr can fail after its operand (an operator that requires an assignment target)) - `in`: one token: led_in (takes a builder checkpoint: led_in: a call of Expr can fail after its operand (an operator that requires an assignment target)) @@ -113,7 +113,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - Expr NUD / array: `opt(Expr)`: by attempt; takes a mark: a call of Expr can fail after its operand (an operator that requires an assignment target) - Expr NUD / array: `opt(Expr)`: by attempt; takes a mark: a call of Expr can fail after its operand (an operator that requires an assignment target) - Expr NUD / paren: `many((',' Expr))`: one token; takes a mark: it can fail after `','` -- Expr NUD / import_: `alt('(' !{'...'} Expr opt(',' opt(!{'...'} Expr opt(…))…`: one token; takes a mark: branch 0: it can fail after `'('`; branch 1: it can fail after `'.'` +- Expr NUD / import_: `alt('(' !{'...'} Expr opt(',' opt(… … …)) ')' \| '.' alt…`: one token; takes a mark: branch 0: it can fail after `'('`; branch 1: it can fail after `'.'` - Expr NUD / import_: `opt(!{'...'} Expr opt(','))`: by attempt; takes a mark: it can fail after `Expr` - Expr NUD / import_: `alt('meta' \| ('defer'\|'source') '(' !{'...'} Expr opt('…`: one token; takes a mark: branch 1: it can fail after `('defer'\|'source')` - Expr NUD / import_: `opt(!{'...'} Expr opt(','))`: by attempt; takes a mark: it can fail after `Expr` @@ -190,9 +190,9 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - longest match: a candidate frame (a mark per new best) at `async`, `function`, `new`, every token of a kind no case names, over ident (#4), newDotTarget (#14), new_ (#16), template (#17), function_ (#20), generator (#21) and 2 more - NewTarget LED (2 connectors, 0 binary operators): - `.`: one token: led_dot - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - one token, no mark: 1 inline choice, 1 star, 1 sep -- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((',' Expr)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` +- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((… …)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` - NewTarget NUD / superMember: `many((',' Expr))`: one token; takes a mark: it can fail after `','` - NewTarget NUD / new_: `opt('(' sep(Expr, ',') ')')`: one token; takes a mark: it can fail after `'('` - NewTarget NUD / new_: `sep(Expr, ',')`: by attempt @@ -219,7 +219,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - ClassHeritage LED (4 connectors, 0 binary operators): - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - one token, no mark: 1 inline choice, 1 star - ClassHeritage NUD / class_: `opt(!{'break'\|'case'\|'catch'\|'class'\|…32} Ident)`: by attempt diff --git a/docs/decisions/typescript.md b/docs/decisions/typescript.md index 5ec39979..19da6f4a 100644 --- a/docs/decisions/typescript.md +++ b/docs/decisions/typescript.md @@ -228,7 +228,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `!`: one token: led_bang - `?`: one token: led_question (takes a builder checkpoint: led_question: it can fail after `Expr`) - `as`: one token: led_as @@ -507,10 +507,10 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - longest match: a candidate frame (a mark per new best) at `async`, `function`, `import`, `new`, every token of a kind no case names, over ident (#4), newDotTarget (#13), importMeta (#14), new_ (#15), template (#16), function_ (#19) and 3 more - NewTarget LED (3 connectors, 0 binary operators): - `.`: one token: led_dot - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `<`: one token: led_lt (takes a builder checkpoint: led_lt: it can fail after `sep(Type, ',')`) - one token, no mark: 1 inline choice, 1 star, 5 opt, 1 sep -- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((',' Expr)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` +- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((… …)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` - NewTarget NUD / superMember: `many((',' Expr))`: one token; takes a mark: it can fail after `','` - NewTarget NUD / new_: `alt('<' sep(Type, ',') !(alt('>>' \| '>=' \| '>>=' \| '>>>…`: one token; takes a mark: branch 0: it can fail after `'<'`; branch 1: it can fail after `'('` - NewTarget NUD / new_: `sep(Type, ',')`: by attempt @@ -549,7 +549,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - ClassHeritage LED (5 connectors, 0 binary operators): - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `<`: one token: led_lt (takes a builder checkpoint: led_lt: it can fail after `sep(Type, ',')`) - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - one token, no mark: 1 inline choice, 1 star, 2 opt diff --git a/docs/decisions/typescriptreact.md b/docs/decisions/typescriptreact.md index d21c4926..43f719a3 100644 --- a/docs/decisions/typescriptreact.md +++ b/docs/decisions/typescriptreact.md @@ -228,7 +228,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `!`: one token: led_bang - `?`: one token: led_question (takes a builder checkpoint: led_question: it can fail after `Expr`) - `as`: one token: led_as @@ -507,10 +507,10 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - longest match: a candidate frame (a mark per new best) at `async`, `function`, `import`, `new`, every token of a kind no case names, over ident (#4), newDotTarget (#13), importMeta (#14), new_ (#15), template (#16), function_ (#19) and 3 more - NewTarget LED (3 connectors, 0 binary operators): - `.`: one token: led_dot - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `<`: one token: led_lt (takes a builder checkpoint: led_lt: it can fail after `sep(Type, ',')`) - one token, no mark: 1 inline choice, 1 star, 5 opt, 1 sep -- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((',' Expr)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` +- NewTarget NUD / superMember: `alt('.' Ident \| '[' Expr many((… …)) ']')`: one token; takes a mark: branch 0: it can fail after `'.'`; branch 1: it can fail after `'['` - NewTarget NUD / superMember: `many((',' Expr))`: one token; takes a mark: it can fail after `','` - NewTarget NUD / new_: `alt('<' sep(Type, ',') !(alt('>>' \| '>=' \| '>>=' \| '>>>…`: one token; takes a mark: branch 0: it can fail after `'<'`; branch 1: it can fail after `'('` - NewTarget NUD / new_: `sep(Type, ',')`: by attempt @@ -549,7 +549,7 @@ Per rule: its candidate lists (every key and what decides it), then the inline c - ClassHeritage LED (5 connectors, 0 binary operators): - `.`: one token: led_dot - `?.`: one token: led_optChain - - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr`) + - `[`: one token: led_bracket (takes a builder checkpoint: led_bracket: it can fail after `Expr many((',' Expr))`) - `<`: one token: led_lt (takes a builder checkpoint: led_lt: it can fail after `sep(Type, ',')`) - `(`: one token: led_paren (takes a builder checkpoint: led_paren: it can fail after `sep(Expr, ',')`) - one token, no mark: 1 inline choice, 1 star, 2 opt diff --git a/docs/emit-sizes.json b/docs/emit-sizes.json index 7c49b1f8..2120cd74 100644 --- a/docs/emit-sizes.json +++ b/docs/emit-sizes.json @@ -1,47 +1,47 @@ { "typescript": { - "ts": 281120, - "ts+recovery": 325868, - "js": 587762, - "go": 508048, - "go+recovery": 552587, - "rust": 366231, - "rust+recovery": 425529 + "ts": 281518, + "ts+recovery": 326385, + "js": 590355, + "go": 508534, + "go+recovery": 553179, + "rust": 365667, + "rust+recovery": 425162 }, "javascript": { - "ts": 199390, - "ts+recovery": 238613, - "js": 391766, - "go": 339083, - "go+recovery": 377322, - "rust": 273220, - "rust+recovery": 326659 + "ts": 200769, + "ts+recovery": 240097, + "js": 393657, + "go": 341504, + "go+recovery": 379813, + "rust": 273787, + "rust+recovery": 327393 }, "typescriptreact": { - "ts": 313771, - "ts+recovery": 358886, - "js": 608853, - "go": 542620, - "go+recovery": 587565, - "rust": 402873, - "rust+recovery": 462502 + "ts": 314169, + "ts+recovery": 359409, + "js": 611449, + "go": 543106, + "go+recovery": 588163, + "rust": 402309, + "rust+recovery": 462141 }, "javascriptreact": { - "ts": 214563, - "ts+recovery": 254229, - "js": 410461, - "go": 358912, - "go+recovery": 397673, - "rust": 288790, - "rust+recovery": 342729 + "ts": 215942, + "ts+recovery": 255711, + "js": 412356, + "go": 361333, + "go+recovery": 400162, + "rust": 289357, + "rust+recovery": 343461 }, "textdialect": { - "ts": 96425, - "ts+recovery": 129571, - "js": 182217, - "go": 137018, - "go+recovery": 168302, - "rust": 154190, - "rust+recovery": 199406 + "ts": 96083, + "ts+recovery": 129134, + "js": 181640, + "go": 136675, + "go+recovery": 167763, + "rust": 153536, + "rust+recovery": 198649 } } diff --git a/javascript.ts b/javascript.ts index 1da593a4..88d46600 100644 --- a/javascript.ts +++ b/javascript.ts @@ -28,12 +28,43 @@ import { token, rule, defineGrammar, left, right, none, noUnaryLhs, lhsAssignTarget, prefixAssignTarget, postfixAssignTarget, op, prefix, postfix, sameLine, - sep, opt, many, many1, alt, exclude, not, reservableNot, capExpr, treeSitterRelax, arm, field, - awaitCtx, yieldCtx, asyncGenCtx, resetCtx, when, + sep, opt, many, many1, alt, not, capExpr, atLevel, treeSitterRelax, arm, field, + ctx, when, altPattern, optPattern, seq, oneOf, noneOf, range, anyChar, star, plus, repeat, notFollowedBy, start, type Element, type Alternative, } from './src/api.ts'; +// ── Contexts (docs/GRAMMAR.md "Contexts") ── +// The grammar parameters: [Await], [Yield], [In], and `syncFn`, a transition until the goals land +// (src/grammar/grammar-utils.ts). Each is its value at the top level of a Script. +export const jsParams = { await: false, yield: false, syncFn: false, in: true } as const; +// A function's parameters and body (FormalParameters[?Yield, ?Await], FunctionBody[?Yield, ?Await]; +// what they hold is [+In]): each kind fixes every parameter. `syncFn` holds where `await` is the +// operator in no goal. +const fnEqs = { + plain: { await: false, yield: false, syncFn: true, in: true }, + generator: { await: false, yield: true, syncFn: true, in: true }, + async: { await: true, yield: false, syncFn: false, in: true }, + asyncGenerator: { await: true, yield: true, syncFn: false, in: true }, +} as const; +export const fnCtx = { + plain: (...items: Element[]) => ctx(fnEqs.plain, ...items), + generator: (...items: Element[]) => ctx(fnEqs.generator, ...items), + async: (...items: Element[]) => ctx(fnEqs.async, ...items), + asyncGenerator: (...items: Element[]) => ctx(fnEqs.asyncGenerator, ...items), +}; +// An arrow's body: ConciseBody[?In] (it keeps the reference's [In]: `for (x => x in y;;)` has no +// parse), [~Yield], and [Await] as the arrow's. +export const arrowBodyCtx = { + plain: (...items: Element[]) => ctx({ await: false, yield: false, syncFn: true }, ...items), + async: (...items: Element[]) => ctx({ await: true, yield: false, syncFn: false }, ...items), +}; +// [+In]: what the spec reads with `in` allowed whatever the reference's [In] (an expression in +// brackets, a template substitution, a property, a conditional's middle operand, a block). +export const inCtx = (...items: Element[]) => ctx({ in: true }, ...items); +// [~In]: a for-head's first expression or initializer (`for (a in b;;)` reads no `in` operator). +export const noInCtx = (...items: Element[]) => ctx({ in: false }, ...items); + // Build the four async×generator arms of a `function` form, routing each arm's params // and body to its [Await]/[Yield] family: plain resets to none, generator -> yield, // async -> await, async-generator -> both. `nameParts` is spread in after `function` @@ -43,10 +74,10 @@ import { // resolve at thunk-eval time (defined below), so this is safe to call inside a rule(). function fnArms(nameParts: Element[], body: Element) { return [ - arm('function_', 'function', ...nameParts, '(', sep(resetCtx(field('parameter', Param)), ','), ')', resetCtx(field('body', body))), - arm('generator', 'function', field('asterisk', '*'), ...nameParts, '(', sep(yieldCtx(field('parameter', Param)), ','), ')', yieldCtx(field('body', body))), - arm('asyncFunction', field('asyncKeyword', 'async'), sameLine, 'function', ...nameParts, '(', sep(awaitCtx(field('parameter', Param)), ','), ')', awaitCtx(field('body', body))), - arm('asyncGenerator', field('asyncKeyword', 'async'), sameLine, 'function', field('asterisk', '*'), ...nameParts, '(', sep(asyncGenCtx(field('parameter', Param)), ','), ')', asyncGenCtx(field('body', body))), + arm('function_', 'function', ...nameParts, '(', sep(fnCtx.plain(field('parameter', Param)), ','), ')', fnCtx.plain(field('body', body))), + arm('generator', 'function', field('asterisk', '*'), ...nameParts, '(', sep(fnCtx.generator(field('parameter', Param)), ','), ')', fnCtx.generator(field('body', body))), + arm('asyncFunction', field('asyncKeyword', 'async'), sameLine, 'function', ...nameParts, '(', sep(fnCtx.async(field('parameter', Param)), ','), ')', fnCtx.async(field('body', body))), + arm('asyncGenerator', field('asyncKeyword', 'async'), sameLine, 'function', field('asterisk', '*'), ...nameParts, '(', sep(fnCtx.asyncGenerator(field('parameter', Param)), ','), ')', fnCtx.asyncGenerator(field('body', body))), ]; } @@ -155,7 +186,7 @@ const Template = token(seq('`', star(altPattern(noneOf('`', '\\', '$'), seq( // Same well-formed-escape rule as strings; the lexer rejects a malformed `\u`/`\x` // in an *untagged* template (`\u{110000}`, `\u{r}`), but allows it when tagged. escapeValid: escape, - template: { open: '`', interpOpen: '${', interpClose: '}' }, + template: { open: '`', interpOpen: '${', interpClose: '}', holeCtx: { in: true } }, // SubstitutionTemplate: TemplateHead Expression[+In] … }); const regexEscape = seq('\\', noneOf(lineTerminator)); const regexClassBody = star(altPattern(noneOf(']', '\\', lineTerminator), regexEscape)); @@ -229,7 +260,7 @@ export const expressionStatement = (Expr: Element) => [ ]; // An arrow's body (`ConciseBody : [lookahead ≠ {] ExpressionBody | { FunctionBody }`): after `=>` // a `{` begins the function body, never an object literal, so `() => { b() {} }.x` has no parse. -export const conciseBody = (Block: Element, Expr: Element) => alt(arm('block', Block), arm('expression', not('{'), Expr)); +export const conciseBody = (Block: Element, Expr: Element) => alt(arm('block', inCtx(Block)), arm('expression', not('{'), Expr)); // `export Declaration` / `export VariableStatement` (16.2.3 ExportDeclaration): what follows // `export` is a declaration, never another statement, so `export if (x) {}`, `export x;`, // `export ;`, `export let: x;` (a labelled statement), `export let.x = 1;` (an expression) have @@ -303,7 +334,7 @@ export const bindingName = [notReserved, field('name', Ident)]; // spec's `[lookahead ≠ using of]` and `using` as an identifier then fails, so the guard is that // triple; `for (using of ;…)` (a binding named `of`) and `for (await using of of …)` stay valid. export const forBindingArms = (BindingPattern: Element, Expr: Element, annotation: Element[] = []) => [ - [field('name', alt(bindingIdentifier, BindingPattern)), ...annotation, opt('=', exclude('in', field('value', Expr)))], + [field('name', alt(bindingIdentifier, BindingPattern)), ...annotation, opt('=', noInCtx(field('value', Expr)))], ]; // `tails` are what may follow the first binding of a `var` / `let` / `const` declaration and of a // `using` one: both grammars' heads parse it once and then branch. @@ -315,27 +346,31 @@ const forDeclaration = (ForBinding: Element, tails: Alternative[], usingTails: A // - `for ( [lookahead ≠ let [] Expression[~In]opt ; Expression opt ; Expression opt )` and the // declared C-style head: a first expression or initializer reads no `in` operator, so `for (a = // b in c;;)` has no parse (each comma operand is its own [~In] Pratt call); -// - `for ( [lookahead ≠ let [] LeftHandSideExpression in Expression )`: the left side reads no `in` -// either, so the `in` is the head's (`for (key in obj)`); the object is a full Expression; +// - `for ( [lookahead ≠ let [] LeftHandSideExpression in Expression )`: the left side (`left`) is a +// LeftHandSideExpression, so the `in` is the head's (`for (key in obj)`) and `for (a + b in c)`, +// `for (a ? b : c in d)` have no parse; the object is a full Expression; // - `for ( [lookahead ∉ { let, async of }] LeftHandSideExpression of AssignmentExpression )`: no // comma after `of`; `for (async of => {};;)` is a C-style head; // - a declaration before `in` / `of` has one binding. -export const forHeadArms = (Expr: Element, ForBinding: Element) => { +// `left`: the left side of a for-in / for-of head: JavaScript's reads a LeftHandSideExpression +// (`atLevel` at the postfix operators' level: no binary or conditional operator, assignment or arrow +// continues it); TypeScript's, as tsc's parser, an expression with no `in` operator (noInCtx). +export const forHeadArms = (Expr: Element, ForBinding: Element, left: Element) => { const cTail = [';', opt(field('condition', Expr), many(field('conditionComma', ','), field('conditionRest', Expr))), ';', opt(field('increment', Expr), many(field('incrementComma', ','), field('incrementRest', Expr)))]; // `; cond ; update` const cStyle = arm('classic', many(field('bindingComma', ','), field('bindingRest', ForBinding)), ...cTail); const forIn = arm('in_', 'in', field('right', Expr), many(field('rightComma', ','), field('rightRest', Expr))), forOf = arm('of', 'of', field('right', Expr)); return [ arm('declaration', forDeclaration(ForBinding, [cStyle, forIn, forOf], [cStyle, forOf])), - arm('classic', not(['let', '[']), opt(exclude('in', field('initializer', Expr)), many(field('initializerComma', ','), exclude('in', field('initializerRest', Expr)))), ...cTail), - arm('in_', not(['let', '[']), exclude('in', field('left', Expr)), 'in', field('right', Expr), many(field('rightComma', ','), field('rightRest', Expr))), - arm('of', not(alt('let', ['async', 'of'])), exclude('in', field('left', Expr)), 'of', field('right', Expr)), + arm('classic', not(['let', '[']), opt(noInCtx(field('initializer', Expr)), many(field('initializerComma', ','), noInCtx(field('initializerRest', Expr)))), ...cTail), + arm('in_', not(['let', '[']), left, 'in', field('right', Expr), many(field('rightComma', ','), field('rightRest', Expr))), + arm('of', not(alt('let', ['async', 'of'])), left, 'of', field('right', Expr)), ]; }; // The head inside `for await ( … )`: only the `of` forms, and its left side's lookahead is // `[lookahead ≠ let]` alone, so `for await (async of x)` is a loop over `x`. -export const forAwaitHeadArms = (Expr: Element, ForBinding: Element) => [ +export const forAwaitHeadArms = (Expr: Element, ForBinding: Element, left: Element) => [ arm('declaration', forDeclaration(ForBinding, [arm('of', 'of', field('right', Expr))], [arm('of', 'of', field('right', Expr))])), - arm('of', not('let'), exclude('in', field('left', Expr)), 'of', field('right', Expr)), + arm('of', not('let'), left, 'of', field('right', Expr)), ]; export const forStatement = ($: Element, ForHead: Element, ForAwaitHead: Element) => ['for', alt(['(', field('head', ForHead), ')'], [field('awaitKeyword', 'await'), '(', field('head', ForAwaitHead), ')']), field('body', $)]; @@ -347,24 +382,26 @@ export const forStatement = ($: Element, ForHead: Element, ForAwaitHead: Element // expression of its own (`this`, `true` / `false` / `null`, `super.x`, `new X`) is that // expression's arm alone, never also an identifier (no tie for declaration order to decide) and // never an arrow's parameter (`true => 1`, `this => 1`, `super => 1`). `undefined` is no reserved -// word: an ordinary identifier. Reservable: it also refuses the context's operator words -// (`await` / `yield`). TypeScript's guard leaves `import` out: `import` with no or a spread +// word: an ordinary identifier. It also refuses the context's operator words (IdentifierReference +// `[~Await] await`, `[~Yield] yield`: ctxReservedWords). TypeScript's guard leaves `import` out: `import` with no or a spread // argument (`import()`, `import(...a)`) is read through this fallback, as tsc's parser does in // files it accepts. Owed: that `import` is tsc-parser tolerance, not the productions. -export const notReservedExpr = reservableNot(alt(...reservedWords.filter((w) => w !== 'import'))); +// The words an identifier is not where the context makes them operators. +export const ctxReservedWords = [when('+await', 'await'), when('+yield', 'yield')]; +export const notReservedExpr = not(alt(...reservedWords.filter((w) => w !== 'import'), ...ctxReservedWords)); // JavaScript's: `import` is an expression only as ImportCall and `import.meta` (13.3.10 // `ImportCall : import ( AssignmentExpression ,opt ) | import ( AssignmentExpression , // AssignmentExpression ,opt )`), so `import()`, `import(a, b, c)` and `import(...a)` have no parse. -const notReservedJsExpr = reservableNot(alt(...reservedWords)); +const notReservedJsExpr = not(alt(...reservedWords, ...ctxReservedWords)); // A computed member's index (13.3 `MemberExpression : MemberExpression [ Expression ]`, `SuperProperty // : super [ Expression ]`, `OptionalChain : ?. [ Expression ]`): an Expression, so a comma list // (`a[0, 1]`, `a?.[0, 1]`); each operand is its own AssignmentExpression call. -export const bracketIndex = (E: Element) => ['[', E, many(field('exprComma', ','), field('exprRest', E)), ']']; +export const bracketIndex = (E: Element) => ['[', inCtx(E, many(field('exprComma', ','), field('exprRest', E))), ']']; // ImportCall's arguments (`( AssignmentExpression ,opt )`, `( AssignmentExpression , // AssignmentExpression ,opt )`): no spread, no empty list. -const importCallArgs = ($: Element) => ['(', not('...'), field('source', $), opt(',', opt(not('...'), field('options', $), opt(','))), ')']; +const importCallArgs = ($: Element) => ['(', inCtx(not('...'), field('source', $), opt(',', opt(not('...'), field('options', $), opt(',')))), ')']; // ── Precedence ladder (shared ECMAScript operator precedence) ── @@ -374,7 +411,7 @@ const importCallArgs = ($: Element) => ['(', not('...'), field('source', $), opt // their right operand like the ladder relationals they are. export const jsLedPrecs = [ { connector: '?', below: '??' }, - { connector: 'in', sameAs: '<', chainRhs: true }, + { connector: 'in', sameAs: '<', chainRhs: true, when: '+in' }, // [+In] RelationalExpression in ShiftExpression { connector: 'instanceof', sameAs: '<', chainRhs: true }, ]; @@ -432,8 +469,8 @@ const jsPrec = ecmaPrecWith(when('~syncFn', 'await')); // (`@a . b`, `@a.℘`; `@a.` has no parse). const decoratorHead = alt(Decorator, ['@', notReservedJsExpr, Ident]); const DecoratorExpr = rule(() => [ - ['@', '(', Expr, many(',', Expr), ')'], // @(expr) - [decoratorHead, many('.', alt(Ident, PrivateField)), opt('(', sep(Expr, ','), ')')], // @dec | @a.b.#c | @dec(args) + ['@', '(', inCtx(Expr, many(',', Expr)), ')'], // @(expr) + [decoratorHead, many('.', alt(Ident, PrivateField)), opt('(', inCtx(sep(Expr, ',')), ')')], // @dec | @a.b.#c | @dec(args) ]); // ── Expressions ── @@ -445,12 +482,12 @@ const Prop = rule(() => { return [ arm('spread', '...', field('argument', Expr)), // accessor (get/set) — get/set bodies are plain (reset) - arm('accessor', field('kind', alt('get', 'set')), field('key', MemberName), field('paren', '('), opt(sep(resetCtx(field('parameter', Param)), ',')), ')', resetCtx(field('body', Block))), + arm('accessor', field('kind', alt('get', 'set')), field('key', MemberName), field('paren', '('), opt(sep(fnCtx.plain(field('parameter', Param)), ',')), ')', fnCtx.plain(field('body', Block))), // method, 4-way split on async × generator (each routes params+body to its family) - arm('asyncGeneratorMethod', 'async', '*', field('key', MemberName), ...propTail(asyncGenCtx)), - arm('asyncMethod', 'async', field('key', MemberName), ...propTail(awaitCtx)), - arm('generatorMethod', '*', field('key', MemberName), ...propTail(yieldCtx)), - arm('method', field('key', MemberName), ...propTail(resetCtx)), + arm('asyncGeneratorMethod', 'async', '*', field('key', MemberName), ...propTail(fnCtx.asyncGenerator)), + arm('asyncMethod', 'async', field('key', MemberName), ...propTail(fnCtx.async)), + arm('generatorMethod', '*', field('key', MemberName), ...propTail(fnCtx.generator)), + arm('method', field('key', MemberName), ...propTail(fnCtx.plain)), // value property — any member name incl computed `[e]: v` (MemberName covers `[Expr]`) arm('init', field('key', MemberName), ':', field('value', Expr)), // computed comma list (lenient): `[a, b]: v`. One expression in the brackets is the @@ -539,7 +576,7 @@ const Expr = rule($ => [ 'true', 'false', 'null', 'this', // `super` is a CONSTRAINED primary (mirrors tsc's parseSuperExpression): MUST be // immediately followed by a call `(args)`, member `.name`/`.#priv`, or element `[expr]`. - [field('superKeyword', 'super'), alt(['(', sep($, ','), ')'], ['.', alt(Ident, PrivateField)], bracketIndex($))], + [field('superKeyword', 'super'), alt(['(', inCtx(sep($, ',')), ')'], ['.', alt(Ident, PrivateField)], bracketIndex($))], // A standalone identifier expression (IdentifierReference): never a reserved word (see // notReservedExpr), so `catch(x){}` with no `try`, `void ;` and `throw ;` are no expression. [notReservedJsExpr, Ident], @@ -554,7 +591,7 @@ const Expr = rule($ => [ // `x; ++y`, and `x\n++\n++\ny` is `x; ++ ++y` (rejected by the prefix target check). [$, sameLine, postfix], ['...', $], - [$, '(', sep($, ','), ')'], + [$, '(', inCtx(sep($, ',')), ')'], [$, '.', alt(Ident, PrivateField)], // optional chaining: ?.x | ?.#x | ?.(args) | ?.[i] | ?.`…`. A private member `?.#x` IS // valid current ECMAScript (V8 + Babel accept it; tsc's lone parse rejection is a bug being @@ -563,9 +600,9 @@ const Expr = rule($ => [ // Owed: `a?.[0, 1]` (OptionalChain `?. [ Expression ]`): TypeScript's v1 ESTree shape // (test/fixtures/shape-typescript.ts estreeOptionalChain and its Rust stream type) tells this branch // from a call by its kids, so both grammars keep one expression here until that shape names it. - [$, '?.', alt(Ident, PrivateField, ['(', sep($, ','), ')'], ['[', $, ']'], Template)], + [$, '?.', alt(Ident, PrivateField, ['(', inCtx(sep($, ',')), ')'], ['[', inCtx($), ']'], Template)], [$, ...bracketIndex($)], - [$, '?', field('then', $), ':', field('otherwise', $)], + [$, '?', inCtx(field('then', $)), ':', field('otherwise', $)], [$, 'instanceof', $], [$, 'in', $], [$, Template], @@ -577,16 +614,16 @@ const Expr = rule($ => [ // NewExpression is not a valid `?.` base, so `new a?.b` / `new class{}?.x` have no parse tree // (tsc + V8 + babel all reject). `not('?.')` guards the no-call exit; `new a()?.b` chains via // the outer `?.` LED unchanged. - arm('construct', 'new', not('<'), NewTarget, alt(['(', sep($, ','), ')'], not('?.'))), - arm('newNamedClass', 'new', field('classKeyword', 'class'), ...bindingName, opt('extends', field('superClass', ClassHeritage)), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}'), field('newArguments', alt(arm('paren', '(', sep(field('argument', $), ','), ')'), arm('none', not('?.'))))), - arm('newAnonymousClass', 'new', field('classKeyword', 'class'), opt('extends', field('superClass', ClassHeritage)), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}'), field('newArguments', alt(arm('paren', '(', sep(field('argument', $), ','), ')'), arm('none', not('?.'))))), + arm('construct', 'new', not('<'), inCtx(NewTarget), alt(['(', inCtx(sep($, ',')), ')'], not('?.'))), + arm('newNamedClass', 'new', field('classKeyword', 'class'), ...bindingName, opt('extends', inCtx(field('superClass', ClassHeritage))), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}'), field('newArguments', alt(arm('paren', '(', inCtx(sep(field('argument', $), ',')), ')'), arm('none', not('?.'))))), + arm('newAnonymousClass', 'new', field('classKeyword', 'class'), opt('extends', inCtx(field('superClass', ClassHeritage))), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}'), field('newArguments', alt(arm('paren', '(', inCtx(sep(field('argument', $), ',')), ')'), arm('none', not('?.'))))), // array literal `[a, , ...b,]`: an element or a hole, then `,` and an element or a hole, the // ArrayBindingPattern's form. Each element is parsed once: `many(opt($), ','), opt($)` parsed // the last one in the repetition, found no `,`, and parsed it again (twice per nesting level). - arm('array', field('bracket', '['), opt(field('element', $)), many(field('comma', ','), opt(field('elementRest', $))), ']'), - arm('object', '{', sep(field('property', Prop), ','), '}'), + arm('array', field('bracket', '['), inCtx(opt(field('element', $)), many(field('comma', ','), opt(field('elementRest', $)))), ']'), + arm('object', '{', inCtx(sep(field('property', Prop), ',')), '}'), // Arrow functions, async/non-async SPLIT so the [Await] grammar parameter can route - // each arm's params + body to the right context word (awaitCtx / resetCtx): an async + // each arm's params + body to the right context word (fnCtx / arrowBodyCtx): an async // arrow's params and body are await-context (`async (a = await) =>` rejects — await // needs an operand), a plain arrow's body resets to none. // capExpr('?'): an ArrowFunction is the LOWEST-precedence AssignmentExpression — it can be @@ -596,17 +633,17 @@ const Expr = rule($ => [ // `||`/`?:` INSIDE an expression body (`() => a || b`) is unaffected — parsed by the body `$`. // The body is a ConciseBody (`conciseBody`): `() => {}` is a block body, not an object literal // that absorbs a trailing `|| a` / `.x`, also where the block does not parse. - arm('asyncArrow', capExpr('?', field('asyncKeyword', 'async'), '(', sep(awaitCtx(field('parameter', Param)), ','), ')', field('arrow', '=>'), awaitCtx(field('body', conciseBody(Block, $))))), - arm('arrow', capExpr('?', '(', sep(field('parameter', Param), ','), ')', field('arrow', '=>'), resetCtx(field('body', conciseBody(Block, $))))), + arm('asyncArrow', capExpr('?', field('asyncKeyword', 'async'), '(', sep(fnCtx.async(field('parameter', Param)), ','), ')', field('arrow', '=>'), arrowBodyCtx.async(field('body', conciseBody(Block, $))))), + arm('arrow', capExpr('?', '(', inCtx(sep(field('parameter', Param), ',')), ')', field('arrow', '=>'), arrowBodyCtx.plain(field('body', conciseBody(Block, $))))), // async arrow with a BARE parameter: `async err => …` (ES2017). `async` and the // parameter must share a line (`async\nx => …` is `async;` then a plain arrow — // the spec's [no LineTerminator here] between async and the binding identifier). - arm('asyncArrowIdentifier', capExpr('?', field('asyncKeyword', 'async'), sameLine, awaitCtx(notReservedJsExpr, field('parameter', Ident)), field('arrow', '=>'), awaitCtx(field('body', conciseBody(Block, $))))), - arm('arrowIdentifier', capExpr('?', notReservedJsExpr, field('parameter', Ident), field('arrow', '=>'), resetCtx(field('body', conciseBody(Block, $))))), + arm('asyncArrowIdentifier', capExpr('?', field('asyncKeyword', 'async'), sameLine, fnCtx.async(notReservedJsExpr, field('parameter', Ident)), field('arrow', '=>'), arrowBodyCtx.async(field('body', conciseBody(Block, $))))), + arm('arrowIdentifier', capExpr('?', notReservedJsExpr, field('parameter', Ident), field('arrow', '=>'), arrowBodyCtx.plain(field('body', conciseBody(Block, $))))), // YieldExpression is an AssignmentExpression[+Yield] only: elsewhere `yield` is an identifier // (`iter = yield();` calls it; `yield * x = 1` multiplies, then fails as an assignment target). arm('yield_', capExpr('?', when('+yield', 'yield', alt(arm('star', sameLine, '*', $), arm('expr', opt(sameLine, $)))))), // yield e | yield* e (delegate) | yield - ['(', field('first', $), many(field('comma', ','), field('rest', $)), ')'], + ['(', inCtx(field('first', $), many(field('comma', ','), field('rest', $))), ')'], // ImportCall: one or two AssignmentExpressions, no spread (the `...` arm is Arguments'), and ImportMeta. // A phase import call (import defer and source phase imports, Stage 3: `ImportCall : import . // ImportPhase ( AssignmentExpression ,opt )`, and with options as ImportCall) takes the same @@ -626,8 +663,8 @@ const Expr = rule($ => [ // named vs anonymous kept separate (greedy opt(Ident) would eat a leading // `extends`). A ClassExpression takes a DecoratorList, as a ClassDeclaration does: any number // of decorators (`x = @a @b class {}`). - arm('namedClass', many(field('decorator', DecoratorExpr)), 'class', ...bindingName, opt('extends', field('superClass', ClassHeritage)), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}')), - arm('anonymousClass', many(field('decorator', DecoratorExpr)), 'class', opt('extends', field('superClass', ClassHeritage)), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}')), + arm('namedClass', many(field('decorator', DecoratorExpr)), 'class', ...bindingName, opt('extends', inCtx(field('superClass', ClassHeritage))), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}')), + arm('anonymousClass', many(field('decorator', DecoratorExpr)), 'class', opt('extends', inCtx(field('superClass', ClassHeritage))), field('bodyOpen', '{'), many(field('member', ClassMember)), field('bodyClose', '}')), ]); // ── Statements ── @@ -687,8 +724,9 @@ const Param = rule(() => { ]; }); -const ForHead = rule(() => forHeadArms(Expr, ForBinding)); -const ForAwaitHead = rule(() => forAwaitHeadArms(Expr, ForBinding)); +const forLeft = () => noInCtx(field('left', atLevel('++', Expr))); // LeftHandSideExpression (see forHeadArms); [~In] so no operand inside it reads the head's `in` (`for (...a in b)`) +const ForHead = rule(() => forHeadArms(Expr, ForBinding, forLeft())); +const ForAwaitHead = rule(() => forAwaitHeadArms(Expr, ForBinding, forLeft())); const SwitchCase = rule(() => [ ['case', Expr, many(',', Expr), ':'], @@ -769,7 +807,7 @@ const MemberName = rule(() => [ BinaryNumber, BigInt_, LegacyNumber, - arm('computed', field('bracket', '['), field('expr', Expr), field('bracketClose', ']')), + arm('computed', field('bracket', '['), inCtx(field('expr', Expr)), field('bracketClose', ']')), ]); // ── Member words ── @@ -824,26 +862,26 @@ const memTail = (ctx: (...items: Element[]) => Element) => [field('paren', '('), // `constructor` is the constructor (its keyword leaf); with a prefix it is a method named // `constructor`. const memberKinds = [ - arm('accessorField', field('accessorWord', accessorWord), field('key', MemberName), opt('=', resetCtx(field('value', Expr))), asi()), + arm('accessorField', field('accessorWord', accessorWord), field('key', MemberName), opt('=', fnCtx.plain(field('value', Expr))), asi()), arm('async', field('asyncWord', asyncWord), field('form', alt( - arm('generatorMethod', field('asterisk', '*'), field('key', MemberName), ...memTail(asyncGenCtx)), - arm('method', field('key', MemberName), ...memTail(awaitCtx)), + arm('generatorMethod', field('asterisk', '*'), field('key', MemberName), ...memTail(fnCtx.asyncGenerator)), + arm('method', field('key', MemberName), ...memTail(fnCtx.async)), ))), - arm('generatorMethod', field('asterisk', '*'), field('key', MemberName), ...memTail(yieldCtx)), - arm('accessor', field('kind', getSetWord), field('key', MemberName), field('paren', '('), opt(sep(resetCtx(field('parameter', Param)), ',')), ')', resetCtx(field('body', Block))), + arm('generatorMethod', field('asterisk', '*'), field('key', MemberName), ...memTail(fnCtx.generator)), + arm('accessor', field('kind', getSetWord), field('key', MemberName), field('paren', '('), opt(sep(fnCtx.plain(field('parameter', Param)), ',')), ')', fnCtx.plain(field('body', Block))), // Where `get` / `set` is the accessor keyword it is no name (`get⏎x;` has no derivation; the // same-line words cannot end a field before a member start anyway). arm('named', not(getSetWord), field('key', MemberName), field('tail', alt( - arm('method', ...memTail(resetCtx)), // method (requires `(`) + arm('method', ...memTail(fnCtx.plain)), // method (requires `(`) // field; it ends as a statement does - arm('field', opt('=', resetCtx(field('value', Expr))), asi()), + arm('field', opt('=', fnCtx.plain(field('value', Expr))), asi()), ))), ]; const ClassMember = rule(() => [ arm('empty', ';'), // SemicolonClassElement: `class C { ; }` - arm('staticBlock', 'static', awaitCtx(field('body', Block))), // ClassStaticBlock: the body is [+Await] (await reserved) + arm('staticBlock', 'static', fnCtx.async(field('body', Block))), // ClassStaticBlock: the body is [+Await] (await reserved) arm('member', field('form', alt( - arm('constructor', field('constructorKeyword', 'constructor'), ...memTail(resetCtx)), + arm('constructor', field('constructorKeyword', 'constructor'), ...memTail(fnCtx.plain)), arm('element', many(field('decorator', DecoratorExpr)), opt(field('staticWord', staticWord)), field('member', alt(...memberKinds))), ))), ]); @@ -1035,6 +1073,7 @@ export const jsBaseCanonical: Record = { export default defineGrammar({ name: 'javascript', scopeName: 'source.js', + params: jsParams, tokens: { // Comments must come before Regex_ to avoid /** ... */ being matched as regex diff --git a/python.ts b/python.ts index aa605332..115cef4e 100644 --- a/python.ts +++ b/python.ts @@ -18,7 +18,7 @@ import { token, rule, defineGrammar, - left, right, op, prefix, cappedPrefix, atLevel, capExpr, arm, assignTarget, exclude, + left, right, op, prefix, cappedPrefix, atLevel, capExpr, arm, assignTarget, ctx, opt, many, many1, alt, not, altPattern, optPattern, seq, oneOf, noneOf, range, anyChar, star, plus, never, notFollowedBy, type Element, @@ -142,13 +142,16 @@ const StarNamedExpression = rule(() => [arm('starred', '*', BitwiseOr()), NamedE const StarNamedExpressions = rule(() => [arm('starNamedList', StarNamedExpression, many(',', StarNamedExpression), opt(','))]); const YieldExpr = rule(() => [['yield', 'from', Expression], ['yield', opt(StarExpressions)]]); +// What brackets hold reads a comparison `in` again (`for a[b in c] in d:`): the context parameter +// `in`, which a for head's targets clear (ForTargets), is set inside every bracket pair. +const inBrackets = (...items: Element[]) => ctx({ in: true }, ...items); // primary: atom and its trailers. const Primary = rule(($) => [ Atom, arm('attr', $, '.', ...NAME()), - [$, Genexp], - [$, '(', opt(Arguments), ')'], - arm('subscript', $, '[', Slices, ']'), + [$, inBrackets(Genexp)], + [$, '(', inBrackets(opt(Arguments)), ')'], + arm('subscript', $, '[', inBrackets(Slices), ']'), ]); const Slice = rule(() => [ [opt(Expression), ':', opt(Expression), opt(':', opt(Expression))], @@ -162,9 +165,9 @@ const Atom = rule(() => [ 'True', 'False', 'None', '...', Strings, Imaginary, Float, Integer, - Tuple, Group, Genexp, - List, Listcomp, - Dict, Set, Dictcomp, Setcomp, + inBrackets(Tuple), inBrackets(Group), inBrackets(Genexp), + inBrackets(List), inBrackets(Listcomp), + inBrackets(Dict), inBrackets(Set), inBrackets(Dictcomp), inBrackets(Setcomp), ]); const Group = rule(() => [arm('parenExpr', '(', alt(YieldExpr, NamedExpression), ')')]); const Tuple = rule(() => [arm('parenTuple', '(', opt(StarNamedExpression, ',', opt(StarNamedExpressions)), ')')]); @@ -174,8 +177,8 @@ const Kvpair = rule(() => [[Expression, ':', Expression]]); const DoubleStarredKvpair = rule(() => [['**', BitwiseOr()], Kvpair]); const Dict = rule(() => [['{', opt(DoubleStarredKvpair, many(',', DoubleStarredKvpair), opt(',')), '}']]); // A for head's targets: star expressions none of which reads a top-level `in` (it is the -// head's), each read under `exclude('in')` (an exclusion holds for the one Pratt frame it enters). -const ForTargets = rule(() => [arm('exprList', exclude('in', StarExpression), many(',', exclude('in', StarExpression)), opt(','))]); +// head's), each read with the context parameter `in` cleared (a primary sets it again). +const ForTargets = rule(() => [arm('exprList', ctx({ in: false }, StarExpression), many(',', ctx({ in: false }, StarExpression)), opt(','))]); const ForIfClause = rule(() => [[opt('async'), 'for', ForTargets, assignTarget('star'), 'in', Disjunction(), many('if', Disjunction())]]); const ForIfClauses = rule(() => [[many1(ForIfClause)]]); const Listcomp = rule(() => [['[', NamedExpression, ForIfClauses, ']']]); @@ -390,10 +393,12 @@ export default defineGrammar({ KeyValuePattern, MappingPattern, KeywordPattern, ClassPattern, Patterns, CaseBlock, SubjectExpr, MatchStmt, CompoundStmt, Statement, Statements, File, }, + // The context parameters (docs/GRAMMAR.md "Contexts"): `in`, whether the comparison `in` is read. + params: { in: true }, ledPrec: [ { connector: 'if', below: 'or' }, { connector: 'not', sameAs: '<', chainRhs: true }, - { connector: 'in', sameAs: '<', chainRhs: true }, + { connector: 'in', sameAs: '<', chainRhs: true, when: '+in' }, // not in a for target (ForTargets) { connector: 'is', sameAs: '<', chainRhs: true }, ], entry: File, diff --git a/src/api.ts b/src/api.ts index 07ded6a4..2f15484f 100644 --- a/src/api.ts +++ b/src/api.ts @@ -1,6 +1,6 @@ import type { LedPrec, Grammar, TokenDecl, PrecLevel, PrecOperator, RuleDecl, RuleExpr, MarkupConfig, ElementRegion, IndentConfig, NewlineConfig, StringInterpolation, TokenPattern, AssignTargetContext } from './grammar/types.ts'; import { computeNullableRules, findEntryRule } from './grammar/grammar-analysis.ts'; -import { whenTest } from './grammar/grammar-utils.ts'; +import { ctxEquation, whenTest } from './grammar/grammar-utils.ts'; import { altPattern, anyChar, followedBy, never, noneOf, notFollowedBy, notPrecededBy, oneOf, optPattern, plus, precededBy, range, repeat, @@ -57,7 +57,7 @@ interface TokenOptions { // that parses a hole belongs to each REFERENCE of the token, not to the token (TypeScript's // template-literal type and its template-literal expression share one token): a bare reference // takes the grammar's `expression` rule, `withHoles(token, rule)` names another. - template?: { open: string; interpOpen: string; interpClose: string }; + template?: { open: string; interpOpen: string; interpClose: string; holeCtx?: Readonly> }; regexContext?: { divisionAfterTypes?: string[]; divisionAfterTexts?: string[]; @@ -263,39 +263,23 @@ class AltNode { readonly items: Alternative[]; constructor(items: Alternative[]) { this.items = items; } } -class ExcludeNode { - // Parse the wrapped rule, but with the given infix/LED connectors disabled at - // the top level (they rebind to the enclosing context). Models grammars with a - // "no-`in`" production: a for-head's `var x = E` parses E so a following `in` - // is the for-in keyword, not the `in` operator. The excluded tokens are grammar - // DATA, so the engine stays language-agnostic. - readonly __kind = 'exclude' as const; - readonly connectors: string[]; - readonly items: Element[]; - constructor(connectors: string[], items: Element[]) { this.connectors = connectors; this.items = items; } -} class CtxNode { - // Mark the wrapped items as [Await]/[Yield] context (the ECMAScript grammar - // parameter): inside an async function/arrow/method body await is the AwaitExpression - // operator (no bare-identifier reading), and inside a generator body yield is the - // YieldExpression operator. Every parser parses the body with the context word set - // (grammar-utils.ts ctxWordOfMode); every other consumer treats it as a transparent group. Wrap ONLY the async/generator arm's body+params; a nested - // non-async function/arrow/class body is simply left UNwrapped (context resets). + // The items with the grammar's context parameters set or cleared (Grammar.params; the spec's + // `[+Yield]`, `[~In]` at a reference); a parameter the equations do not name is copied. + // Every parser parses the body in that word (grammar-utils.ts ctxEquation); every other + // consumer treats it as a transparent group. readonly __kind = 'ctx' as const; - readonly mode: 'await' | 'yield' | 'asyncgen' | 'reset'; + readonly eqs: Readonly>; readonly items: Element[]; - constructor(mode: 'await' | 'yield' | 'asyncgen' | 'reset', items: Element[]) { this.mode = mode; this.items = items; } + constructor(eqs: Readonly>, items: Element[]) { this.eqs = eqs; this.items = items; } } class NotNode { readonly __kind = 'not' as const; // Zero-width negative lookahead over an element, or an array (a seq, like // everywhere else in the rule DSL). Matches nothing; succeeds only when - // `item` can't match. `reservable` flags the bare-identifier reserved-word guard - // (notReservedExpr) so a parser extends it with the operator words the context word in force - // reserves (grammar-utils.ts CTX_WORDS). + // `item` can't match. readonly item: Element | Sequence; - readonly reservable: boolean; - constructor(item: Element | Sequence, reservable = false) { this.item = item; this.reservable = reservable; } + constructor(item: Element | Sequence) { this.item = item; } } class RelaxNode { @@ -375,7 +359,7 @@ class FieldNode { constructor(name: string, item: Element) { this.name = name; this.item = item; } } -type Combinator = HolesNode | SepNode | OptNode | ManyNode | Many1Node | AltNode | ExcludeNode | NotNode | CtxNode | WhenNode | RelaxNode | CapExprNode | AtLevelNode | FieldNode; +type Combinator = HolesNode | SepNode | OptNode | ManyNode | Many1Node | AltNode | NotNode | CtxNode | WhenNode | RelaxNode | CapExprNode | AtLevelNode | FieldNode; /** A named alternative (see ArmNode). */ export function arm(name: string, ...items: Element[]): ArmNode { @@ -414,13 +398,6 @@ export function withHoles(token: TokenRef, rule: RuleRef): HolesNode { return new HolesNode(token, rule); } -// Parse `items` with the given LED connector(s) disabled at the top level (a -// no-`in`-style context). `exclude('in', Expr)` parses an Expr that stops before -// a top-level `in`, leaving it for the enclosing rule. -export function exclude(connectors: string | string[], ...items: Element[]): ExcludeNode { - return new ExcludeNode(typeof connectors === 'string' ? [connectors] : connectors, items); -} - // Parse `strict` (in the parser and all generators) but render `relaxed` for tree-sitter. // For a parser-correct constraint that explodes / inflates the tree-sitter GLR table while // the highlighter doesn't need it. Each side is a single element or an array (a seq). @@ -443,29 +420,26 @@ export function atLevel(operator: string, rule: RuleRef): AtLevelNode { return new AtLevelNode(operator, rule); } -// Mark items as await / yield / async-generator context (see CtxNode). Wrap an -// async arm's body and params in awaitCtx(...), a generator arm's in yieldCtx(...), -// an async-generator's in asyncGenCtx(...). -export function awaitCtx(...items: Element[]): CtxNode { return new CtxNode('await', items); } -export function yieldCtx(...items: Element[]): CtxNode { return new CtxNode('yield', items); } -export function asyncGenCtx(...items: Element[]): CtxNode { return new CtxNode('asyncgen', items); } -// Reset to NO await/yield context (a nested non-async/non-generator function/arrow/ -// method body, a class body, a computed property key, a field initializer). Wrapping a -// body in resetCtx() inside an already-forked family routes its refs back to the plain -// family — the boundary the fork transform stops at (the portable targets clear the -// context word there). -export function resetCtx(...items: Element[]): CtxNode { return new CtxNode('reset', items); } +// The items parsed with the named context parameters set (true) or cleared (false); the others +// are copied from the reference's context: `ctx({ yield: true, await: false }, body)` is the +// spec's `FunctionBody[+Yield, ~Await]`, `ctx({ in: false }, Expr)` its `Expression[~In]`. +export function ctx(eqs: Readonly>, ...items: Element[]): CtxNode { return new CtxNode(eqs, items); } // The items exist only where the context condition holds: `when('+yield', 'yield', ...)` is -// ECMAScript's `[+Yield]` (the condition: `+p` / `~p` over grammar-utils.ts CTX_PARAMS, a +// ECMAScript's `[+Yield]` (the condition: `+p` / `~p` over the grammar's declared params, a // conjunction: `'+yield ~await'`). With no items it is a zero-width test. Among a `prefix(...)`'s -// operators, `when(cond, 'op')` gates that operator. The parsers read it; every other consumer -// (tree-sitter, TextMate, Monarch) renders the items unconditionally. +// operators, `when(cond, 'op')` gates that operator; `[$, when('+in', 'in'), $]` gates a led; an +// item `when(cond, 'word')` of a `not`'s alternation is refused only where cond holds. The +// parsers read it; every other consumer (tree-sitter, TextMate, Monarch) renders the items +// unconditionally, and drops them inside a `not`. class WhenNode { readonly __kind = 'when' as const; readonly cond: string; readonly items: Element[]; - constructor(cond: string, items: Element[]) { whenTest(cond); this.cond = cond; this.items = items; } + constructor(cond: string, items: Element[]) { + if (!/^\s*[+~][A-Za-z_$][\w$]*(\s+[+~][A-Za-z_$][\w$]*)*\s*$/.test(cond)) throw new Error(`when(${JSON.stringify(cond)}): a condition is +p / ~p words`); + this.cond = cond; this.items = items; + } } export function when(cond: string, ...items: Element[]): WhenNode { return new WhenNode(cond, items); } @@ -474,11 +448,6 @@ export function when(cond: string, ...items: Element[]): WhenNode { return new W export function not(item: Element | Sequence): NotNode { return new NotNode(item); } -// The bare-identifier reserved-word guard (notReservedExpr / notReserved): a `not` -// a parser extends with await/yield inside those contexts (see NotNode). -export function reservableNot(item: Element | Sequence): NotNode { - return new NotNode(item, true); -} // ── Precedence ── @@ -590,21 +559,13 @@ function toRuleExpr(el: Element, names: Lowering): RuleExpr { : { type: 'seq' as const, items: el.items.map(i => toRuleExpr(i, names)) }; return { type: 'quantifier', body, kind: '+' }; } - if (el instanceof ExcludeNode) { - // Reuse the transparent `group` node (every walker recurses into `body`); - // `suppress` is read only by the parser's expression engine. - const body = el.items.length === 1 - ? toRuleExpr(el.items[0], names) - : { type: 'seq' as const, items: el.items.map(i => toRuleExpr(i, names)) }; - return { type: 'group', body, suppress: el.connectors }; - } if (el instanceof CtxNode) { - // Transparent group carrying the ctxMode marker; only the parsers read ctxMode (see - // CtxNode), everyone else recurses into body as a plain group. + // Transparent group carrying the equations; only the parsers read them (see CtxNode), + // everyone else recurses into body as a plain group. const body = el.items.length === 1 ? toRuleExpr(el.items[0], names) : { type: 'seq' as const, items: el.items.map(i => toRuleExpr(i, names)) }; - return { type: 'group', body, ctxMode: el.mode }; + return { type: 'group', body, ctx: el.eqs }; } if (el instanceof WhenNode) { const body: RuleExpr = el.items.length === 1 @@ -640,7 +601,7 @@ function toRuleExpr(el: Element, names: Lowering): RuleExpr { const body = isSequence(el.item) ? { type: 'seq' as const, items: el.item.map(i => toRuleExpr(i, names)) } : toRuleExpr(el.item, names); - return el.reservable ? { type: 'not', body, reservable: true } : { type: 'not', body }; + return { type: 'not', body }; } const marker = el as Marker; if (marker.__kind === 'op') return { type: 'op' }; @@ -679,6 +640,7 @@ interface GrammarConfig = Record; prec?: PrecLevelDef[]; ledPrec?: LedPrec[]; + params?: Readonly>; // context parameters: name -> value at entry (Grammar.params; read by `ctx` / `when`) assignTargets?: Record; // declared assignment-target contexts (Grammar.assignTargets) composeGt?: true; // the lexer scans `>` alone and the parser composes `>`-led operators (Grammar.composeGt) composeLt?: true; // likewise for `<` and the `<`-led operators (Grammar.composeLt) @@ -811,7 +773,19 @@ export function defineGrammar>(config: G }); const entryRule = config.entry ? names.get(config.entry) : undefined; // `entry` may be omitted: findEntryRule then takes the last rule if (config.entry && !entryRule) throw new Error('`entry` references an undeclared rule'); - const grammar = { name: config.name, scopeName: config.scopeName, tokens, precs, ledPrecs: config.ledPrec, ...(config.composeGt ? { composeGt: true as const } : {}), ...(config.composeLt ? { composeLt: true as const } : {}), ...(config.assignTargets ? { assignTargets: config.assignTargets } : {}), rules, entryRule, scopeOverrides, contextualScopes, markup: config.markup, elements: config.elements, indent: config.indent, newline: config.newline, expressionRule: config.expression ? names.get(config.expression) : undefined, aliasScopes: config.aliasScopes, canonicalRepoNames: config.canonicalRepoNames, manifest: config.manifest, treeSitterConflicts: config.treeSitterConflicts, treeSitterContextualNames: config.treeSitterContextualNames }; + // Every `when` condition and `ctx` equation names a declared parameter (each throws by name). + const checkCtx = (e: RuleExpr): void => { + if (!e || typeof e !== 'object') return; + if (e.type === 'group') { if (e.when !== undefined) whenTest(e.when, config.params); if (e.ctx !== undefined) ctxEquation(e.ctx, config.params); } + if ('body' in e && e.body) checkCtx(e.body as RuleExpr); + if ('items' in e) (e.items as RuleExpr[]).forEach(checkCtx); + if (e.type === 'sep') checkCtx(e.element); + }; + rules.forEach((r) => checkCtx(r.body)); + for (const l of precs) for (const o of l.operators) if (o.when !== undefined) whenTest(o.when, config.params); + for (const lp of config.ledPrec ?? []) if (lp.when !== undefined) whenTest(lp.when, config.params); + for (const t of tokens) if (t.template?.holeCtx !== undefined) ctxEquation(t.template.holeCtx, config.params); + const grammar = { name: config.name, scopeName: config.scopeName, tokens, precs, ledPrecs: config.ledPrec, ...(config.params ? { params: config.params } : {}), ...(config.composeGt ? { composeGt: true as const } : {}), ...(config.composeLt ? { composeLt: true as const } : {}), ...(config.assignTargets ? { assignTargets: config.assignTargets } : {}), rules, entryRule, scopeOverrides, contextualScopes, markup: config.markup, elements: config.elements, indent: config.indent, newline: config.newline, expressionRule: config.expression ? names.get(config.expression) : undefined, aliasScopes: config.aliasScopes, canonicalRepoNames: config.canonicalRepoNames, manifest: config.manifest, treeSitterConflicts: config.treeSitterConflicts, treeSitterContextualNames: config.treeSitterContextualNames }; // Nullable NON-ENTRY rules are a definition error: the engine never returns an empty match for a // rule, so such a rule's empty case is unreachable and references to it fail silently where the diff --git a/src/editor/gen-tree-sitter.ts b/src/editor/gen-tree-sitter.ts index 8ad8c2ec..e9e22877 100644 --- a/src/editor/gen-tree-sitter.ts +++ b/src/editor/gen-tree-sitter.ts @@ -1,5 +1,5 @@ import type { Grammar, RuleExpr, RuleDecl, TokenPattern } from '../grammar/types.ts'; -import { collectLiterals, isKeywordLiteral, ZERO_WIDTH_MARKERS, isZeroWidthMarker } from '../grammar/grammar-utils.ts'; +import { collectLiterals, contextFreeView, isKeywordLiteral, ZERO_WIDTH_MARKERS, isZeroWidthMarker } from '../grammar/grammar-utils.ts'; import { buildLr, END, type LeafGraph, type LrAnalysis } from './lr-automaton.ts'; import { info as tokenPatternInfo, continuesAt, type CSet } from '../grammar/lex-match-plan.ts'; import { analyzeGrammar, findEntryRule, hasMarker } from '../grammar/grammar-analysis.ts'; @@ -3206,7 +3206,10 @@ bool tree_sitter_${grammarName}_external_scanner_scan(void *payload, TSLexer *le return { grammarJs, highlightsScm, scannerC, externalTokens: ['raw_text'], assertions: [] }; } -export function generateTreeSitter(grammar: Grammar, langName?: string): TreeSitterOutput { +export function generateTreeSitter(input: Grammar, langName?: string): TreeSitterOutput { + // tree-sitter has no contexts: it reads the context-free view (every `ctx` group its body, no + // guard word that only a context refuses): it over-accepts where the parsers' contexts refuse. + const grammar = contextFreeView(input); const name = (langName ?? grammar.name); const grammarName = toSnake(name); // Markup languages (HTML/Vue) get the purpose-built markup grammar, not the token-stream one. diff --git a/src/grammar/grammar-analysis.ts b/src/grammar/grammar-analysis.ts index 53f0708b..1427238d 100644 --- a/src/grammar/grammar-analysis.ts +++ b/src/grammar/grammar-analysis.ts @@ -13,7 +13,7 @@ // reserved-aware "qualKeys" variant) and every parse CONTROL loop. The interpreter keeps its // loops independent so it remains a genuine oracle for the emitter's loops — an oracle sharing // the suspect machinery could not catch bugs in it. -import { ZERO_WIDTH_MARKERS, ctxObserves, isZeroWidthMarker, whenTest } from './grammar-utils.ts'; +import { ZERO_WIDTH_MARKERS, ctxObserves, isZeroWidthMarker, notStaticBody, whenTest } from './grammar-utils.ts'; import type { Grammar, RuleExpr, RuleDecl, ElementRegion } from './types.ts'; import { tokenPatternFirstCharSet } from './token-pattern.ts'; @@ -161,7 +161,7 @@ export function analyzeGrammar(grammar: Grammar) { const bp = (i + 1) * 2; for (const op of level.operators) { if (op.position === 'prefix') { - prefixOps.set(op.value, { lbp: 0, rbp: level.assoc === 'right' ? bp - 1 : bp, assoc: level.assoc, position: 'prefix', requireAssignTarget: op.requireAssignTarget, ...(op.capped ? { capBp: bp } : {}), ...(op.when !== undefined ? { when: whenTest(op.when) } : {}) }); + prefixOps.set(op.value, { lbp: 0, rbp: level.assoc === 'right' ? bp - 1 : bp, assoc: level.assoc, position: 'prefix', requireAssignTarget: op.requireAssignTarget, ...(op.capped ? { capBp: bp } : {}), ...(op.when !== undefined ? { when: whenTest(op.when, grammar.params) } : {}) }); if (op.requireAssignTarget) requireAssignTargetOps.add(op.value); } else if (op.position === 'postfix') { postfixOpValues.add(op.value); @@ -183,6 +183,7 @@ export function analyzeGrammar(grammar: Grammar) { const ledPrecByConnector = new Map(); for (const lp of grammar.ledPrecs ?? []) { const anchorOp = lp.sameAs ?? lp.below; + if (!anchorOp && lp.when !== undefined && !lp.chainRhs) continue; // an entry that only gates its led (LedPrec.when) if (!anchorOp) throw new Error(`ledPrec ${lp.connector}: needs sameAs or below`); const op = opTable.get(anchorOp); if (!op) throw new Error(`ledPrec ${lp.connector}: anchor ${JSON.stringify(anchorOp)} is not a ladder operator`); @@ -670,37 +671,6 @@ export function analyzeGrammar(grammar: Grammar) { } } - // ── Suppress sets ── - // The LED connectors a `suppress` group disables (`exclude('in', Expr)`: no `in` in a for-head) - // are a constant of the grammar at each site, so a compiled parser never builds one at run time: - // each distinct set is kept once here, sorted, in first-occurrence order over the rules; set 0 is - // the empty set, the state outside every suppress group. A compiled parser holds the index of the - // set in force, and which sets disable a led is decided here too (suppressedIn), so it tests an - // index, never a set. - const suppressSets: string[][] = [[]]; - const suppressSetIds = new Map([['[]', 0]]); - const suppressKey = (connectors: readonly string[]) => JSON.stringify([...new Set(connectors)].sort()); - const collectSuppress = (e: RuleExpr): void => { - if (e.type === 'group' && e.suppress && e.suppress.length) { - const key = suppressKey(e.suppress); - if (!suppressSetIds.has(key)) { suppressSetIds.set(key, suppressSets.length); suppressSets.push(JSON.parse(key)); } - } - if (e.type === 'seq' || e.type === 'alt') e.items.forEach(collectSuppress); - else if (e.type === 'quantifier' || e.type === 'group' || e.type === 'not') collectSuppress(e.body); - else if (e.type === 'sep') collectSuppress(e.element); - }; - for (const rule of grammar.rules) collectSuppress(rule.body); - // The index of a suppress group's connector set. - const suppressSetOf = (connectors: readonly string[]): number => { - const id = suppressSetIds.get(suppressKey(connectors)); - if (id === undefined) throw new Error(`suppress set ${suppressKey(connectors)} is not a group of this grammar`); - return id; - }; - // The sets that disable a led whose first literal is `connector` (none for a led without one): - // the led is tried only while the set in force is none of them. - const suppressedIn = (connector: string | null): number[] => - connector === null ? [] : suppressSets.flatMap((set, i) => (set.includes(connector) ? [i] : [])); - return { tokenNames, opTable, prefixOps, noUnaryLhsOps, postfixOpValues, requireAssignTargetOps, @@ -711,7 +681,6 @@ export function analyzeGrammar(grammar: Grammar) { maxBp, ruleByName, leftRecSet, prattClassified, leftRecClassified, templateTokenName, templateTokenNames, firstSets, exprFirst, ruleSecond, exprSecond, exprSecondBy, - suppressSets, suppressSetOf, suppressedIn, // The context-word bits each rule's parse reads (grammar-utils.ts ctxObserves): with the rule, // the key of a memo entry and of a reusable row. ctxObserve: ctxObserves(grammar, prattRules), @@ -730,14 +699,14 @@ export function analyzeGrammar(grammar: Grammar) { // kind also begins with its head); // - a prefix-operator item (`prefix $`) is each prefix operator of the precedence table; // - a `not` over a body that reads exactly one token removes that body's symbols from what the -// items after it begin with; a reserved-word guard removes them except the context's words -// (`maybeWords`: whether those are reserved is the context's, known only at run time); +// items after it begin with, except the words it refuses only in some contexts (its `when` +// items: whether those are refused is the context's, known only at run time); // `not(not(X))` keeps only X's FIRST; every other zero-width test keeps everything. // Which kinds may carry a literal is the lexer plan's (`kindsOf`, a superset; none: no token does), // handed in as data: this analysis knows the grammar, not the lexer. A symbol is a literal's text, // or KIND + a token kind's name. export const KIND = '\u0000'; -export type ConcreteLex = { kindsOf: (lit: string) => readonly string[]; gtComps: readonly string[]; maybeWords: readonly string[] }; +export type ConcreteLex = { kindsOf: (lit: string) => readonly string[]; gtComps: readonly string[] }; export function concreteFirst(grammar: Grammar, a: ReturnType, lex: ConcreteLex) { const literals = new Set(); const collect = (e: RuleExpr): void => { @@ -757,7 +726,7 @@ export function concreteFirst(grammar: Grammar, a: ReturnType { if (e.type !== 'not') return null; if (e.body.type === 'not') { const f = first(e.body.body); return f.empty ? null : (s) => f.syms.has(s); } - const m = oneToken(e.body); + const m = oneToken(notStaticBody(e.body)); // a word it refuses only in some contexts may begin the item if (m === null) return null; const out = new Set(m); - return e.reservable ? (s) => !out.has(s) || lex.maybeWords.includes(s) : (s) => !out.has(s); + return (s) => !out.has(s); }; const ZERO = new Set([...ZERO_WIDTH_MARKERS, 'op', 'postfix']); function seqF(items: readonly RuleExpr[]): F { diff --git a/src/grammar/grammar-names.ts b/src/grammar/grammar-names.ts index c605b720..e755a048 100644 --- a/src/grammar/grammar-names.ts +++ b/src/grammar/grammar-names.ts @@ -199,13 +199,15 @@ export function nameRule(rule: RuleDecl): RuleNames { } return out; - function walk(it: RuleExpr, scope: Scope, children: NamedSlot[], where: string, arm: number): void { + function walk(it: RuleExpr, scope: Scope, children: NamedSlot[], where: string, arm: number, groupField?: string): void { switch (it.type) { case 'ref': - children.push(put(out.childOf, it, scope.take(lowerFirst(it.name), it.field))); + children.push(put(out.childOf, it, scope.take(lowerFirst(it.name), it.field ?? groupField))); return; case 'group': - walk(it.body, scope, children, where, arm); + // A group builds no node: a name written on it (`field('left', atLevel('++', Expr))`) + // names the one reference it holds. + walk(it.body, scope, children, where, arm, it.body.type === 'ref' ? it.field : undefined); return; case 'seq': for (const s of it.items) walk(s, scope, children, where, arm); diff --git a/src/grammar/grammar-utils.ts b/src/grammar/grammar-utils.ts index d38b9843..dfb299fa 100644 --- a/src/grammar/grammar-utils.ts +++ b/src/grammar/grammar-utils.ts @@ -14,89 +14,120 @@ import type { Grammar, RuleExpr } from './types.ts'; export const ZERO_WIDTH_MARKERS: ReadonlySet = new Set(['not', 'sameLine', 'noCommentBefore', 'noMultilineFlowBefore', 'notLeftLeaf', 'assignTarget']); export const isZeroWidthMarker = (t: RuleExpr['type']): boolean => ZERO_WIDTH_MARKERS.has(t); -/** The grammar's context parameters (docs/GRAMMAR.md "Contexts: `when`"), one bit each of the - * context WORD (bit 1 << index): `await` and `yield` are ECMAScript's [Await] / [Yield]. - * `syncFn` is TRANSITIONAL (kind: transition; end state: the declared parameters with goals, - * where the Module goal's entry word sets `await`; exit: the goals step deletes it and the - * `await` operator's gate becomes `when('+await')`): it is set in a body where `await` is the - * operator in no goal (a non-async function, method, arrow, accessor, class element) and clear - * at the top level, which the one entry reads as both goals (Module: the operator, Script: the - * identifier), and in an async body. */ -export const CTX_PARAMS = ['await', 'yield', 'syncFn'] as const; -export type CtxMode = 'await' | 'yield' | 'asyncgen' | 'reset'; -/** A `when` condition (`'+yield'`, `'~syncFn'`, `'+a ~b'`: a conjunction) as the test +/** The grammar's context parameters (docs/GRAMMAR.md "Contexts"), declared by the grammar + * (`Grammar.params`: name -> its value at entry), one bit each of the context WORD in declaration + * order: bit 1 << k is set where parameter k DIFFERS from its entry value, so the entry word is 0. + * ECMAScript's are [Await], [Yield] and [In]; JavaScript's `syncFn` is TRANSITIONAL (kind: + * transition; end state: goals, where the Module goal's entry word sets `await`; exit: the goals + * step deletes it and the `await` operator's gate becomes `when('+await')`): it is set in a body + * where `await` is the operator in no goal (a non-async function, method, arrow, accessor, class + * element) and clear at the top level, which the one entry reads as both goals (Module: the + * operator, Script: the identifier), and in an async body. */ +export type CtxParams = Readonly>; +const paramBit = (params: CtxParams | undefined, name: string, where: string): { bit: number; entry: boolean } => { + const names = Object.keys(params ?? {}); + const i = names.indexOf(name); + if (i < 0) throw new Error(`${where}: '${name}' is not a context parameter of this grammar (declared: ${names.length ? names.join(', ') : 'none'}; Grammar.params)`); + return { bit: 1 << i, entry: params![name]! }; +}; +/** A `when` condition (`'+yield'`, `'~in'`, `'+a ~b'`: a conjunction) as the test * `(word & mask) === val`. An unknown parameter is an error, not a condition that never holds. */ -export function whenTest(cond: string): { mask: number; val: number } { +export function whenTest(cond: string, params: CtxParams | undefined): { mask: number; val: number } { let mask = 0, val = 0; for (const part of cond.trim().split(/\s+/)) { - const i = CTX_PARAMS.indexOf(part.slice(1) as typeof CTX_PARAMS[number]); - if ((part[0] !== '+' && part[0] !== '~') || i < 0) throw new Error(`when(${JSON.stringify(cond)}): '${part}' is not +p / ~p over the context parameters ${CTX_PARAMS.join(', ')}`); - mask |= 1 << i; if (part[0] === '+') val |= 1 << i; + if (part[0] !== '+' && part[0] !== '~') throw new Error(`when(${JSON.stringify(cond)}): '${part}' is not +p / ~p`); + const { bit, entry } = paramBit(params, part.slice(1), `when(${JSON.stringify(cond)})`); + mask |= bit; if ((part[0] === '+') !== entry) val |= bit; } return { mask, val }; } -/** Whether some `when` of the grammar (an item or an operator) reads `syncFn`: only then does a - * reset body differ from the top level (the bit is set there), so a grammar that never reads it - * keeps one context for both. */ -export function readsSyncFn(g: Pick): boolean { - const bit = 1 << CTX_PARAMS.indexOf('syncFn'); - const reads = (c: string | undefined): boolean => c !== undefined && (whenTest(c).mask & bit) !== 0; - if (g.precs.some((l) => l.operators.some((o) => reads(o.when)))) return true; - const walk = (e: RuleExpr): boolean => { - if (!e || typeof e !== 'object') return false; +/** Every bit of the grammar's context word. */ +export const ctxAll = (params: CtxParams | undefined): number => (1 << Object.keys(params ?? {}).length) - 1; +/** A `ctx` group's equations (`{ yield: true, in: true }`; a parameter it does not name is copied) + * as the word its body runs in: `(word & keep) | set`. */ +export function ctxEquation(eqs: Readonly>, params: CtxParams | undefined): { keep: number; set: number } { + let fixed = 0, set = 0; + for (const [name, v] of Object.entries(eqs)) { + const { bit, entry } = paramBit(params, name, `ctx(${JSON.stringify(eqs)})`); + fixed |= bit; if (v !== entry) set |= bit; + } + return { keep: ctxAll(params) & ~fixed, set }; +} +/** The number of distinct values of the context word: a key that joins a position with a word + * (the packrat memo's) is `pos * ctxSpan + word`. */ +export const ctxSpan = (params: CtxParams | undefined): number => 1 << Object.keys(params ?? {}).length; +/** The words a negative lookahead refuses only in some contexts: the `when(cond, 'word')` items + * of its alternation (the reserved-word guard `not(alt(...reservedWords, when('+yield', + * 'yield')))`: ECMAScript's IdentifierReference `[~Yield] yield`). Every other consumer than a + * parser drops them (a guard that refuses a word in some context refuses it in none of a + * context-free reading). */ +export function notCtxWords(body: RuleExpr, params: CtxParams | undefined): Array<{ text: string; mask: number; val: number }> { + const items = body.type === 'alt' ? body.items : [body]; + return items.flatMap((it) => (it.type === 'group' && it.when !== undefined && it.body.type === 'literal' ? [{ text: it.body.value, ...whenTest(it.when, params) }] : [])); +} +/** The grammar as a context-free consumer reads it (tree-sitter): every `ctx` group is its body (a + * sequence one spliced into the sequence around it), and every `not` body loses its `when` items + * (notStaticBody); a `when` group elsewhere stays, a transparent group (its items exist). Rules + * keep their names and order. */ +const cfViews = new WeakMap(); +export function contextFreeView>(g: G): G { + const hit = cfViews.get(g) as G | undefined; + if (hit !== undefined) return hit; + const plainCtx = (e: RuleExpr): boolean => + e.type === 'group' && e.ctx !== undefined && e.when === undefined && e.capBelow === undefined && e.atLevel === undefined && e.treeSitterRelaxed === undefined; + const map = (e: RuleExpr): RuleExpr => { + if (!e || typeof e !== 'object') return e; + if (plainCtx(e)) { const b = map((e as Extract).body); return e.field !== undefined || e.arm !== undefined ? { ...b, ...(e.field !== undefined ? { field: e.field } : {}), ...(e.arm !== undefined ? { arm: e.arm } : {}) } : b; } switch (e.type) { - case 'group': return reads(e.when) || walk(e.body); - case 'seq': case 'alt': return e.items.some(walk); - case 'quantifier': case 'not': return walk(e.body); - case 'sep': return walk(e.element); - default: return false; + case 'not': return { ...e, body: map(notStaticBody(e.body)) }; + case 'seq': return { ...e, items: e.items.flatMap((x) => { const m = map(x); return plainCtx(x) && m.type === 'seq' && m.field === undefined && m.arm === undefined ? m.items : [m]; }) }; + case 'alt': return { ...e, items: e.items.map(map) }; + case 'group': return { ...e, body: map(e.body), ...(e.treeSitterRelaxed !== undefined ? { treeSitterRelaxed: map(e.treeSitterRelaxed) } : {}) }; + case 'quantifier': return { ...e, body: map(e.body) }; + case 'sep': return { ...e, element: map(e.element) }; + default: return e; } }; - return g.rules.some((r) => walk(r.body)); -} -/** The word a context marker sets (awaitCtx / yieldCtx / asyncGenCtx / resetCtx). */ -export function ctxWordOfMode(mode: CtxMode, splitSync: boolean): number { - const sync = splitSync ? 4 : 0; - return mode === 'await' ? 1 : mode === 'yield' ? 2 | sync : mode === 'asyncgen' ? 3 : sync; + const view = { ...g, rules: g.rules.map((r) => ({ ...r, body: map(r.body) })) }; + cfViews.set(g, view); + return view; } -/** The number of distinct values of the context word: a key that joins a position with a word - * (the packrat memo's) is `pos * CTX_SPAN + word`. */ -export const CTX_SPAN = 1 << CTX_PARAMS.length; -/** The operator word each context bit reserves in an identifier's reserved-word guard - * (`reservableNot`): CTX_WORDS[i] is refused where bit 1 << i is set. */ -export const CTX_WORDS: readonly string[] = ['await', 'yield']; -/** The bits of the word a reserved-word guard reads (those of CTX_WORDS). */ -export const CTX_WORD_BITS = 3; -/** Whether a reserved-word guard refuses `text` in context `word` (beyond its own words). */ -export function ctxReserves(word: number, text: string): boolean { - if ((word & CTX_WORD_BITS) === 0) return false; - const i = CTX_WORDS.indexOf(text); - return i >= 0 && (word & (1 << i)) !== 0; +/** A `not` body without its `when` items (the context-free reading of a guard: notCtxWords). */ +export function notStaticBody(body: RuleExpr): RuleExpr { + if (body.type !== 'alt') return body; + const items = body.items.filter((it) => !(it.type === 'group' && it.when !== undefined)); + return items.length === body.items.length ? body : items.length === 1 ? items[0]! : { ...body, items }; } -/** The bits of the context word each rule's parse can read: a `when` (an item, or a gated - * operator of a Pratt rule), a reserved-word guard, or a rule it reaches, without a context - * marker in between (a marker sets the whole word, so what lies under it reads the marker's word, - * not the caller's). A rule's parse is a function of (position, word & observes): the key a memo - * entry or a reused row needs beside the rule. */ -export function ctxObserves(g: Pick, prattRules: ReadonlySet): Map { - const gatedOps = g.precs.reduce((m, l) => l.operators.reduce((n, o) => (o.when !== undefined ? n | whenTest(o.when).mask : n), m), 0); - const direct = new Map(), reaches = new Map>(); +/** The bits of the context word each rule's parse can read: a `when` (an item, a gated led or a + * gated operator of a Pratt rule), or a rule it reaches, minus the bits a `ctx` group on the way + * fixes (what lies under it reads the group's value, not the caller's). A rule's parse is a + * function of (position, word & observes): the key a memo entry or a reused row needs beside the + * rule. */ +export function ctxObserves(g: Pick, prattRules: ReadonlySet): Map { + const gatedOps = g.precs.reduce((m, l) => l.operators.reduce((n, o) => (o.when !== undefined ? n | whenTest(o.when, g.params).mask : n), m), 0); + const gatedLeds = new Map((g.ledPrecs ?? []).flatMap((lp) => (lp.when !== undefined ? [[lp.connector, whenTest(lp.when, g.params).mask] as const] : []))); + const all = ctxAll(g.params); + const direct = new Map(), reaches = new Map>(); for (const r of g.rules) { - let bits = prattRules.has(r.name) ? gatedOps : 0; - const refs = new Set(); - const walk = (e: RuleExpr): void => { + const pratt = prattRules.has(r.name); + let bits = pratt ? gatedOps : 0; + const refs: Array<[string, number]> = []; + const walk = (e: RuleExpr, keep: number): void => { if (!e || typeof e !== 'object') return; switch (e.type) { - case 'ref': refs.add(e.name); if (e.hole !== undefined) refs.add(e.hole); return; - case 'group': if (e.ctxMode) return; if (e.when !== undefined) bits |= whenTest(e.when).mask; walk(e.body); return; - case 'not': if (e.reservable) bits |= CTX_WORD_BITS; walk(e.body); return; - case 'seq': case 'alt': e.items.forEach(walk); return; - case 'quantifier': walk(e.body); return; - case 'sep': walk(e.element); return; + case 'literal': if (pratt) bits |= (gatedLeds.get(e.value) ?? 0) & keep; return; // a gated led's connector (over-approximate: any use of the word) + case 'ref': refs.push([e.name, keep]); if (e.hole !== undefined) refs.push([e.hole, keep]); return; + case 'group': + if (e.when !== undefined) bits |= whenTest(e.when, g.params).mask & keep; + walk(e.body, e.ctx !== undefined ? keep & ctxEquation(e.ctx, g.params).keep : keep); + return; + case 'seq': case 'alt': e.items.forEach((x) => walk(x, keep)); return; + case 'quantifier': case 'not': walk(e.body, keep); return; + case 'sep': walk(e.element, keep); return; default: return; } }; - walk(r.body); + walk(r.body, all); direct.set(r.name, bits); reaches.set(r.name, refs); } const obs = new Map(direct); @@ -104,7 +135,7 @@ export function ctxObserves(g: Pick, prattRules: Rea changed = false; for (const [name, refs] of reaches) { let b = obs.get(name)!; - for (const s of refs) b |= obs.get(s) ?? 0; + for (const [s, keep] of refs) b |= (obs.get(s) ?? 0) & keep; if (b !== obs.get(name)) { obs.set(name, b); changed = true; } } } diff --git a/src/grammar/types.ts b/src/grammar/types.ts index bb3493fa..610f6e66 100644 --- a/src/grammar/types.ts +++ b/src/grammar/types.ts @@ -98,6 +98,9 @@ export interface TemplateDelimiters { open: string; // starts AND ends a template literal (e.g. '`') interpOpen: string; // starts an interpolation hole (e.g. '${') interpClose: string; // ends an interpolation hole, also the brace used for nesting depth (e.g. '}') + // The context equations a hole is parsed under (Grammar.params; ECMAScript's `${ Expression[+In] }`: + // `{ in: true }`): the parameters it names are set or cleared there, the others copied. + holeCtx?: Readonly>; } /** When the regex token's `/` is a division operator instead of a regex literal. */ @@ -573,9 +576,13 @@ export interface PrecLevel { * lbp (left-chaining, like a ladder op's rhs) instead of as a full expression. */ export interface LedPrec { connector: string; // the led's first literal after the self-operand ('?', 'in', 'as', …) + // One of sameAs / below, unless the entry only gates the led (`when` alone: no binding power). sameAs?: string; // lbp = lbp(thisLadderOp) below?: string; // lbp = lbp(thisLadderOp) - 1 chainRhs?: boolean; // trailing self-operand at this lbp (default: full expression) + // The led exists only where this condition over the context parameters holds (a `when` + // condition: ECMAScript's `[+In] RelationalExpression in ShiftExpression` is `when: '+in'`). + when?: string; } // Every node may carry an author-written NAME (src/api.ts `arm` / `field`; read through @@ -594,11 +601,10 @@ type RuleExprNode = // every consumer reads it from the reference and none infers it from the parse context. | { type: 'ref'; name: string; hole?: string } | { type: 'quantifier'; body: RuleExpr; kind: '*' | '+' | '?' } - // `ctxMode` marks a subtree as [Await]/[Yield] context (the spec's grammar parameter): - // every parser (the interpreter, the jsTarget parser, the portable IR's `ctx` step) parses the - // body with the context word set to the marker's (grammar-utils.ts ctxWordOfMode). - // Every OTHER consumer treats this exactly like a plain transparent group (recurse - // into `body`), so the marker is invisible outside the parsers. + // `ctx`: the equations of the grammar's context parameters for the body (api.ts `ctx`; the + // spec's `[+Yield]` / `[~In]` at a reference): every parser parses the body with the named + // parameters set or cleared and the others copied (grammar-utils.ts ctxEquation). Every OTHER + // consumer treats it as a plain transparent group (recurse into `body`). // `treeSitterRelaxed`: a TREE-SITTER-ONLY alternate rendering. The parser (and every other // generator) uses `body` — the strict form; gen-tree-sitter renders `treeSitterRelaxed` instead. // Lets a PARSER-only constraint that is correct but tree-sitter-GLR-hostile (e.g. @@ -618,11 +624,12 @@ type RuleExprNode = // as a shared rule of this name and renders each reference as `$.` — sharing its // states instead of inlining (and duplicating) them at every use site (issue #46). // Visibility follows tree-sitter's `_`-prefix convention. - // `when`: a condition over the context word (grammar-utils.ts CTX_PARAMS, whenTest): the body - // exists only where it holds (`when('+yield', ...)`; an empty body is a zero-width test). The - // parsers read it (the fork evaluates it per family, the portable IR tests the word); every - // other consumer (tree-sitter, TextMate, Monarch, shapes) sees a transparent group: erased. - | { type: 'group'; body: RuleExpr; suppress?: string[]; ctxMode?: 'await' | 'yield' | 'asyncgen' | 'reset'; when?: string; treeSitterRelaxed?: RuleExpr; treeSitterRuleName?: string; capBelow?: string; atLevel?: string } // suppress: LED connectors disabled while parsing body (e.g. no-`in`) + // `when`: a condition over the grammar's context parameters (Grammar.params; grammar-utils.ts + // whenTest): the body exists only where it holds (`when('+yield', ...)`; an empty body is a + // zero-width test; `[$, when('+in', 'in'), $]` gates a led). The parsers read it; every other + // consumer (tree-sitter, TextMate, Monarch, shapes) sees a transparent group: erased (inside a + // `not`, dropped: grammar-utils.ts notStaticBody). + | { type: 'group'; body: RuleExpr; ctx?: Readonly>; when?: string; treeSitterRelaxed?: RuleExpr; treeSitterRuleName?: string; capBelow?: string; atLevel?: string } // Zero-width negative lookahead: matches (consuming nothing) iff `body` does // NOT match at the current position. Used to express disambiguations the // longest-match parser can't reach by structure alone (e.g. a `<…>` type-arg @@ -634,11 +641,10 @@ type RuleExprNode = // identifier token are reserved (gen-textmate collectReservedWords), the `>`-led // punctuators it tests (grammar-utils gtComposites), a `not(L)` before an // optional `L…` (gen-tree-sitter's lowering). - // `reservable`: this is the bare-identifier reserved-word guard (notReservedExpr). - // Every parser also refuses the words the context word in force reserves (grammar-utils.ts - // CTX_WORDS) — so `await`/`yield` lose their identifier reading inside an async/generator - // body; the portable IR as an `aheadCtx` step. Invisible elsewhere. - | { type: 'not'; body: RuleExpr; reservable?: boolean } + // A `when(cond, 'word')` item of its alternation is refused only where cond holds (the + // reserved-word guard's `[~Yield] yield`: grammar-utils.ts notCtxWords; the portable IR's + // `aheadCtx` step); every consumer but the parsers drops it (notStaticBody). + | { type: 'not'; body: RuleExpr } // Zero-width "no LineTerminator here" assertion: matches (consuming nothing) // iff the NEXT token is on the same line (no preceding newline). Encodes // ECMAScript/TS restricted productions like an array/indexed-access type's `[`, @@ -698,6 +704,9 @@ export interface Grammar { tokens: TokenDecl[]; precs: PrecLevel[]; ledPrecs?: LedPrec[]; + // The context parameters (docs/GRAMMAR.md "Contexts"): name -> value at entry, in bit order + // (grammar-utils.ts whenTest / ctxEquation). Absent: none (a `when` or `ctx` is refused). + params?: Readonly>; // The `>` re-scan, DECLARED: `>` closes a bracket (TypeScript's type arguments, a JSX tag) where // a `>`-led operator could also begin, so the lexer scans every `>` alone and the parser composes // `>>`, `>=`, `>>>=` … from adjacent single `>` tokens where it reads an operator (tsc's diff --git a/src/interpreter/assign-targets-cst.ts b/src/interpreter/assign-targets-cst.ts index 9f275736..2cc5fff6 100644 --- a/src/interpreter/assign-targets-cst.ts +++ b/src/interpreter/assign-targets-cst.ts @@ -36,7 +36,7 @@ export function assignTargetWalker(grammar: Grammar, rules: Iterable, // One rule reference and nothing else (zero-width items aside). const unitOf = (e: RuleExpr): boolean => { if (isRule(e)) return true; - if (e.type === 'group' && e.suppress === undefined && e.ctxMode === undefined) return unitOf(e.body); + if (e.type === 'group') return unitOf(e.body); // a group builds no node (ctx and when ones included) if (e.type !== 'seq') return false; const own = e.items.filter((x) => !isZeroWidthMarker(x.type)); return own.length === 1 && unitOf(own[0]!); diff --git a/src/interpreter/interpreter.ts b/src/interpreter/interpreter.ts index f47f130c..169aa598 100644 --- a/src/interpreter/interpreter.ts +++ b/src/interpreter/interpreter.ts @@ -1,5 +1,5 @@ import type { Grammar, RuleExpr, RuleDecl } from '../grammar/types.ts'; -import { CTX_SPAN, ctxReserves, ctxWordOfMode, gtComposites, isKeywordLiteral, readsSyncFn, whenTest } from '../grammar/grammar-utils.ts'; +import { ctxEquation, ctxSpan, gtComposites, isKeywordLiteral, notCtxWords, notStaticBody, whenTest } from '../grammar/grammar-utils.ts'; import { analyzeGrammar, findEntryRule, markupContainerOf } from '../grammar/grammar-analysis.ts'; import { compileTokenizer, lexSpecOf, type Token } from './lexer.ts'; import { assignTargetWalker } from './assign-targets-cst.ts'; @@ -40,8 +40,13 @@ export function createParser(grammar: Grammar) { tokenizers.set(grammar, lex); } const tokenize = lex; - // The context word's value under each context marker (grammar-utils.ts ctxWordOfMode). - const splitSync = readsSyncFn(grammar); + // A memo key joins a position with the context word: pos * CTX_SPAN + word. + const CTX_SPAN = ctxSpan(grammar.params); + const holeCtx = grammar.tokens.find((t) => t.template?.holeCtx !== undefined)?.template?.holeCtx; + const holeEq = holeCtx !== undefined ? ctxEquation(holeCtx, grammar.params) : null; + const whenTests = new Map(), ctxEqs = new Map(); + const whenOf = (cond: string) => whenTests.get(cond) ?? whenTests.set(cond, whenTest(cond, grammar.params)).get(cond)!; + const eqOf = (eqs: Readonly>) => ctxEqs.get(eqs) ?? ctxEqs.set(eqs, ctxEquation(eqs, grammar.params)).get(eqs)!; const tokenNames = new Set(grammar.tokens.map(t => t.name)); @@ -82,10 +87,15 @@ export function createParser(grammar: Grammar) { // connector literal has a declared LedPrec is precedence-gated; chainRhs leds must // end in a self-operand (the trailing ref the chain re-parses at the level's bp). const ledPrecOf = new Map(); + // A gated led (LedPrec.when): it exists only where the word passes the test. + const ledWhenOf = new Map(); + const ledWhen = new Map((grammar.ledPrecs ?? []).flatMap((lp) => (lp.when !== undefined ? [[lp.connector, whenTest(lp.when, grammar.params)] as const] : []))); for (const [ruleName, { leds }] of prattClassified.entries()) { for (const led of leds) { const first = led.items[0]; if (first?.type !== 'literal') continue; + const gate = ledWhen.get(first.value); + if (gate !== undefined) ledWhenOf.set(led, gate); const lp = ledPrecByConnector.get(first.value); if (!lp) continue; if (lp.rhsBp !== null) { @@ -164,16 +174,25 @@ export function createParser(grammar: Grammar) { function selfAtLevel(e: RuleExpr | undefined, ruleName: string): boolean { return !!e && e.type === 'group' && e.atLevel !== undefined && selfRefName(e.body, ruleName); } - type MixfixInfo = { openLit: string; sepLit: string }; + // eq: the operand is read under a `ctx` group (the ternary's middle, [+In]): its equations, which + // the re-bind's re-parse runs in too. + type MixfixInfo = { openLit: string; sepLit: string; eq: { keep: number; set: number } | null }; + // The self operand, bare or inside a `ctx` group (its equations), or undefined. + function selfOperand(e: RuleExpr | undefined, ruleName: string): { keep: number; set: number } | null | undefined { + if (selfRefName(e, ruleName)) return null; + if (e?.type === 'group' && e.ctx !== undefined && e.when === undefined && selfRefName(e.body, ruleName)) return ctxEquation(e.ctx, grammar.params); + return undefined; + } // A continuation ` $self …` whose inner `$self` operand can // over-consume the `L2` the operator needs (e.g. ternary `? $ : $`, conditional // type `extends $ ? $ : $`). The re-bind retries that operand capped. function mixfixOf(items: RuleExpr[], ruleName: string): MixfixInfo | null { + const eq = selfOperand(items[1], ruleName); if (items.length >= 4 && items[0]?.type === 'literal' - && selfRefName(items[1], ruleName) + && eq !== undefined && items[2]?.type === 'literal') { - return { openLit: items[0].value, sepLit: items[2].value }; + return { openLit: items[0].value, sepLit: items[2].value, eq }; } return null; } @@ -318,8 +337,11 @@ export function createParser(grammar: Grammar) { // token is an ident-kind whose text equals it — exactly `kwSet.has(tok.text)`. Pure-keyword // bodies only (a punctuation literal would need matchLiteral's split-`>` semantics) → else // the recursive path stands. `null` cached = no fast form for this node. - const notKwCache = new Map | null>(); - function notKwSet(notNode: RuleExpr): Set | null { + const notKwCache = new Map(); + // The keywords a guard refuses, and those it refuses only where a condition holds (its `when` + // items: grammar-utils.ts notCtxWords); null when its body is not keywords alone. + type NotKw = { kw: Set; ctxw: Array<{ text: string; mask: number; val: number }> }; + function notKwSet(notNode: RuleExpr): NotKw | null { const cached = notKwCache.get(notNode); if (cached !== undefined) return cached; const set = new Set(); @@ -328,7 +350,8 @@ export function createParser(grammar: Grammar) { : e.type === 'alt' ? e.items.every(collect) : false; const body = (notNode as Extract).body; - const result = collect(body) && set.size > 0 ? set : null; + const ctxw = notCtxWords(body, grammar.params); + const result = collect(notStaticBody(body)) && set.size > 0 && ctxw.every((w) => isKeywordLiteral(w.text)) ? { kw: set, ctxw } : null; notKwCache.set(notNode, result); return result; } @@ -348,7 +371,7 @@ export function createParser(grammar: Grammar) { // Packrat memo for pratt/left-recursive rules (Expr, Type, …): cache the // parse result + end position by start position, so backtracking doesn't // re-parse the same rule at the same spot. Sound because a rule's result is - // a function of its start position alone (the suppressed and capped parses + // a function of its start position and context word (the capped parses // that are not bypass the memo — see parseRule). The result includes the node's // cap (`_prattCapped`): a hit restores it, so a construct that reads it after a // trailing self operand (cap propagation) sees the same flag as a fresh parse. @@ -433,16 +456,9 @@ export function createParser(grammar: Grammar) { return null; } - // LED-connector exclusion (no-`in`-style contexts). `suppressNext` is set by a - // `group` node carrying `suppress`, then consumed by the NEXT pratt/left-rec - // rule it wraps; `suppressCur` is that rule's active exclusion. Recursive - // parsePratt (operator RHS) inherit it; a nested parseRule (bracketed group, - // operand of a non-op LED) resets it — matching the spec's [~In] propagation. - let suppressNext: Set | null = null; // The node before the item the current sequence is matching, for a target check that opens an // opt / alternation branch (matchSeqAssignTargets); undefined at a rule's start. let assignTargetPrev: CstChild | undefined; - let suppressCur: Set | null = null; // A reference to the template token, matched at the current position: the token itself (a // template with no holes), or a head·hole·(middle·hole)*·tail chain whose holes are parsed @@ -463,7 +479,11 @@ export function createParser(grammar: Grammar) { // expression and every span must continue (middle) or close (tail) — an // unterminated template is a parse failure, not a shorter match while (true) { - const exprNode = parseRule(hole); + // A hole is parsed in the word its template's equations make (TemplateDelimiters.holeCtx). + const outer = ctxWord; + if (holeEq !== null) ctxWord = (ctxWord & holeEq.keep) | holeEq.set; + let exprNode: CstNode | null; + try { exprNode = parseRule(hole); } finally { ctxWord = outer; } if (!exprNode) { pos = save; return null; } children.push(exprNode); const next = peek(); @@ -499,34 +519,25 @@ export function createParser(grammar: Grammar) { // Non-recursive rules don't reset context and aren't memoized. if (!isPratt && !isLeftRec) return parseNonRec(rule); - // Consume any pending LED exclusion: it applies to THIS rule only, so clear - // the pending slot first (nested parseRule calls reset to allow-in). - const mySup = suppressNext; - suppressNext = null; - - // Memoizable (pratt / left-recursive): look up by start position. A - // suppressed parse (no-`in` context) or a capped parse (parseLimit active, - // from the mixfix re-bind retry) is context/position+cap dependent, so it - // bypasses the position-keyed packrat memo entirely. + // Memoizable (pratt / left-recursive): look up by start position and the context word it + // reads. A capped parse (parseLimit active, from the mixfix re-bind retry) is + // position+cap dependent, so it bypasses the memo entirely. const capped = parseLimit >= 0; const start = pos; let m = memo.get(name); const key = start * CTX_SPAN + (ctxWord & ctxObserve.get(name)!); - const hit = !mySup && !capped ? m && m.get(key) : undefined; + const hit = !capped ? m && m.get(key) : undefined; // A hit met inside a verifying re-parse is returned: verifying it too would re-parse every // nesting level again (exponential in depth); each entry is still verified where it is hit // outside one. const verify = hit !== undefined && MEMO_VERIFY && !memoVerifying; if (hit !== undefined && !verify) { pos = hit.end; _prattCapped = hit.capped; return hit.node; } - const prevSup = suppressCur; - suppressCur = mySup; let result: CstNode | null; if (verify) memoVerifying = true; try { result = isPratt ? parsePratt(rule, 0) : parseLeftRec(rule); } finally { - suppressCur = prevSup; if (verify) memoVerifying = false; } if (verify) { // MEMO_VERIFY: the entry must be what the parse it stands for returns @@ -536,7 +547,7 @@ export function createParser(grammar: Grammar) { } return result; } - if (!mySup && !capped) { + if (!capped) { if (!m) { m = new Map(); memo.set(name, m); } m.set(key, { node: result, end: pos, capped: isPratt && result !== null && _prattCapped }); } @@ -809,9 +820,9 @@ export function createParser(grammar: Grammar) { for (const led of leds) { if (led.items[0]?.type === 'op' || led.items[0]?.type === 'postfix') continue; if (tailClosed && accessTailLeds.has(led.items)) continue; // no access tail after a postfix - // Skip a LED whose connector is excluded in this context (e.g. `in` under - // a no-`in` for-head) — it rebinds to the enclosing rule instead. - if (suppressCur && led.items[0]?.type === 'literal' && suppressCur.has(led.items[0].value)) continue; + // A gated led (`in` under [~In]) exists only where the word passes its test. + const gate = ledWhenOf.get(led); + if (gate !== undefined && (ctxWord & gate.mask) !== gate.val) continue; // Precedence gate for alternative-form LEDs: without it they bind maximally // tight (`a == b ? c : d` mis-grouped as `a == (b ? c : d)`). const lp = ledPrecOf.get(led); @@ -996,23 +1007,15 @@ export function createParser(grammar: Grammar) { assignTargetPrev = outerPrev; return node ? [node] : null; } - // A `suppress`-carrying group disables the listed LED connectors for the - // rule it wraps: stage them for the next parseRule to pick up. The staging ends with - // the group: a body that never enters that rule (its FIRST set refuses the token, so - // `exclude('in', Expr)` before a `;` matches nothing) leaves nothing staged for the - // NEXT rule after the group (`for (; a in b;)` reads its `in`). // A `when` group exists only where its condition holds over the word in force. - if (expr.when !== undefined) { const w = whenTest(expr.when); if ((ctxWord & w.mask) !== w.val) return null; } - // A context marker parses its body in its word, then puts back the one in force. - if (expr.ctxMode) { - const outer = ctxWord; ctxWord = ctxWordOfMode(expr.ctxMode, splitSync); + if (expr.when !== undefined) { const w = whenOf(expr.when); if ((ctxWord & w.mask) !== w.val) return null; } + // A `ctx` group parses its body in the word its equations make, then puts back the one in force. + if (expr.ctx !== undefined) { + const e = eqOf(expr.ctx); + const outer = ctxWord; ctxWord = (ctxWord & e.keep) | e.set; try { return matchExpr(expr.body); } finally { ctxWord = outer; } } - if (!expr.suppress || !expr.suppress.length) return matchExpr(expr.body); - suppressNext = new Set(expr.suppress); - const r = matchExpr(expr.body); - suppressNext = null; - return r; + return matchExpr(expr.body); } case 'not': { // Zero-width negative lookahead: succeed (no children) iff the body @@ -1020,10 +1023,9 @@ export function createParser(grammar: Grammar) { const kw = notKwSet(expr); if (kw) { // fast path: one membership test const tok = peek(); - const hit = !!tok && tok.type !== '' && tokenNames.has(tok.type) && (kw.has(tok.text) || (!!expr.reservable && ctxReserves(ctxWord, tok.text))); + const hit = !!tok && tok.type !== '' && tokenNames.has(tok.type) && (kw.kw.has(tok.text) || kw.ctxw.some((w) => (ctxWord & w.mask) === w.val && w.text === tok.text)); return hit ? null : []; } - if (expr.reservable) throw new Error('interpreter: a reservable guard must test keywords'); const saved = pos; const m = matchExpr(expr.body); pos = saved; @@ -1186,7 +1188,12 @@ export function createParser(grammar: Grammar) { // token at the *same* bracket depth as `openLit`, freeing that token for the // operator's own separator, then match `sepLit` and the rest uncapped. // `pos` is at `openLit` on entry. Returns the LED children or null (restored). - function matchMixfixLed(led: { items: RuleExpr[] }, ruleName: string, info: { openLit: string; sepLit: string }): CstChild[] | null { + function matchMixfixLed(led: { items: RuleExpr[] }, ruleName: string, info: MixfixInfo): CstChild[] | null { + const parseOperand = (): CstNode | null => { + if (info.eq === null) return parseRule(ruleName); + const outer = ctxWord; ctxWord = (ctxWord & info.eq.keep) | info.eq.set; + try { return parseRule(ruleName); } finally { ctxWord = outer; } + }; const saved = pos; const openLeaf = matchLiteral(info.openLit); if (!openLeaf) { pos = saved; return null; } @@ -1195,7 +1202,7 @@ export function createParser(grammar: Grammar) { // Greedy parse of the operand, to (a) confirm the separator is missing right // after it (otherwise the failure is elsewhere → don't apply) and (b) bound // the scan window. - const operand = parseRule(ruleName); + const operand = parseOperand(); if (!operand) { pos = saved; return null; } const greedyEnd = pos; // If the separator DOES match here, the LED's failure was later in `rest`, @@ -1222,7 +1229,7 @@ export function createParser(grammar: Grammar) { pos = afterOpen; const prevLimit = parseLimit; parseLimit = sepIdx; - const reOperand = parseRule(ruleName); + const reOperand = parseOperand(); parseLimit = prevLimit; if (!reOperand || pos !== sepIdx) continue; diff --git a/src/ir/assign-targets.ts b/src/ir/assign-targets.ts index 3c6929fd..2cbc2df9 100644 --- a/src/ir/assign-targets.ts +++ b/src/ir/assign-targets.ts @@ -55,7 +55,7 @@ function* walk(steps: Step[]): Generator { switch (s.t) { case 'star': yield* walk([s.step]); break; case 'sep': yield* walk([s.elem]); break; - case 'opt': case 'seq': case 'suppress': case 'ctx': yield* walk(s.steps); break; + case 'opt': case 'seq': case 'ctx': yield* walk(s.steps); break; case 'alt': for (const b of s.branches) yield* walk(b); break; default: break; } @@ -230,7 +230,7 @@ export function planAssignTargets(grammar: Grammar, rules: RuleIR[]): AssignTarg break; case 'rule': case 'ruleBp': prev = s.name; break; case 'lit': case 'altlit': case 'ahead': case 'aheadCtx': case 'sameLine': break; - case 'seq': case 'suppress': case 'ctx': prev = before(s.steps, prev); break; + case 'seq': case 'ctx': prev = before(s.steps, prev); break; case 'opt': before(s.steps, prev); prev = null; break; case 'alt': { const inherit = disjointLeads(s.branches) ? prev : null; s.branches.forEach((b) => before(b, inherit)); prev = null; break; } case 'star': before([s.step], null); prev = null; break; diff --git a/src/ir/decision-report.ts b/src/ir/decision-report.ts index b5a7cbb7..c9a49a52 100644 --- a/src/ir/decision-report.ts +++ b/src/ir/decision-report.ts @@ -60,20 +60,20 @@ function show(ir: ParserIR, s: Step, d = 0): string { case 'sameLine': return 'sameLine'; case 'when': return `when(${s.mask}:${s.val})`; case 'assignTarget': return `assignTarget(${s.ctx})`; - case 'suppress': case 'ctx': return sub(s.steps); + case 'ctx': return sub(s.steps); } } // ── the plan's facts, read per step ── const zeroWidth = (s: Step) => s.t === 'ahead' || s.t === 'aheadCtx' || s.t === 'sameLine' || s.t === 'when' || s.t === 'assignTarget' || s.t === 'look'; -const neverFails = (s: Step): boolean => s.t === 'star' || s.t === 'opt' || s.t === 'sep' || ((s.t === 'seq' || s.t === 'suppress' || s.t === 'ctx') && s.steps.every(neverFails)); +const neverFails = (s: Step): boolean => s.t === 'star' || s.t === 'opt' || s.t === 'sep' || ((s.t === 'seq' || s.t === 'ctx') && s.steps.every(neverFails)); // Why a body that is not clean can fail after it consumed: where it consumes first. function dirtyAfter(ir: ParserIR, steps: Step[]): string { const j = steps.findIndex((x) => !zeroWidth(x)); if (j < 0) return 'it can fail'; const x = steps[j]!; if (steps.length === j + 1 && (x.t === 'rule' || x.t === 'ruleBp')) return `a call of ${x.name} can fail after its operand (an operator that requires an assignment target)`; - if (steps.length === j + 1 && (x.t === 'seq' || x.t === 'suppress' || x.t === 'ctx')) return dirtyAfter(ir, x.steps); + if (steps.length === j + 1 && (x.t === 'seq' || x.t === 'ctx')) return dirtyAfter(ir, x.steps); return `it can fail after ${code(clip(show(ir, x), 40))}`; } @@ -298,7 +298,7 @@ function stepSites(ir: ParserIR, r: ParserIR['rules'][number], rf: ParserIR['rul out.push({ kind: s.t, where: at, text: show(ir, s), mode: guarded ? 'one' : 'attempt', mark: !s.clean, why: (s.clean ? '' : dirtyAfter(ir, body)) + (rustOnly ? ' [guard: Rust only]' : '') }); const bf = sf.t === 'star' ? [sf.step] : sf.t === 'sep' ? [sf.elem] : (sf as { steps: Step[] }).steps; body.forEach((x, k) => visit(x, bf[k] ?? x, at)); - } else if (s.t === 'seq' || s.t === 'suppress' || s.t === 'ctx') { + } else if (s.t === 'seq' || s.t === 'ctx') { const ff = (sf as { steps?: Step[] }).steps ?? s.steps; s.steps.forEach((x, k) => visit(x, ff[k] ?? x, at)); } diff --git a/src/ir/parser-ir.ts b/src/ir/parser-ir.ts index 4cc28805..f5a89460 100644 --- a/src/ir/parser-ir.ts +++ b/src/ir/parser-ir.ts @@ -26,7 +26,7 @@ import { identifierClassesOf } from '../grammar/uni-ident.ts'; import { planAssignTargets, type ArmForm } from './assign-targets.ts'; import { KIND, analyzeGrammar, concreteFirst, directivesOf, findEntryRule, tagOpenOnlyOpensTags } from '../grammar/grammar-analysis.ts'; import { nameRule, syntaxKey, type RuleNames } from '../grammar/grammar-names.ts'; -import { CTX_WORDS, CTX_WORD_BITS, collectLiterals, ctxWordOfMode, gtComposites, isKeywordLiteral, readsSyncFn, whenTest, type CtxMode } from '../grammar/grammar-utils.ts'; +import { collectLiterals, ctxEquation, gtComposites, isKeywordLiteral, notCtxWords, notStaticBody, whenTest } from '../grammar/grammar-utils.ts'; import { tokenPatternCharLoop } from '../grammar/token-pattern.ts'; import { type TextUnits, firstUnit, oneUnit, unitLen } from '../grammar/text-units.ts'; import { scannedTokens, templateLiterals, tokenLiterals } from './lex-family.ts'; @@ -142,43 +142,36 @@ type StepOp = | { t: 'seq'; steps: Step[]; share?: number } // a grouped sub-sequence (e.g. a star body `(',' Expr)`) | { t: 'sameLine' } // zero-width: the next token is on the same line (no preceding newline) | { t: 'assignTarget'; ctx: string; mask?: number } // zero-width: the node just returned passes target context ctx (its pass bit: mask; assign-targets.ts) - | { t: 'suppress'; set: number; steps: Step[]; share?: number } // parse the body with the LED connectors of ParserIR.suppressSets[set] disabled (no-`in` context) - | { t: 'ctx'; ctx: Ctx; steps: Step[]; share?: number } // parse the body in [Await]/[Yield] context `ctx`, then put back the one in force + | { t: 'ctx'; keep: number; set: number; steps: Step[]; share?: number } // parse the body in the word `(word & keep) | set` (ctxWord), then put back the one in force | { t: 'when'; mask: number; val: number }; // zero-width: the context word in force passes `(word & mask) === val` (api.ts `when`) export type Alt = Step[]; /** A `when` group (api.ts `when`) as steps: the word test, then the items (none: the test alone). */ -const whenOf = (cond: string, steps: Step[]): Step => { const w: Step = { t: 'when', ...whenTest(cond) }; return steps.length === 0 ? w : { t: 'seq', steps: [w, ...steps] }; }; +const whenOf = (test: { mask: number; val: number }, steps: Step[]): Step => { const w: Step = { t: 'when', ...test }; return steps.length === 0 ? w : { t: 'seq', steps: [w, ...steps] }; }; +/** The word a `ctx` step's body runs in, as an expression over the word `cur` in force: a + * constant where the equations fix every parameter (a function body's), else the kept bits of + * `cur` with the set ones. One spelling for every printer (`&`, `|` and parentheses read alike + * in TS, Go and Rust). */ +export const ctxWord = (keep: number, set: number, cur: string): string => (keep === 0 ? String(set) : set === 0 ? `(${cur} & ${keep})` : `((${cur} & ${keep}) | ${set})`); /** A step's (or step list's) structure as a string, without its names: the key under which two * equal structures are one computation (a lookahead body, a shared step). */ export function stepKey(s: Step | readonly Step[]): string { return JSON.stringify(s, (k, v) => (k === 'field' || k === 'branchNames' || k === 'src' ? undefined : v)); } -// The ECMAScript [Await] / [Yield] grammar parameters: the context a body is parsed in, as one word -// a parser holds (bit CTX_AWAIT: `await` is the operator, bit CTX_YIELD: `yield` is). The grammar -// marks each body that sets it (awaitCtx / yieldCtx / asyncGenCtx, resetCtx for the bodies that set -// none: a plain function, an accessor, a field initializer); a `ctx` step is such a body. What the -// context decides is whether those words are reserved: an identifier's reserved-word guard -// (`reservableNot`) also refuses the context's operator words, so it is an `aheadCtx` test: its -// words' set, or a word of ParserIR.ctxWords whose bit the context has. Every other step reads the parser's state as it always did, so a parse is -// the same function of (position, state) with the context one more part of the state: a step or a -// lookahead that two contexts share is one computation, and nothing keyed on rule and position is -// kept that the context would have to join (the portable parsers keep no memo; a Doc reuses only -// the entry rule's top-level entries, which are parsed in the entry's context, CTX_NONE). -// A `ctx` step restores the context it found on success and on failure alike, so the context in -// force is always that of the innermost enclosing body. -// A `when` step (api.ts `when`) tests the word: an item or an arm exists only where its condition -// holds (`yield`'s operator arm: +yield), and a gated prefix operator (`await`: PrattRule.prefix's -// `when`) is an operator only there. The word's bits are grammar-utils.ts CTX_PARAMS: bit 4 -// (`syncFn`, transitional, see there) is set by a reset body only in a grammar that reads it. -export const CTX_NONE = 0, CTX_AWAIT = 1, CTX_YIELD = 2; -export type Ctx = number; -/** The bits of the word an `aheadCtx` test reads (grammar-utils.ts CTX_WORDS, shared with the interpreter and jsTarget). */ -export { CTX_WORD_BITS }; -// The LED connectors a `suppress` step disables (`exclude('in', Expr)`: no `in` in a for-head) are -// a constant of the grammar at each site, so a parser never builds one at run time. The grammar -// analysis keeps each distinct set once (ParserIR.suppressSets, sorted; set 0 is the empty set, the -// state outside every suppress step) and decides which sets disable a led (PrattRule.ledSuppressedIn), -// so a parser holds the index of the set in force and a target tests an index, never a set. +// The grammar's context parameters (Grammar.params; ECMAScript's [Await], [Yield], [In]): the +// context a body is parsed in, as one word a parser holds (bit k set: parameter k differs from its +// entry value, so the entry word is 0). A `ctx` step (api.ts `ctx`) parses its body in the word +// its equations make (ctxWord) and restores the word it found on success and on failure alike, so +// the word in force is always that of the innermost enclosing body. A `when` step tests the word: +// an item or an arm exists only where its condition holds (`yield`'s operator arm: +yield), a +// gated prefix operator (`await`: PrattRule.prefix's `when`) and a gated led (`in`: +// PrattRule.ledWhen) only there. An identifier's reserved-word guard refuses some words only in a +// context (its `when` items: grammar-utils.ts notCtxWords), so it is an `aheadCtx` test: its +// words' set, or a word of ParserIR.ctxWords whose bit the word has. Every other step reads the +// parser's state as it always did, so a parse is the same function of (position, state) with the +// context one more part of the state: a step or a lookahead that two contexts share is one +// computation, and nothing keyed on rule and position is kept that the context would have to join +// (the portable parsers keep no memo; a Doc reuses only the entry rule's top-level entries, which +// are parsed in the entry word, 0). // One token, tested without consuming it: a member is a literal text (the token's lid) or a token // kind (its kid). A lookahead whose body reads exactly one token — `not(alt('(', '=', …))`, or // `not(not(alt(Ident, String, '[')))` — is this test, so buildIR lowers it to an `ahead` step over @@ -330,7 +323,7 @@ export type Guard = { first: GuardSet | null; second: GuardSet | null; lead: Lea export type Pair = { when: GuardSet; second: GuardSet }; /** One test of the buffered token: whether it is in ParserIR.tokenSets[set] — or, with `ctx`, a * word the context in force reserves (ParserIR.ctxWords) — compared with `is`. */ -export type LeadTest = { set: number; is: boolean; ctx: boolean }; +export type LeadTest = { set: number; is: boolean; ctx: number }; // ctx: an `aheadCtx` test, the word bits its context words read (ctxWordBits; 0: an `ahead` test) /** The steps a candidate runs inside its frame: those after the tests its guard took over. */ export const guardedSteps = (g: Guard, steps: Step[]): Step[] => (g === null || g.skip === 0 ? steps : steps.slice(g.skip)); /** A member of ParserIR.tokenSets, by its index and its members. */ @@ -521,7 +514,7 @@ export type PrattRule = { ledLbp: Array; // parallel to leds: precedence gate (ternary/in/instanceof) — bind only when lbp > minBp; null = bind maximally tight ledSameLine: boolean[]; // parallel to leds: a leading `sameLine` guard (TS type tails) — the connector must be on the operand's line ledNotLeftLeaf: Array; // parallel to leds: skip this led when the left node's head-leaf text is in this set (`void.x` etc.) - ledSuppressedIn: number[][]; // parallel to leds: the ParserIR.suppressSets that hold its connector — the led is tried only while the set in force is none of them + ledWhen: Array<{ mask: number; val: number } | null>; // parallel to leds: a gated led (LedPrec.when: `in` under [~In]) is tried only where the word passes (word & mask) === val ledForm: number[]; // parallel to leds: the built node's form (a binary-connector led, `a < T >`/`a as T`, is not a target; with target contexts, plus its leaf bits) // Present iff the grammar declares target contexts (assign-targets.ts): each NUD arm's form // (parallel to nudOrder), a postfix token arm's, the binary node's (its leaf bits; accLeft: the @@ -599,6 +592,9 @@ export type TplCfg = { // One well-formed escape (the token's `escapeValid`): an untagged template's opening span // rejects a `\` that does not begin one. Null when the token declares none. escapeValid: TokenPattern | null; + // The word each hole is parsed in, `(word & keep) | set` (ctxWord; TemplateDelimiters.holeCtx); + // null: the word in force. Every template matcher sets it around each hole and puts it back. + holeCtx: { keep: number; set: number } | null; }; /** Every rule that parses template holes in `ir` (a Pratt rule's template arms, a template `tok` @@ -686,7 +682,6 @@ export type ParserIR = { /** The display names of rules that declare one (RuleDecl.label), by rule name: what a missing * rule's `expected …` diagnostic names (total parsing); a rule without one is named by its name. */ ruleLabels: Record; - suppressSets: string[][]; // the connector sets `suppress` steps disable, indexed by Step.set; [0] is the empty set regexCtx: RegexCtx | null; // null unless the grammar has a regex token with context tpl: TplCfg | null; // null unless the grammar has a template token elements: ElementPlan | null; // null unless the grammar declares an element region @@ -963,22 +958,39 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { if (id === undefined) { id = lookaheads.length; lookaheads.push(steps); lookaheadIds.set(key, id); } return id; }; - // The suppress sets and which of them disable a led are the grammar analysis's (one definition, - // shared with the jsTarget parser of target-js.ts). - const { suppressSets } = a; - const suppressOf = (connectors: string[], steps: Step[]): Step => ({ t: 'suppress', set: a.suppressSetOf(connectors), steps }); - const splitSync = readsSyncFn(grammar); - const ctxOf = (mode: CtxMode, steps: Step[]): Step => ({ t: 'ctx', ctx: ctxWordOfMode(mode, splitSync), steps }); + const ctxOf = (eqs: Readonly>, steps: Step[]): Step => ({ t: 'ctx', ...ctxEquation(eqs, grammar.params), steps }); + const whenTestOf = (cond: string) => whenTest(cond, grammar.params); + // A gated led's test, by its connector (LedPrec.when). + const ledGate = new Map((grammar.ledPrecs ?? []).flatMap((lp) => (lp.when !== undefined ? [[lp.connector, whenTestOf(lp.when)] as const] : []))); // An identifier's reserved-word guard: the one-token test of its words and, in each context, the - // context's operator words. Its body is one token by construction (`reservableNot(alt(...))`). - // The words' set is a constant of the site, as every `ahead` set is; only the context's words - // are read at run time: a printer tests the set, then (outside every context, at the cost of one - // load) whether the token is a word the context reserves. - let ctxWords: string[] = []; - const reservableOf = (steps: Step[]): Step => { - const m = steps.length === 1 ? oneTokenOf(steps[0]) : null; - if (m === null) throw new Error('portable: a reservable guard must test one token'); - ctxWords = [...CTX_WORDS]; + // words it refuses only there (its `when` items, notCtxWords: `when('+yield', 'yield')`). The + // words' set is a constant of the site, as every `ahead` set is; only the context's words are + // read at run time: a printer tests the set, then (outside every context, at the cost of one + // load) whether the token is a word the context reserves. Each such word is refused where ONE + // bit is set (ParserIR.ctxWords[k] for bit 1 << k, one word per bit across the grammar); any + // other condition is refused by name. + const ctxWords: string[] = []; + const guardWords = (body: RuleExpr) => notCtxWords(body, grammar.params); + const collectCtxWords = (e: RuleExpr): void => { + if (!e || typeof e !== 'object') return; + if (e.type === 'not') { + for (const w of guardWords(e.body)) { + const k = Math.log2(w.mask); + if (!Number.isInteger(k) || w.val !== w.mask) throw new Error(`portable: a guard's context word '${w.text}' must be refused where one parameter differs from its entry value`); + if (ctxWords[k] !== undefined && ctxWords[k] !== w.text) throw new Error(`portable: context bit ${k} reserves both '${ctxWords[k]}' and '${w.text}'`); + ctxWords[k] = w.text; + } + } + if ('body' in e && e.body) collectCtxWords(e.body as RuleExpr); + if ('items' in e) (e.items as RuleExpr[]).forEach(collectCtxWords); + if (e.type === 'sep') collectCtxWords(e.element); + }; + grammar.rules.forEach((r) => collectCtxWords(r.body)); + const ctxBits = ctxWordBits({ ctxWords }); + const reservableOf = (body: RuleExpr): Step | null => { + if (guardWords(body).length === 0) return null; + const m = oneTokenOf(stepOf(notStaticBody(body))); + if (m === null) throw new Error('portable: a guard with context words must test one token'); return { t: 'aheadCtx', set: tokenSetOf(m), is: false }; }; // A negative lookahead. Over a one-token body it is the `ahead` test of that token's set, over @@ -1019,12 +1031,11 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { const lvl = a.atLevelBp(e); if (lvl !== null) return { t: 'ruleBp', name: (e.body as { name: string }).name, bp: lvl }; const ss = altSteps(e.body); - if (e.when !== undefined) return whenOf(e.when, ss); // a context condition (api.ts when) - if (e.ctxMode) return ctxOf(e.ctxMode, ss); // [Await]/[Yield] context - if (e.suppress && e.suppress.length) return suppressOf(e.suppress, ss); // no-`in` context + if (e.when !== undefined) return whenOf(whenTestOf(e.when), ss); // a context condition (api.ts when) + if (e.ctx !== undefined) return ctxOf(e.ctx, ss); // context equations (api.ts ctx) return ss.length === 1 ? ss[0] : { t: 'seq', steps: ss }; } - case 'not': return e.reservable ? reservableOf(altSteps(e.body)) : notOf(altSteps(e.body)); // zero-width negative lookahead + case 'not': return reservableOf(e.body) ?? notOf(altSteps(e.body)); // zero-width negative lookahead case 'sameLine': return { t: 'sameLine' }; // zero-width no-newline assertion case 'assignTarget': return { t: 'assignTarget', ctx: e.ctx }; // zero-width declared target check (assign-targets.ts) case 'seq': return { t: 'seq', steps: e.items.map(stepOf) }; // grouped sub-sequence (star/sep body) @@ -1092,7 +1103,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { // taken over (Guard.lead). Moving a test out of the candidate's frame onto the buffered token // changes nothing the candidate decides, because each such test (1) is zero-width and builds // nothing, (2) stands before every step that consumes, fails or changes the parser's state (the - // context, the suppress set: a `ctx` / `suppress` step is not a lead test, and none is looked + // context: a `ctx` step is not a lead test, and none is looked // through), so it reads the token at the candidate's start in the state the frame starts in, // and (3) reads only that token — its kind and literal, and for `aheadCtx` the context in force — // the token every target has already buffered there (a peek that reads no further than it, so @@ -1103,12 +1114,12 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { const lead: LeadTest[] = []; for (const s of steps) { if ((s.t !== 'ahead' && s.t !== 'aheadCtx') || ('share' in s && s.share !== undefined)) break; - const t: LeadTest = { set: s.set, is: s.is, ctx: s.t === 'aheadCtx' }; + const t: LeadTest = { set: s.set, is: s.is, ctx: s.t === 'aheadCtx' ? ctxBits : 0 }; const prev = lead[lead.length - 1]; if (prev !== undefined && !prev.is && !t.is) { // not in A, and not in B (or a context word): not in A ∪ B (or a context word) const x = tokenSets[prev.set]!, y = tokenSets[t.set]!; - lead[lead.length - 1] = { set: tokenSetOf({ lits: [...x.lits, ...y.lits], toks: [...x.toks, ...y.toks] }), is: false, ctx: prev.ctx || t.ctx }; + lead[lead.length - 1] = { set: tokenSetOf({ lits: [...x.lits, ...y.lits], toks: [...x.toks, ...y.toks] }), is: false, ctx: prev.ctx | t.ctx }; } else lead.push(t); skip++; } @@ -1135,7 +1146,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { const ks = [...kindsOf(l)]; const inS = (s: TokenSet, k: string) => s.lits.includes(l) || s.toks.includes(k); return ks.some((k) => (g.first === null || inS(g.first, k)) - && g.lead.every((x) => inS(tokenSets[x.set]!, k) === x.is || (x.ctx && ctxWords.includes(l)))); + && g.lead.every((x) => inS(tokenSets[x.set]!, k) === x.is || (x.ctx !== 0 && ctxWords.includes(l)))); }; const pairsOf = (items: RuleExpr[], gs: Guard[]): Guard[] => { const by = items.map((e, i) => (gs[i]?.first && gs[i]!.first!.toks.every((k) => !templateTokens.has(k)) && !a.exprNullable(e) ? a.exprSecondBy(e) : null)); @@ -1191,7 +1202,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { // left-recursive rules through it avoids the infinite left-recursion a plain rd rule would hit. names = nameRule(r); if (a.prattRules.has(r.name) || a.leftRecSet.has(r.name)) { - const p = buildPratt(r.name, r.body, a, names, stepOf, named, notOf, reservableOf, suppressOf, ctxOf, litTtype, altGuard, templateTokens); + const p = buildPratt(r.name, r.body, a, names, stepOf, named, notOf, reservableOf, ctxOf, whenTestOf, litTtype, altGuard, templateTokens); p.nudSeqGuard = p.nudSeqGuard.map((g, i) => leadOf(g, p.nudSeqs[i]!)); p.nudCappedGuard = p.nudCappedGuard.map((g, i) => leadOf(g, p.nudCapped[i]!.steps)); return p; @@ -1241,6 +1252,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { interpClose: tplTok.template.interpClose, braceOpen: tplTok.template.interpOpen.slice(-1), escapeValid: tplTok.escapeValidPattern ?? null, + holeCtx: tplTok.template.holeCtx !== undefined ? ctxEquation(tplTok.template.holeCtx, grammar.params) : null, }; } @@ -1283,7 +1295,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { return { lits: [...lits], toks: [...toks] }; } case 'seq': return seqFirst(s.steps); - case 'suppress': case 'ctx': return seqFirst(s.steps); + case 'ctx': return seqFirst(s.steps); case 'look': case 'ahead': case 'aheadCtx': case 'sameLine': case 'when': case 'assignTarget': case 'star': case 'opt': case 'sep': return null; // zero-width / nullable leading → unpredictable } }; @@ -1325,7 +1337,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { // It is emitted only where it can refuse a token the list is actually tried at: one that begins // another candidate of the same list. A refusal no such token reaches would be a test with // nothing to refute. - const concrete = concreteFirst(grammar, a, { kindsOf: (l) => [...kindsOf(l)], gtComps, maybeWords: CTX_WORDS }); + const concrete = concreteFirst(grammar, a, { kindsOf: (l) => [...kindsOf(l)], gtComps }); { const kinds = [...tokens.map((t) => t.name), ...(tpl ? ['$templateHead', '$templateMiddle', '$templateTail'] : [])]; const grammarLits = concrete.literals.filter((l) => !gtComps.includes(l)); @@ -1348,7 +1360,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { return { ...g!, lead: [{ set: tokenSetOf({ lits: [...s.lits, ...lits], toks: [...s.toks, ...toks] }), is: false, ctx: head.ctx }, ...g!.lead.slice(1)] }; } const set = tokenSetOf({ lits, toks }); - return g === null ? { first: null, second: null, lead: [{ set, is: false, ctx: false }], skip: 0 } : { ...g, lead: [{ set, is: false, ctx: false }, ...g.lead] }; + return g === null ? { first: null, second: null, lead: [{ set, is: false, ctx: 0 }], skip: 0 } : { ...g, lead: [{ set, is: false, ctx: 0 }, ...g.lead] }; }); } } @@ -1410,14 +1422,14 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { switch (s.t) { case 'lit': case 'tok': case 'altlit': case 'alt': case 'star': case 'opt': case 'sep': return true; case 'rule': case 'ruleBp': return cleanRules.has(s.name); - case 'seq': case 'suppress': case 'ctx': return listFailsClean(s.steps); + case 'seq': case 'ctx': return listFailsClean(s.steps); default: return zeroWidth(s); } }; // A list fails only where its first consuming step does when everything after that step cannot // fail (a star / opt / sep, or a group of them): before it only zero-width tests, which consume // nothing; so it fails clean when that step does (`[Target, opt(':' Type), opt('=' Expr)]`). - const neverFails = (s: Step): boolean => s.t === 'star' || s.t === 'opt' || s.t === 'sep' || ((s.t === 'seq' || s.t === 'suppress' || s.t === 'ctx') && s.steps.every(neverFails)); + const neverFails = (s: Step): boolean => s.t === 'star' || s.t === 'opt' || s.t === 'sep' || ((s.t === 'seq' || s.t === 'ctx') && s.steps.every(neverFails)); const listFailsClean = (steps: Step[]): boolean => { const j = steps.findIndex((x) => !zeroWidth(x)); return steps.length > 0 && (j < 0 || (failsClean(steps[j]!) && steps.slice(j + 1).every(neverFails))); @@ -1438,7 +1450,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { // or at that step, after leaves only. A led arm's block relies on the same fact for its // connector (ledClean). const isLeaf = (s: Step): boolean => s.t === 'lit' || s.t === 'altlit' || (s.t === 'tok' && s.hole === undefined); - const flatSeq = (steps: Step[]): Step[] => steps.flatMap((x) => (x.t === 'seq' ? flatSeq(x.steps) : [x])); + const flatSeq = (steps: Step[]): Step[] => steps.flatMap((x) => (x.t === 'seq' || x.t === 'ctx' ? flatSeq(x.steps) : [x])); const listFailsLeaves = (steps0: Step[]): boolean => { const steps = flatSeq(steps0); const j = steps.findIndex((x) => !zeroWidth(x) && !isLeaf(x)); @@ -1472,17 +1484,19 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { const d = x !== undefined && (x.t === 'rule' || x.t === 'ruleBp') ? dirtyAt.get(x.name) : undefined; return d !== undefined && refusesAll(next, d); }; - const annotateSteps = (steps: Step[]): void => { + // `after`: the step that follows the list where it is a `seq` or `ctx` body (both are run in + // place, so their last step is followed by the step after them). + const annotateSteps = (steps: Step[], after?: Step): void => { for (const [k, s] of steps.entries()) { - const next = steps[k + 1]; + const next = k + 1 < steps.length ? steps[k + 1] : after; if (s.t === 'star') { annotateSteps([s.step]); const g = bodyGuard([s.step]); if (g !== undefined) s.guard = g; if (failsClean(s.step) || doomed([s.step], next)) s.clean = true; else if (listFailsLeaves([s.step])) s.leaves = true; } else if (s.t === 'opt') { annotateSteps(s.steps); const g = bodyGuard(s.steps); if (g !== undefined) s.guard = g; if (listFailsClean(s.steps) || doomed(s.steps, next)) s.clean = true; else if (listFailsLeaves(s.steps)) s.leaves = true; } - else if (s.t === 'seq' || s.t === 'suppress' || s.t === 'ctx') annotateSteps(s.steps); + else if (s.t === 'seq' || s.t === 'ctx') annotateSteps(s.steps, next); else if (s.t === 'sep') { annotateSteps([s.elem]); const g = bodyGuard([s.elem]); if (g !== undefined) s.guard = g; if (failsClean(s.elem) || doomed([s.elem], next)) s.clean = true; else if (listFailsLeaves([s.elem])) s.leaves = true; } else if (s.t === 'alt') { s.firsts = s.branches.map((b) => seqFirst(b)); s.predictive = allDisjoint(s.firsts); - s.branches.forEach(annotateSteps); + s.branches.forEach((x) => annotateSteps(x)); s.clean = s.branches.map(restFailsClean); } } @@ -1492,19 +1506,19 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { r.altFirst = r.alts.map((alt) => seqFirst(alt)); r.predictive = allDisjoint(r.altFirst); if (!r.predictive && r.alts.length > 1) r.altDispatch = dispatchOf(r.altGuard.map((g) => g?.first ?? null)); - r.alts.forEach(annotateSteps); + r.alts.forEach((x) => annotateSteps(x)); r.clean = r.alts.every(listFailsClean); } else { r.nudSeqPredictive = allDisjoint(r.nudSeqs.map((seq) => seqFirst(seq))); - r.nudSeqs.forEach(annotateSteps); + r.nudSeqs.forEach((x) => annotateSteps(x)); r.nudCapped.forEach((c) => annotateSteps(c.steps)); r.nudBrackets.forEach((b) => annotateSteps(b.steps)); r.leds.forEach((b) => annotateSteps(b.steps)); r.ledClean = r.leds.map((b) => restFailsClean(b.steps.slice(1))); - r.ledSuppressedIn = r.leds.map((b) => a.suppressedIn(b.first)); + r.ledWhen = r.leds.map((b) => (b.first !== null ? ledGate.get(b.first) ?? null : null)); } } - lookaheads.forEach(annotateSteps); + lookaheads.forEach((x) => annotateSteps(x)); // ── Committed choices (Commit): the candidates each token can admit, per dispatch key ── { // The kinds a parser can buffer: a skipped token (trivia) never reaches it. @@ -1514,7 +1528,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { case 'lit': case 'tok': case 'altlit': return false; case 'rule': case 'ruleBp': return a.nullableRules.has(s.name); case 'alt': return s.branches.some(nullableList); - case 'seq': case 'suppress': case 'ctx': return nullableList(s.steps); + case 'seq': case 'ctx': return nullableList(s.steps); default: return true; // star / opt / sep, and every zero-width test } }; @@ -1563,7 +1577,7 @@ function buildIR(grammar: Grammar, facts: PortableFacts): ParserIR { const f = new Set(reuse.rules.flatMap((r) => [...concrete.first1({ type: 'ref', name: r })])); entrySync = { lits: [...f].filter((x) => !x.startsWith(KIND)), toks: [...f].filter((x) => x.startsWith(KIND)).map((x) => x.slice(KIND.length)) }; } - return { grammarName: grammar.name, entry, tokens, puncts, gtComps, rules, tokenSets, ctxWords, lookaheads, shared, forms, reuse, entrySync, ruleLabels: Object.fromEntries(grammar.rules.flatMap((r) => (r.label === undefined ? [] : [[r.name, r.label]]))), suppressSets, regexCtx, tpl, elements, newlineCfg, identToken, identLike, identPrefix, identClasses: identifierClassesOf(grammar.tokens), ...(assignTargets ? { assignTargets } : {}) }; + return { grammarName: grammar.name, entry, tokens, puncts, gtComps, rules, tokenSets, ctxWords, lookaheads, shared, forms, reuse, entrySync, ruleLabels: Object.fromEntries(grammar.rules.flatMap((r) => (r.label === undefined ? [] : [[r.name, r.label]]))), regexCtx, tpl, elements, newlineCfg, identToken, identLike, identPrefix, identClasses: identifierClassesOf(grammar.tokens), ...(assignTargets ? { assignTargets } : {}) }; } // The step lists a rule runs: an rd rule's alternatives, a Pratt rule's NUD and LED arms. @@ -1586,7 +1600,7 @@ const stepKids = (s: Step): Step[] => { switch (s.t) { case 'star': return [s.step]; case 'sep': return [s.elem]; - case 'opt': case 'seq': case 'suppress': case 'ctx': return s.steps; + case 'opt': case 'seq': case 'ctx': return s.steps; case 'alt': return s.branches.flat(); default: return []; } @@ -1599,7 +1613,7 @@ const stepKids = (s: Step): Step[] => { // matched, and builds nothing — no leaf, no children list, no node, no builder call. It examines // exactly the tokens the building form examines (the same peeks, the same moves back, in the same // order), so an entry's extent (EntryMeta.ext) is unchanged, and it reads and restores the parser's -// state (the suppress set, the [Await]/[Yield] context) exactly as the building form does. +// state (the context word) exactly as the building form does. // A rule a recognize-form step calls is recognized too: an rd rule has a recognize form (its // longest match compares end positions only, since the node a tie would choose is never seen); a // Pratt rule does not, because what it accepts reads the nodes it built (the head leaf a led tests, @@ -1616,7 +1630,7 @@ export type Forms = { recognizeShared: boolean[]; // parallel to ParserIR.shared: printed in recognize form lookBuilds: boolean[]; // parallel to ParserIR.lookaheads: its body runs a Pratt rule's building form /** The recognize-form functions that run no building form, directly or through anything they - * call: they read and move the token cursor alone (position, tokens, look extent, suppress set, + * call: they read and move the token cursor alone (position, tokens, look extent, context word, * context), so a target with several engine types may print them once, on the cursor. */ cursorOnly: { rules: string[]; shared: boolean[]; looks: boolean[] }; }; @@ -1624,7 +1638,7 @@ export type Forms = { // What a step runs, and under which frame, is decided here once: a star / opt / sep body (a step // inside a body), an ordered choice (each branch in a BRANCH frame, tried under its FIRST set when // that is small enough to test: isFirstGuardable), a predictive choice (only the branch its FIRST -// set selects), a suppress or ctx body (the state set around the body's conjunction), a shared +// set selects), a ctx body (the word set around the body's conjunction), a shared // step (ParserIR.shared: its function's call), and every leaf test. A StepLowering spells each // piece in one target's language, for one engine form (building or recognizing, ParserIR.forms) // over one receiver; it holds only that spelling. @@ -1659,10 +1673,9 @@ export type StepLowering = { aheadCtx(set: number, is: boolean): string; sameLine(): string; when(mask: number, val: number): string; // the context word in force passes (word & mask) === val - inPlace(kind: 'alt' | 'suppress' | 'ctx', stmts: string): string; // the step's statements (stepStmts) run where the step is + inPlace(kind: 'alt' | 'ctx', stmts: string): string; // the step's statements (stepStmts) run where the step is ret(cond: string): string; // statements returning cond - suppress(set: number, cond: string): string; // statements: cond with ParserIR.suppressSets[set] staged for the next Pratt call - ctx(ctx: Ctx, cond: string): string; // statements: cond in context ctx, the one in force put back after + ctx(keep: number, set: number, cond: string): string; // statements: cond in the word (word & keep) | set (ctxWord), the one in force put back after branch(cond: string, clean: boolean): string; // a BRANCH frame: returns true when cond matched, else undoes it (clean: the branch fails clean, so there is nothing to undo and no mark) guarded(first: NonNullable, branch: string): string; // the branch, tried only when the next token is in first choice(peek: boolean, tries: string[], total: boolean): string; // the tries in order, then false (total: the last try returns, nothing follows it); peek: a guard reads the next token @@ -1718,12 +1731,11 @@ export function stepBody(s: Step, L: StepLowering): string { case 'sameLine': return L.sameLine(); case 'when': return L.when(s.mask, s.val); case 'assignTarget': return need(L.assignTarget, 'assignTarget')(s.mask!); - case 'suppress': return L.inPlace('suppress', L.suppress(s.set, conjOf(s.steps, L))); - case 'ctx': return L.inPlace('ctx', L.ctx(s.ctx, conjOf(s.steps, L))); + case 'ctx': return L.inPlace('ctx', L.ctx(s.keep, s.set, conjOf(s.steps, L))); } } /** The step as the statements of a function returning whether it matched (a shared step's body; - * an `alt`, `suppress` or `ctx` step run in place). */ + * an `alt` or `ctx` step run in place). */ export function stepStmts(s: Step, L: StepLowering): string { switch (s.t) { case 'alt': { @@ -1742,8 +1754,7 @@ export function stepStmts(s: Step, L: StepLowering): string { }); return L.choice(tried.some((_, i) => isFirstGuardable(firsts[i] ?? null, n)), always < 0 ? tries : [...tries, L.ret('true')], always >= 0); } - case 'suppress': return L.suppress(s.set, conjOf(s.steps, L)); - case 'ctx': return L.ctx(s.ctx, conjOf(s.steps, L)); + case 'ctx': return L.ctx(s.keep, s.set, conjOf(s.steps, L)); default: return L.ret(stepBody(s, L)); } } @@ -1944,7 +1955,7 @@ export function entryShell(plan: ReusePlan, ids: LexIdPlan, L: EntryLowering): s } // ── The Pratt shell: how a Pratt rule's functions run, decided once ── -// Three functions: the entry (the suppress set staged for this call put in force), `bp` (a NUD, +// Three functions: the entry, `bp` (a NUD, // then the LED loop at a minimum binding power) and `nud` (every NUD arm the rule's Dispatch // admits, each a longest-match candidate). The LED loop tries, in order: the led groups (the leds // by their connector's lid, each arm under its guard; a group whose arms all failed ends the loop @@ -1959,7 +1970,7 @@ export type LedGuardLowering = { lbpAbove(lbp: number): string; // the led's precedence gate: lbp > minBp sameLine: string; // the connector is on the operand's line notLeftLeaf(words: string[]): string; // the left node's head-leaf text is none of words - notSuppressed(set: number): string; // the suppress set in force is not ParserIR.suppressSets[set] + when(mask: number, val: number): string; // a gated led: the context word in force passes (word & mask) === val ifAll(parts: string[]): string; // the `if` before the led's block ('' when nothing gates it) }; // How a NUD arm's node is capped: never; always (a capExpr arm: an assignment-level arrow); or @@ -2083,7 +2094,8 @@ export function prattShell(r: PrattRule, ir: Pick; - const isCompound = (s: Step): s is Compound => s.t === 'star' || s.t === 'opt' || s.t === 'sep' || s.t === 'alt' || s.t === 'seq' || s.t === 'suppress' || s.t === 'ctx'; + const isCompound = (s: Step): s is Compound => s.t === 'star' || s.t === 'opt' || s.t === 'sep' || s.t === 'alt' || s.t === 'seq' || s.t === 'ctx'; const kids = stepKids; // Each distinct compound step by its structure: its size (in steps, itself included), how often // each distinct compound child occurs in it, how often it stands directly in a root list, and @@ -2393,8 +2405,8 @@ function codesToRanges(codes: number[]): CharRange[] { // Binding powers come from the analysis (opTable/prefixOps), single-sourced with the interpreter. function buildPratt( name: string, body: RuleExpr, a: ReturnType, names: RuleNames, - stepOf: (e: RuleExpr) => Step, named: (e: RuleExpr, s: Step) => Step, notOf: (steps: Step[]) => Step, reservableOf: (steps: Step[]) => Step, - suppressOf: (connectors: string[], steps: Step[]) => Step, ctxOf: (mode: 'await' | 'yield' | 'asyncgen' | 'reset', steps: Step[]) => Step, + stepOf: (e: RuleExpr) => Step, named: (e: RuleExpr, s: Step) => Step, notOf: (steps: Step[]) => Step, reservableOf: (body: RuleExpr) => Step | null, + ctxOf: (eqs: Readonly>, steps: Step[]) => Step, whenTestOf: (cond: string) => { mask: number; val: number }, litTtype: (v: string) => '$keyword' | '$punct', altGuard: (e: RuleExpr, earlier: readonly RuleExpr[]) => Guard, templateTokens: ReadonlySet, ): PrattRule { @@ -2473,9 +2485,9 @@ function buildPratt( continue; } if (items[0].type === 'literal') { nudOrder.push({ kind: 'bracket', index: nudBrackets.length }); nudNames.push(armName(alt)); nudBrackets.push({ first: items[0].value, steps: items.map((it) => stepOfPratt(it)) }); nudWritten.push(alt); continue; } - // A single transparent group (no suppress, no context) unwraps to its body (an explicit grouping). + // A single transparent group (no context) unwraps to its body (an explicit grouping). let nudItems = items; - if (items.length === 1 && items[0].type === 'group' && !items[0].suppress && !items[0].ctxMode && items[0].when === undefined && items[0].atLevel === undefined) { + if (items.length === 1 && items[0].type === 'group' && items[0].ctx === undefined && items[0].when === undefined && items[0].atLevel === undefined) { nudItems = items[0].body.type === 'seq' ? items[0].body.items : [items[0].body]; } nudOrder.push({ kind: 'seq', index: nudSeqs.length }); nudNames.push(armName(alt)); @@ -2502,8 +2514,11 @@ function buildPratt( leds.push({ first: conn, steps }); // The interpreter's mixfixOf reads the items after the self `$` as written (a leading // `sameLine` is one of them, so such a led has no re-bind). + // The operand may stand in a `ctx` group (the ternary's middle, [+In]): the re-bind re-runs + // the operand step (rebind-family.ts rbStep 1), so it re-parses in the group's word too. const r1 = restAll[1], r2 = restAll[2]; - ledRebind.push(restAll.length >= 4 && restAll[0]!.type === 'literal' && r1?.type === 'ref' && r1.name === name && r2?.type === 'literal' && litTtype(r2.value) === '$punct' ? r2.value : null); + const selfOp = (e: RuleExpr | undefined): boolean => e?.type === 'ref' ? e.name === name : e?.type === 'group' && e.ctx !== undefined && e.when === undefined && e.body.type === 'ref' && e.body.name === name; + ledRebind.push(restAll.length >= 4 && restAll[0]!.type === 'literal' && selfOp(r1) && r2?.type === 'literal' && litTtype(r2.value) === '$punct' ? r2.value : null); ledNames.push(armName(alt)); ledLeftNames.push(names.childOf.get(items[0])!.name); ledAccessTail.push(!lastIsOperand && !wordConnector); ledLbp.push(prec ? prec.lbp : null); @@ -2525,10 +2540,9 @@ function buildPratt( if (e.type === 'group' && e.atLevel !== undefined) return stepOf(e); // a ruleBp step (atLevel) if (e.type === 'seq') return { t: 'seq', steps: e.items.map(stepOfPratt) }; if (e.type === 'sameLine') return { t: 'sameLine' }; - if (e.type === 'not') return (e.reservable ? reservableOf : notOf)((e.body.type === 'seq' ? e.body.items : [e.body]).map(stepOfPratt)); - if (e.type === 'group' && e.when !== undefined && !e.capBelow) return whenOf(e.when, (e.body.type === 'seq' ? e.body.items : [e.body]).map(stepOfPratt)); - if (e.type === 'group' && e.ctxMode && !e.capBelow) return ctxOf(e.ctxMode, (e.body.type === 'seq' ? e.body.items : [e.body]).map(stepOfPratt)); - if (e.type === 'group' && e.suppress && e.suppress.length) return suppressOf(e.suppress, (e.body.type === 'seq' ? e.body.items : [e.body]).map(stepOfPratt)); + if (e.type === 'not') return reservableOf(e.body) ?? notOf((e.body.type === 'seq' ? e.body.items : [e.body]).map(stepOfPratt)); + if (e.type === 'group' && e.when !== undefined && !e.capBelow) return whenOf(whenTestOf(e.when), (e.body.type === 'seq' ? e.body.items : [e.body]).map(stepOfPratt)); + if (e.type === 'group' && e.ctx !== undefined && !e.capBelow) return ctxOf(e.ctx, (e.body.type === 'seq' ? e.body.items : [e.body]).map(stepOfPratt)); if (e.type === 'group' && !e.capBelow) { return e.body.type === 'seq' ? { t: 'seq', steps: e.body.items.map(stepOfPratt) } : stepOfPratt(e.body); } @@ -2574,7 +2588,7 @@ function buildPratt( case 'prefix': return null; } })); - return { kind: 'pratt', name, nudToks, nudBrackets, nudSeqs, nudSeqGuard, nudSeqPredictive: false, nudBracketClosesTail, nudSeqClosesTail, nudBracketForm, nudSeqForm, nudBracketCapsFromTail, nudSeqCapsFromTail, nudCapped, nudCappedGuard, nudOrder, nudNames, nudDispatch, prefix, binary, leds, ledNames, ledLeftNames, ledAccessTail, ledLbp, ledSameLine, ledNotLeftLeaf, ledSuppressedIn: [], ledForm, ledClosesTail, ledCapsFromTail, ledRebind, ledClean: [], postfixToks, postfixTokNames, postfix, postfixSameLine, opNames: names.ops ?? null, ...(nudTplHole !== undefined ? { nudTplHole } : {}), ...(postfixTplHole !== undefined ? { postfixTplHole } : {}) }; + return { kind: 'pratt', name, nudToks, nudBrackets, nudSeqs, nudSeqGuard, nudSeqPredictive: false, nudBracketClosesTail, nudSeqClosesTail, nudBracketForm, nudSeqForm, nudBracketCapsFromTail, nudSeqCapsFromTail, nudCapped, nudCappedGuard, nudOrder, nudNames, nudDispatch, prefix, binary, leds, ledNames, ledLeftNames, ledAccessTail, ledLbp, ledSameLine, ledNotLeftLeaf, ledWhen: [], ledForm, ledClosesTail, ledCapsFromTail, ledRebind, ledClean: [], postfixToks, postfixTokNames, postfix, postfixSameLine, opNames: names.ops ?? null, ...(nudTplHole !== undefined ? { nudTplHole } : {}), ...(postfixTplHole !== undefined ? { postfixTplHole } : {}) }; } // ── Lex integer ids (kid = kind index, lid = text/literal index) ── @@ -2619,14 +2633,14 @@ export function literalKinds(ir: Pick): void { for (const s of steps) { switch (s.t) { case 'lit': out.add(s.value); break; case 'altlit': for (const o of s.opts) out.add(o.value); break; case 'sep': out.add(s.delim); collectStepLitTexts([s.elem], out); break; - case 'suppress': case 'ctx': collectStepLitTexts(s.steps, out); break; + case 'ctx': collectStepLitTexts(s.steps, out); break; case 'star': collectStepLitTexts([s.step], out); break; case 'opt': case 'seq': collectStepLitTexts(s.steps, out); break; case 'alt': for (const b of s.branches) collectStepLitTexts(b, out); break; @@ -2672,8 +2686,7 @@ export function buildLexIdPlan(ir: ParserIR): LexIdPlan { } for (const body of ir.lookaheads) collectStepLitTexts(body, litTexts); for (const s of ir.tokenSets) for (const x of s.lits) litTexts.add(x); - for (const x of ir.ctxWords) litTexts.add(x); - for (const s of ir.suppressSets) for (const x of s) litTexts.add(x); + for (const x of ir.ctxWords) if (x !== undefined) litTexts.add(x); if (ir.regexCtx) { for (const x of ir.regexCtx.divisionTexts) litTexts.add(x); for (const x of ir.regexCtx.regexTexts) litTexts.add(x); @@ -2740,12 +2753,15 @@ export function tokenSetBits(plan: LexIdPlan, sets: readonly TokenSet[]): TokenS /** The context bit and the literal id of each word of ParserIR.ctxWords (an `aheadCtx` test * refuses the token when the context has the bit and the token's lid is the word's). */ export function ctxWordLids(ir: ParserIR, plan: LexIdPlan): Array<{ bit: number; lid: number }> { - return ir.ctxWords.map((w, i) => { + return ir.ctxWords.flatMap((w, i) => { + if (w === undefined) return []; const lid = plan.lids.indexOf(w); if (lid <= 0) throw new Error(`portable: context word ${JSON.stringify(w)} has no literal id`); - return { bit: 1 << i, lid }; + return [{ bit: 1 << i, lid }]; }); } +/** The bits of the word an `aheadCtx` test reads (those ParserIR.ctxWords names a word for). */ +export const ctxWordBits = (ir: Pick): number => ir.ctxWords.reduce((m, w, i) => (w === undefined ? m : m | (1 << i)), 0); export function lidOf(plan: LexIdPlan, text: string): number { const i = plan.lids.indexOf(text); return i >= 0 ? i : 0; @@ -3029,7 +3045,7 @@ function collectStepTtypes(steps: Step[], out: Set): void { case 'tok': out.add(s.name); break; case 'altlit': for (const o of s.opts) if (o.ttype !== '$punct') out.add(o.ttype); break; case 'sep': collectStepTtypes([s.elem], out); break; - case 'suppress': case 'ctx': collectStepTtypes(s.steps, out); break; + case 'ctx': collectStepTtypes(s.steps, out); break; case 'star': collectStepTtypes([s.step], out); break; case 'opt': case 'seq': collectStepTtypes(s.steps, out); break; case 'alt': for (const b of s.branches) collectStepTtypes(b, out); break; @@ -3302,7 +3318,7 @@ export function formatFirstBytes(fb: LexFirstBytes | null): string { export const REC_RD = 0, REC_PRATT = 1; export const REC_S_LIT = 0, REC_S_COMP = 1, REC_S_TOK = 2, REC_S_TPLTOK = 3, REC_S_RULE = 4, REC_S_RULEBP = 5, REC_S_STAR = 6, REC_S_OPT = 7, REC_S_SEP = 8, REC_S_ALTLIT = 9, REC_S_ALT = 10, REC_S_LOOK = 11, REC_S_AHEAD = 12, REC_S_AHEADCTX = 13, REC_S_SEQ = 14, REC_S_SAMELINE = 15, - REC_S_SUPPRESS = 16, REC_S_CTX = 17, REC_S_SHARED = 18, REC_S_WHEN = 19; + REC_S_CTX = 16, REC_S_SHARED = 17, REC_S_WHEN = 18; // A Pratt rule's NUD arms (PrattRule.nudOrder), by tag. export const REC_N_TOK = 0, REC_N_BRACKET = 1, REC_N_SEQ = 2, REC_N_CAPPED = 3, REC_N_PREFIX = 4; export type RecoveryTables = { data: number[]; ruleAt: number[] }; @@ -3381,8 +3397,7 @@ export function recoveryTables(ir: ParserIR, ids: LexIdPlan, ar: ArenaIdPlan): R case 'sameLine': return emit([REC_S_SAMELINE]); case 'when': return emit([REC_S_WHEN, s.mask, s.val]); case 'assignTarget': throw new Error('portable recovery: unreachable (recoveryTables refuses target contexts)'); - case 'suppress': { const b = list(s.steps); return emit([REC_S_SUPPRESS, s.set, ref(b)]); } - case 'ctx': { const b = list(s.steps); return emit([REC_S_CTX, s.ctx, ref(b)]); } + case 'ctx': { const b = list(s.steps); return emit([REC_S_CTX, s.keep, s.set, ref(b)]); } } } const skip = (g: Guard, steps: Step[]) => guardedSteps(g, steps); @@ -3417,7 +3432,7 @@ export function recoveryTables(ir: ParserIR, ids: LexIdPlan, ar: ArenaIdPlan): R const leds = r.leds.map((b, i): Cell[] => { const nll = r.ledNotLeftLeaf[i]; return [lid(b.first), ref(list(b.steps)), r.ledLbp[i] ?? -1, r.ledSameLine[i] ? 1 : 0, r.ledAccessTail[i] ? 1 : 0, r.ledClosesTail[i] ? 1 : 0, r.ledCapsFromTail[i] ? 1 : 0, r.ledForm[i]!, - ref(nll ? emit([nll.length, ...nll.map(lid)]) : -1), r.ledRebind[i] ? lid(r.ledRebind[i]!) : -1, r.ledSuppressedIn[i]!.length, ...r.ledSuppressedIn[i]!]; + ref(nll ? emit([nll.length, ...nll.map(lid)]) : -1), r.ledRebind[i] ? lid(r.ledRebind[i]!) : -1, r.ledWhen[i]?.mask ?? 0, r.ledWhen[i]?.val ?? 0]; }); const sections: Cell[][] = [ [arms.length, ...arms.flat()], diff --git a/src/ir/recovery-family.ts b/src/ir/recovery-family.ts index fe40e5ae..28a2f883 100644 --- a/src/ir/recovery-family.ts +++ b/src/ir/recovery-family.ts @@ -18,7 +18,7 @@ import { type Expr, type Fn, type Lowering, type RecordDecl, type Stmt, printFns } from './algo-ir.ts'; import { RI_RB_SCAN, RB_EXTERNS_INTERP, REBIND_EXTERNS, rbBracketFn } from './rebind-family.ts'; import { type ArenaIdPlan, type LexIdPlan, type ParserIR, prattTakesBp, ruleIdOf, tplHoleRules } from './parser-ir.ts'; -import { REC_RD, REC_N_TOK, REC_N_BRACKET, REC_N_SEQ, REC_N_CAPPED, REC_N_PREFIX, REC_S_LIT, REC_S_COMP, REC_S_TOK, REC_S_TPLTOK, REC_S_RULE, REC_S_RULEBP, REC_S_STAR, REC_S_OPT, REC_S_SEP, REC_S_ALTLIT, REC_S_ALT, REC_S_LOOK, REC_S_AHEAD, REC_S_AHEADCTX, REC_S_SEQ, REC_S_SAMELINE, REC_S_SUPPRESS, REC_S_CTX, REC_S_SHARED, REC_S_WHEN } from './parser-ir.ts'; +import { REC_RD, REC_N_TOK, REC_N_BRACKET, REC_N_SEQ, REC_N_CAPPED, REC_N_PREFIX, REC_S_LIT, REC_S_COMP, REC_S_TOK, REC_S_TPLTOK, REC_S_RULE, REC_S_RULEBP, REC_S_STAR, REC_S_OPT, REC_S_SEP, REC_S_ALTLIT, REC_S_ALT, REC_S_LOOK, REC_S_AHEAD, REC_S_AHEADCTX, REC_S_SEQ, REC_S_SAMELINE, REC_S_CTX, REC_S_SHARED, REC_S_WHEN } from './parser-ir.ts'; export const DIAG: RecordDecl = { name: 'Diag', @@ -133,7 +133,7 @@ export const ENGINE_EXTERNS: Fn[] = [ ext('enPeekKid', [], ['int']), ext('enPeekLid', [], ['int']), ext('enPeekNl', [], ['bool']), // The building matchers: a literal, a composed '>' literal, a token kind. ext('enLit', [['l', 'int']], ['bool']), ext('enComp', [['l', 'int']], ['bool']), ext('enTok', [['k', 'int']], ['bool']), - ext('enAhead', [['set', 'int'], ['is', 'bool']], ['bool']), ext('enCtxWord', [], ['bool']), ext('enWhen', [['mask', 'int'], ['val', 'int']], ['bool']), ext('enSecondIn', [['set', 'int']], ['bool']), + ext('enAhead', [['set', 'int'], ['is', 'bool']], ['bool']), ext('enCtxWord', [], ['bool']), ext('enWhen', [['mask', 'int'], ['val', 'int']], ['bool']), ext('enCtxSet', [['keep', 'int'], ['set', 'int']]), ext('enSecondIn', [['set', 'int']], ['bool']), // The native functions: a lookahead body, a rule (its node appended), a Pratt rule at a binding // power (its node appended), a shared step, an interpolated template whose holes rule `hole` parses. ext('enLook', [['id', 'int']], ['bool']), ext('enRule', [['r', 'int']], ['bool']), ext('enBp', [['r', 'int'], ['bp', 'int']], ['bool']), @@ -202,8 +202,8 @@ export const TEXT_EXTERNS: Fn[] = [textExt('litText'), textExt('kindText'), text // (termination T2); the attempts made, and the most one scope took; the bars (strictly increasing, at most RM_MAX_BARS); then the // repairs, three ints each (kind, token index, arg). export const RM_REC = 0, RM_FAIL = 1, RM_PROBE = 2, RM_SP = 3, RM_SD = 4, RM_ATT = 5, RM_AMAX = 6, RM_NB = 7, RM_BARS = 8, RM_MAX_BARS = 32, RM_DIAGS = RM_BARS + RM_MAX_BARS; -export const ST_CAPPED = 0, ST_FORM = 1, ST_TAIL = 2, ST_SUP_NEXT = 3, ST_SUP_CUR = 4, ST_CTX = 5; -const ST_ALL = [ST_CAPPED, ST_FORM, ST_TAIL, ST_SUP_NEXT, ST_SUP_CUR, ST_CTX]; +export const ST_CAPPED = 0, ST_FORM = 1, ST_TAIL = 2, ST_CTX = 3; +const ST_ALL = [ST_CAPPED, ST_FORM, ST_TAIL, ST_CTX]; const T = (i: Expr): Expr => ({ k: 'tab', t: 'rt', i }); // The trailer of the plan's table ([2 + N] holds its index): the rule ids of `$error`, `$missing` @@ -304,14 +304,7 @@ const riRule = method('riRule', [['r', 'int'], ['d', 'int']], ['bool'], [ if_(call('riNat', v('r'), n(-1)), [ret(tru)]), let_('rec', T(add(n(2), v('r')))), if_(eq(T(v('rec')), n(REC_RD)), [ret(call('riFrame', v('r'), v('rec'), n(0), sub(v('d'), n(1))))]), - // A Pratt rule called fresh: the suppress set staged for it becomes the one in force. - let_('prev', call('enSt', n(ST_SUP_CUR))), - let_('next', call('enSt', n(ST_SUP_NEXT))), - run('enSetSt', n(ST_SUP_CUR), v('next')), - run('enSetSt', n(ST_SUP_NEXT), n(0)), - let_('ok', call('riFrame', v('r'), v('rec'), n(0), sub(v('d'), n(1))), 'bool'), - run('enSetSt', n(ST_SUP_CUR), v('prev')), - ret(v('ok')), + ret(call('riFrame', v('r'), v('rec'), n(0), sub(v('d'), n(1)))), ]); // Mark k undone (the position, the list, the builder and the repair memory as they were) and dropped. const riUndo = method('riUndo', [['k', 'int']], [], [run('enReset', v('k')), run('enUnmark', v('k'))]); @@ -533,16 +526,11 @@ const riStep = method('riStep', [['s', 'int'], ['d', 'int']], ['bool'], [ op(REC_S_SAMELINE, [ret(and(ge(call('enPeekKid'), n(0)), not(call('enPeekNl'))))]), // A `when` test: the context word in force passes (word & mask) === val (the target's enWhen). op(REC_S_WHEN, [ret(call('enWhen', S1, S2))]), - op(REC_S_SUPPRESS, [ - run('enSetSt', n(ST_SUP_NEXT), S1), - let_('ok', call('riList', S2R, v('d')), 'bool'), - run('enSetSt', n(ST_SUP_NEXT), n(0)), - ret(v('ok')), - ]), + // A `ctx` body: in the word (word & keep) | set (the target's enCtxSet), the one in force put back after. op(REC_S_CTX, [ let_('c0', call('enSt', n(ST_CTX))), - run('enSetSt', n(ST_CTX), S1), - let_('ok', call('riList', S2R, v('d')), 'bool'), + run('enCtxSet', S1, S2), + let_('ok', call('riList', S3R, v('d')), 'bool'), run('enSetSt', n(ST_CTX), v('c0')), ret(v('ok')), ]), @@ -707,7 +695,7 @@ const ledOk = (x: Expr): Expr => and( or(lt(at(x, 2), n(0)), gt(at(x, 2), v('minBp'))), not(and(isT(x, 3), v('nl'))), or(lt(at(x, 8), n(0)), not(call('riIn', atR(x, 8), v('head')))), - not(call('riIn', add(x, n(10)), v('sup'))), + call('enWhen', at(x, 10), at(x, 11)), // a gated led (PrattRule.ledWhen; mask 0: none) ); // `progRead`: a later test of this iteration reads `prog` (the binary arm is the last: it does not set it). const finLed = (form: Expr, progRead = true): Stmt[] => [ @@ -735,9 +723,8 @@ const riBpOf = (rebind: boolean): Fn => method('riBpIn', [['r', 'int'], ['rec', let_('lid', call('enPeekLid')), let_('nl', call('enPeekNl'), 'bool'), let_('prog', fls, 'bool'), - // What the led tests read of the engine: the left operand's first leaf, the suppress set in force. + // What the led tests read of the engine: the left operand's first leaf. let_('head', call('enHeadLid', v('sb'))), - let_('sup', call('enSt', n(ST_SUP_CUR))), let_('j', n(0)), let_('x', add(sec(P_LED), n(1))), while_(and(lt(v('j'), T(sec(P_LED))), not(v('prog'))), [ @@ -750,7 +737,7 @@ const riBpOf = (rebind: boolean): Fn => method('riBpIn', [['r', 'int'], ['rec', ]), if_(v('won'), ledWon), ]), - inc('x', add(n(11), at(v('x'), 10))), + inc('x', n(12)), inc('j'), ]), if_(and(not(v('prog')), eq(v('tc'), n(0)), call('riIn', sec(P_POST_TOK), v('kid'))), [run('enLeafKid'), ...finLed(n(0))]), @@ -885,8 +872,7 @@ const riNat = method('riNat', [['r', 'int'], ['bp', 'int']], ['bool'], [ let_('lk', call('enLookEnd')), run('enLookSet', n(0)), let_('k', call('enMark')), - // The engine's flags as the native call found them (it stages the suppress set it reads), put - // back when it is undone, so the interpreted frame starts where the native one did. + // The engine's flags as the native call found them, put back when it is undone, so the interpreted frame starts where the native one did. ...ST_ALL.map((st) => let_(`st${st}`, call('enSt', n(st)))), let_('ok', fls, 'bool'), if_(lt(v('bp'), n(0)), [set('ok', call('enRule', v('r')))], [set('ok', call('enBp', v('r'), v('bp')))]), diff --git a/src/shape/shape-plan.ts b/src/shape/shape-plan.ts index 95873f7c..ae8e1ab2 100644 --- a/src/shape/shape-plan.ts +++ b/src/shape/shape-plan.ts @@ -736,7 +736,7 @@ function shapeSteps(r: RuleIR, tags: Map, marked: Map c(x, inner)); break; + case 'opt': case 'seq': case 'ctx': o.steps = o.steps.map((x) => c(x, inner)); break; case 'alt': o.branches = o.branches.map((b) => b.map((x) => c(x, inner))); break; } return o; diff --git a/src/shape/v1/shape-schema.ts b/src/shape/v1/shape-schema.ts index 2baa69fe..9518304e 100644 --- a/src/shape/v1/shape-schema.ts +++ b/src/shape/v1/shape-schema.ts @@ -152,7 +152,7 @@ export const ADJUDICATIONS = { /** Emit-time static coverage of Shape AST step/pratt rendering. */ export type ShapeStepKind = | 'lit' | 'tok' | 'rule' | 'ruleBp' | 'star' | 'opt' | 'sep' - | 'altlit' | 'alt' | 'look' | 'ahead' | 'aheadCtx' | 'seq' | 'sameLine' | 'suppress' | 'ctx'; + | 'altlit' | 'alt' | 'look' | 'ahead' | 'aheadCtx' | 'seq' | 'sameLine' | 'ctx'; export type ShapePrattKind = | 'atom' | 'group' | 'prefix' | 'binary' | 'postfix' | 'postfixTok' | 'led' | 'nudSeq' | 'nudCapped' | 'template'; @@ -165,7 +165,7 @@ export type ShapeCoverage = { export const SHAPE_STEP_KINDS: readonly ShapeStepKind[] = [ 'lit', 'tok', 'rule', 'ruleBp', 'star', 'opt', 'sep', - 'altlit', 'alt', 'look', 'ahead', 'aheadCtx', 'seq', 'sameLine', 'suppress', 'ctx', + 'altlit', 'alt', 'look', 'ahead', 'aheadCtx', 'seq', 'sameLine', 'ctx', ] as const; export const SHAPE_PRATT_KINDS: readonly ShapePrattKind[] = [ 'atom', 'group', 'prefix', 'binary', 'postfix', 'postfixTok', diff --git a/src/shape/v1/shape-validate.ts b/src/shape/v1/shape-validate.ts index 713d6692..eb02d255 100644 --- a/src/shape/v1/shape-validate.ts +++ b/src/shape/v1/shape-validate.ts @@ -57,7 +57,6 @@ function slotsOfStep(s: Step, leaves: Record): Slot[] { return [{ k: 'alt', branches: s.branches.map((b) => b.flatMap((x) => slotsOfStep(x, leaves))) }]; case 'seq': return s.steps.flatMap((x) => slotsOfStep(x, leaves)); - case 'suppress': case 'ctx': return s.steps.flatMap((x) => slotsOfStep(x, leaves)); case 'look': diff --git a/src/targets/target-go.ts b/src/targets/target-go.ts index 3a5420d7..c8660091 100644 --- a/src/targets/target-go.ts +++ b/src/targets/target-go.ts @@ -11,11 +11,11 @@ // warmed parser allocates ~nothing per parse. import { type ParserIR, type MarkForm, type RdRule, type PrattRule, type NodeCap, type Step, type LexTok, type NewlineCfg, type FirstSig, type Guard, type Dispatch, type LexFirstBytes, type LexIdPlan, type ArenaIdPlan, type ReusePlan, type AssignTargetsIR } from '../ir/parser-ir.ts'; import type { ArmForm } from '../ir/assign-targets.ts'; -import { prattTail, hasRebind, nudLowForm, hasUnaryNud, demandTwinCond, demandLids, DEFER_SHIFT, type DemandIR, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, CTX_WORD_BITS, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, TT_SKIP_PUNCT, tplHoleRules, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; +import { prattTail, hasRebind, nudLowForm, hasUnaryNud, demandTwinCond, demandLids, DEFER_SHIFT, type DemandIR, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, ctxWordBits, ctxWord, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, TT_SKIP_PUNCT, tplHoleRules, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; import type { Grammar } from '../grammar/types.ts'; import { defineParserTarget, type SharedAlgorithms } from './define-parser-target.ts'; import type { EmitOptions } from './target.ts'; -import { ST_CAPPED, ST_FORM, ST_TAIL, ST_SUP_NEXT, ST_SUP_CUR, RM_DIAGS, RM_FAIL, RM_PROBE, RM_SP, RM_ATT, RM_AMAX, nativeCases, shorterDispatch } from '../ir/recovery-family.ts'; +import { ST_CAPPED, ST_FORM, ST_TAIL, RM_DIAGS, RM_FAIL, RM_PROBE, RM_SP, RM_ATT, RM_AMAX, nativeCases, shorterDispatch } from '../ir/recovery-family.ts'; import { ATOM, COMPARISON, findAnyName, stopBytes, isNum, isOpt, isRec, isRecList, recName, type BinOp, type Lowering, unitMask, type MetaInt, type MkMeta, type R, type TokInt, type Ty } from '../ir/algo-ir.ts'; import { uniIdentPlan, uniLookup } from '../grammar/uni-ident.ts'; import { type TextUnits, firstUnit, unitLen } from '../grammar/text-units.ts'; @@ -36,7 +36,7 @@ const guardCond = (g: Guard, t: string, keyed: boolean): string[] => { const parts = keyed || g.first === null ? [] : [`${goLib('inTokenSet')}(${g.first.id}, ${t})`]; if (g.second !== null) parts.push(`p.${goLib('secondIn')}(${g.second.id})`); for (const l of g.lead) { // the guard's lead tests (parser-ir.ts LeadTest) on t - const inS = l.ctx ? `(${goLib('inTokenSet')}(${l.set}, ${t}) || (p.ctx&${CTX_WORD_BITS} != 0 && ${goLib('inCtxWords')}(p.ctx, ${t})))` : `${goLib('inTokenSet')}(${l.set}, ${t})`; + const inS = l.ctx ? `(${goLib('inTokenSet')}(${l.set}, ${t}) || (p.ctx&${l.ctx} != 0 && ${goLib('inCtxWords')}(p.ctx, ${t})))` : `${goLib('inTokenSet')}(${l.set}, ${t})`; parts.push(l.is ? inS : `!${inS}`); } // Guard.pairs. Spelled in place, not as a pairIn helper as the other targets do: such a helper is @@ -256,8 +256,7 @@ function goSteps(ids: LexIdPlan, f: GoForm, recv: string, e: GoEngine, ar?: Aren inPlace: (_kind, stmts) => `func() bool { ${stmts} }()`, ret: (cond) => `return ${cond}`, // A `ctx` step's body is a boolean expression: no return path leaves between the two assignments. - suppress: (set, cond) => `p.suppressNext = ${set}; _r := (${cond}); p.suppressNext = 0; return _r`, - ctx: (ctx, cond) => `_c := p.ctx; p.ctx = ${ctx}; _r := (${cond}); p.ctx = _c; return _r`, + ctx: (keep, set, cond) => `_c := p.ctx; p.ctx = ${ctxWord(keep, set, '_c')}; _r := (${cond}); p.ctx = _c; return _r`, // A branch that fails clean (Step.clean) has nothing to undo: no frame. branch: (cond, clean) => (clean ? `{ if ${cond} { return true } }` : f === 'R' ? branchGoR(cond) : f === 'W' ? branchGoW(cond, recv) : branchGo(cond)), guarded: (first, branch) => `if _ft != nil && ${firstCond(first, '_ft', ids)} ${branch}`, @@ -1174,7 +1173,7 @@ function goRowOpRead(r: PrattRule, ids: LexIdPlan, withEnd: boolean, dem: boolea // returns, and lookEnd() folds in the stretch since. Every move of the position to an earlier // token goes through back(). // The token cursor: what every recognizer reads and moves (the position, the tokens, the look -// extent, the suppress set and the context in force). Both engine types embed it, so the cursor's +// extent and the context word in force). Both engine types embed it, so the cursor's // helpers and every recognizer that runs no building form (Forms.cursorOnly) are printed once, as // its methods, and called through either engine (Go promotes the embedded methods). function cursorGo(ir: ParserIR, ids: LexIdPlan): string { @@ -1184,8 +1183,7 @@ function cursorGo(ir: ParserIR, ids: LexIdPlan): string { \ttoks []Tok \tpos, maxLook int \tpeekEnd int // one past the token of the latest peek (see back) -\tsuppressNext, suppressCur uint16 // indices into the grammar's suppress sets (ParserIR.suppressSets; 0 = none) -\tctx uint8 // the [Await]/[Yield] context word in force (bit 1 await, bit 2 yield; see ParserIR's Ctx) +\tctx uint8 // the context word in force (a bit per context parameter; see parser-ir.ts's context word) } func (p *cursor) peek() *Tok { @@ -1202,7 +1200,7 @@ func (p *cursor) lookEnd() int { if p.peekEnd > p.maxLook { return p.peekEnd }; func (p *cursor) lookReset() { p.maxLook = 0; p.peekEnd = 0 } ${goLibFn('ahead', `func (p *cursor) ahead(k int, is bool) bool { t := p.peek(); return (t != nil && inTokenSet(k, t)) == is } `)}${goLibFn('ctxWord', `// ctxWord: whether the next token is a word the context in force reserves; outside every context it reads nothing. -func (p *cursor) ctxWord() bool { if p.ctx&${CTX_WORD_BITS} == 0 { return false }; t := p.peek(); return t != nil && inCtxWords(p.ctx, t) } +func (p *cursor) ctxWord() bool { if p.ctx&${ctxWordBits(ir)} == 0 { return false }; t := p.peek(); return t != nil && inCtxWords(p.ctx, t) } `)}${goLibFn('secondIn', `// secondIn: whether the token after the current one is in tokenSets[k] (a candidate's SECOND guard). func (p *cursor) secondIn(k int) bool { i := p.pos + 1; if i >= p.maxLook { p.maxLook = i + 1 }; return i < len(p.toks) && inTokenSet(k, &p.toks[i]) } `)}func (p *cursor) offAt(i int) int { if i < len(p.toks) { return int(p.toks[i].Off) }; return 0 } @@ -1452,7 +1450,7 @@ const goPrattBase = (r: PrattRule, ids: LexIdPlan, leftLeaf: (words: string) => lbpAbove: (lbp: number) => `${lbp} > minBp`, sameLine: '!t.Nl', notLeftLeaf: (words: string[]) => leftLeaf(`[]string{${words.map(J).join(', ')}}`), - notSuppressed: (set: number) => `p.suppressCur != ${set}`, + when: (mask: number, val: number) => `p.ctx&${mask} == ${val}`, ifAll: (parts: string[]) => (parts.length ? `if ${parts.join(' && ')} ` : ''), }, // on the row's dense led index (cases 1..k): a jump table whatever the lids @@ -1583,12 +1581,7 @@ ${kids.map((k) => `\t\tcase ${k}: \t}`, entry: (bp) => `${goPrattOpTables(r, ids, ir.assignTargets?.demand)} func (p *engine) parse${r.name}() int32 { -\tprev := p.suppressCur -\tp.suppressCur = p.suppressNext -\tp.suppressNext = 0 -\tr := p.bp_${r.name}(${bp ? '0' : ''}) -\tp.suppressCur = prev -\treturn r +\treturn p.bp_${r.name}(${bp ? '0' : ''}) }`, bpOpen: (label, nudBp, bp, tail) => `func (p *engine) bp_${r.name}(${bp ? 'minBp int' : ''}) int32 {${T.p0} \tleft := p.nud_${r.name}(${nudBp ? 'minBp' : ''}) @@ -2276,12 +2269,7 @@ ${kids.map((k) => `\t\tcase ${k}: \t\tform = ${T.bin}${prattTail(r) === 'none' ? '' : '; tailClosed = true'} \t}`, entry: (bp) => `func (p *${recv}) parse${r.name}W() (spanned, bool) { -\tprev := p.suppressCur -\tp.suppressCur = p.suppressNext -\tp.suppressNext = 0 -\tr, ok := p.bpW_${r.name}(${bp ? '0' : ''}) -\tp.suppressCur = prev -\treturn r, ok +\treturn p.bpW_${r.name}(${bp ? '0' : ''}) }`, bpOpen: (label, nudBp, bp, tail) => `func (p *${recv}) bpW_${r.name}(${bp ? 'minBp int' : ''}) (spanned, bool) {${T.p0} \tleft, ok := p.nudW_${r.name}(${nudBp ? 'minBp' : ''}) @@ -2328,7 +2316,9 @@ function emitParserMethodsW(recv: string, ir: ParserIR, ids: LexIdPlan, ar: Aren \tsave := p.pos; sb := len(p.scratch); ${arenaCkpt()} \tp.${goLib('pushLeafW')}(${ttIdOf(ar, '$templateHead')}, uint32(p.pos), t.Off, t.End); p.pos++ \tfor { +${ir.tpl?.holeCtx ? `\t\t_hc := p.ctx; p.ctx = ${ctxWord(ir.tpl.holeCtx.keep, ir.tpl.holeCtx.set, '_hc')} \t\texpr, ok := p.parse${hole}W() +\t\tp.ctx = _hc` : `\t\texpr, ok := p.parse${hole}W()`} \t\tif !ok { p.back(save); p.scratch = p.scratch[:sb]; ${arenaRestore()}; return spanned{}, false } \t\tif expr.present { p.scratch = append(p.scratch, expr.h) } \t\tnext := p.peek() @@ -3451,6 +3441,7 @@ func (rv *recov) enTok(k int) bool { return rv.p.${goLib('tokW')}(uint16(k)) && func (rv *recov) enAhead(set int, is bool) bool { return rv.p.${goLib('ahead')}(set, is) } func (rv *recov) enCtxWord() bool { return rv.p.${goLib('ctxWord')}() } func (rv *recov) enWhen(mask, val int) bool { return int(rv.p.ctx)&mask == val } +func (rv *recov) enCtxSet(keep, set int) { rv.p.ctx = uint8(int(rv.p.ctx)&keep | set) } func (rv *recov) enSecondIn(set int) bool { return rv.p.${goLib('secondIn')}(set) } func (rv *recov) enLook(id int) bool { ${disp('id', 'ntLook', 'func(*parserW) bool', nc.look, (i) => `look${i}`, (c) => c(''))} @@ -3524,10 +3515,6 @@ func (rv *recov) enSt(k int) int { case ${ST_TAIL}: if p.tail { return 1 } return 0 - case ${ST_SUP_NEXT}: - return int(p.suppressNext) - case ${ST_SUP_CUR}: - return int(p.suppressCur) } return int(p.ctx) } @@ -3540,10 +3527,6 @@ func (rv *recov) enSetSt(k, v int) { p.form = uint8(v) case ${ST_TAIL}: p.tail = v != 0 - case ${ST_SUP_NEXT}: - p.suppressNext = uint16(v) - case ${ST_SUP_CUR}: - p.suppressCur = uint16(v) default: p.ctx = uint8(v) } @@ -3567,7 +3550,7 @@ func ParseInterpreted(src string, b Builder, depth int) (h int32, ok bool, steps p.pos = 0 p.scratch = p.scratch[:0] p.lookReset() - p.capped, p.form, p.tail, p.suppressNext, p.suppressCur, p.ctx = false, 0, false, 0, 0, 0 + p.capped, p.form, p.tail, p.ctx = false, 0, false, 0 rv := newRecov(p) ok = rv.riRule(${ruleIdOf(ar, ir.entry)}, depth) && p.pos == len(p.toks) var fr int32 @@ -3650,7 +3633,7 @@ func ParseTotalWork(src string, b Builder) (h int32, ok bool, errs []Diagnostic, p.pos = 0 p.scratch = p.scratch[:0] p.lookReset() - p.capped, p.form, p.tail, p.suppressNext, p.suppressCur, p.ctx = false, 0, false, 0, 0, 0 + p.capped, p.form, p.tail, p.ctx = false, 0, false, 0 rv := newRecov(p) rv.riTotal() if len(p.scratch) != 1 { panic(errNoRoot) } @@ -3689,7 +3672,9 @@ export const goTarget = defineParserTarget({ \tsb := len(p.scratch); nb := len(p.nodes); kb := len(p.kids); save := p.pos \tp.${goLib('pushLeaf')}(${ttIdOf(ar, '$templateHead')}, uint32(p.pos)); p.pos++ \tfor { +${ir.tpl?.holeCtx ? `\t\t_hc := p.ctx; p.ctx = ${ctxWord(ir.tpl.holeCtx.keep, ir.tpl.holeCtx.set, '_hc')} \t\texpr := p.parse${hole}() +\t\tp.ctx = _hc` : `\t\texpr := p.parse${hole}()`} \t\tif expr < 0 { p.back(save); p.scratch = p.scratch[:sb]; p.nodes = p.nodes[:nb]; p.kids = p.kids[:kb]; return -1 } \t\tp.scratch = append(p.scratch, expr) \t\tnext := p.peek() diff --git a/src/targets/target-js.ts b/src/targets/target-js.ts index b705697d..37d28dcf 100644 --- a/src/targets/target-js.ts +++ b/src/targets/target-js.ts @@ -12,7 +12,7 @@ // loop, the longest-match non-recursive loop, the mixfix operand re-bind, the // packrat memo, save/restore backtracking) stay as a generic runtime that the // emitted code CALLS — copied VERBATIM from interpreter.ts so their longest-match / -// tail-closing / suppress / mixfix semantics are byte-identical to the oracle. +// tail-closing / context / mixfix semantics are byte-identical to the oracle. // What those loops used to dispatch per arm (matchExpr(alt) / matchSeq(items)) is // now a GENERATED specialized matcher per NUD/LED/alt arm, so the interpretive // dispatch — the ~third of parse time the CPU profile attributes to matchExpr + @@ -24,7 +24,7 @@ // parser must reproduce its CST byte-for-byte. import type { Grammar, RuleExpr, RuleDecl } from '../grammar/types.ts'; -import { CTX_WORDS, collectLiterals, ctxWordOfMode, gtComposites, isKeywordLiteral, readsSyncFn, whenTest } from '../grammar/grammar-utils.ts'; +import { collectLiterals, ctxEquation, gtComposites, isKeywordLiteral, notCtxWords, notStaticBody, whenTest } from '../grammar/grammar-utils.ts'; import { tokenPatternSource } from '../grammar/token-pattern.ts'; import { analyzeGrammar, findEntryRule, markupContainerOf, type MarkupContainer, type Sec } from '../grammar/grammar-analysis.ts'; import { emitLexer, emitTokenColumns, lexSpecOf } from '../interpreter/lexer.ts'; @@ -44,40 +44,44 @@ const SAVE_FAIL = 'pos = _save; scn = _sn; return false;'; // vocabulary. type FirstTok = { lit: string } | { tok: string } | null; -type MixfixInfo = { openLit: string; sepLit: string }; +type MixfixInfo = { openLit: string; sepLit: string; eq: { keep: number; set: number } | null }; /** Build the full static analysis the emitter needs, returned as plain data. */ -// A group that only groups: no suppress set, context marker or `when` condition (those change what -// the body is parsed in, so the body is not the group). +// A group that only groups: no context equations or `when` condition (those change what the body +// is parsed in, so the body is not the group). const plainGroup = (e: RuleExpr): e is Extract => - e.type === 'group' && !(e.suppress && e.suppress.length) && !e.ctxMode && e.when === undefined; + e.type === 'group' && e.ctx === undefined && e.when === undefined; function analyze(grammar: Grammar) { const { tokenNames, opTable, prefixOps, noUnaryLhsOps, postfixOpValues, requireAssignTargetOps, ledPrecByConnector, binaryConnectors, connectorLbp, atLevelBp, prattRules, prattClassified, leftRecClassified, leftRecSet, ruleByName, nullableRules, exprNullable, maxBp, templateTokenName, templateTokenNames, - exprSecond, suppressSetOf, suppressedIn, ctxObserve, + exprSecond, ctxObserve, } = analyzeGrammar(grammar); // The jsTarget parser is being retired (docs/ROADMAP.md): the engine's later Pratt mechanisms // are refused by name rather than ignored (it would parse a capped prefix or a level-read // operand as an ordinary one). for (const [op, info] of prefixOps) if (info.capBp !== undefined) throw new Error(`jsTarget: the capped prefix operator '${op}' (cappedPrefix) is not supported; use the portable targets`); - const atLevelIn = (e: RuleExpr): boolean => (e.type === 'group' && e.atLevel !== undefined) - || ((e.type === 'seq' || e.type === 'alt') && e.items.some(atLevelIn)) - || ((e.type === 'quantifier' || e.type === 'group' || e.type === 'not') && atLevelIn(e.body)) - || (e.type === 'sep' && atLevelIn(e.element)); + // An atLevel read of a Pratt rule from another rule (JavaScript's for-in left, a + // LeftHandSideExpression) is a parseRuleEntry call at the level's bp (matchInto 'group'), as the + // interpreter's parsePratt at that level; any other atLevel is refused. + const foreignAtLevel = (e: RuleExpr, ruleName: string): boolean => e.type === 'group' && e.atLevel !== undefined && e.body.type === 'ref' && e.body.name !== ruleName && prattRules.has(e.body.name); + const atLevelIn = (e: RuleExpr, ruleName = ''): boolean => (e.type === 'group' && e.atLevel !== undefined && !foreignAtLevel(e, ruleName)) + || ((e.type === 'seq' || e.type === 'alt') && e.items.some((x) => atLevelIn(x, ruleName))) + || ((e.type === 'quantifier' || e.type === 'group' || e.type === 'not') && atLevelIn(e.body, ruleName)) + || (e.type === 'sep' && atLevelIn(e.element, ruleName)); // One use is supported: a Pratt rule's NUD ending in its own operand read at an operator's level // (`['<', Type, '>', atLevel('!', $)]`, the type assertion), a PREFIX-SHAPED NUD (selfAtLevelEnd). const selfAtLevelEnd = (alt: RuleExpr, ruleName: string): boolean => { const items = alt.type === 'seq' ? alt.items : [alt]; const last = items[items.length - 1]; return last !== undefined && last.type === 'group' && last.atLevel !== undefined && last.body.type === 'ref' && last.body.name === ruleName - && !items.slice(0, -1).some(atLevelIn); + && !items.slice(0, -1).some((x) => atLevelIn(x)); }; for (const r of grammar.rules) { const alts = r.body.type === 'alt' ? r.body.items : [r.body]; - if (alts.some((alt) => atLevelIn(alt) && !(prattRules.has(r.name) && selfAtLevelEnd(alt, r.name)))) throw new Error(`jsTarget: rule ${r.name} reads a rule atLevel(…); not supported, use the portable targets`); + if (alts.some((alt) => atLevelIn(alt, r.name) && !(prattRules.has(r.name) && selfAtLevelEnd(alt, r.name)))) throw new Error(`jsTarget: rule ${r.name} reads a rule atLevel(…); not supported, use the portable targets`); } if (grammar.assignTargets && Object.keys(grammar.assignTargets).length) throw new Error(`jsTarget: declared target contexts (Grammar.assignTargets: ${Object.keys(grammar.assignTargets).join(', ')}) are not supported; use the portable targets`); @@ -95,9 +99,17 @@ function analyze(grammar: Grammar) { function selfRefName(e: RuleExpr | undefined, ruleName: string): boolean { return !!e && e.type === 'ref' && e.name === ruleName; } + // The self operand, bare or inside a `ctx` group (the ternary's middle, [+In]: its equations, + // which the re-bind's re-parse runs in too), or undefined. + function selfOperand(e: RuleExpr | undefined, ruleName: string): { keep: number; set: number } | null | undefined { + if (selfRefName(e, ruleName)) return null; + if (e?.type === 'group' && e.ctx !== undefined && e.when === undefined && selfRefName(e.body, ruleName)) return ctxEquation(e.ctx, grammar.params); + return undefined; + } function mixfixOf(items: RuleExpr[], ruleName: string): MixfixInfo | null { - if (items.length >= 4 && items[0]?.type === 'literal' && selfRefName(items[1], ruleName) && items[2]?.type === 'literal') { - return { openLit: items[0].value, sepLit: items[2].value }; + const eq = selfOperand(items[1], ruleName); + if (items.length >= 4 && items[0]?.type === 'literal' && eq !== undefined && items[2]?.type === 'literal') { + return { openLit: items[0].value, sepLit: items[2].value, eq }; } return null; } @@ -404,7 +416,9 @@ function analyze(grammar: Grammar) { prattRules, leftRecSet, ruleByName, prattClassified, leftRecClassified, maxBp, templateTokenName, templateTokenNames, firstTokenOf, altDeepFirst, altNullable, altSecond, ledMeta, contMeta, nudCap, nullableRules, firstSets, symtab, qualKeys, - exprFirst, exprNullable, suppressSetOf, suppressedIn, atLevelBp, selfAtLevelEnd, ctxObserve, splitSync: readsSyncFn(grammar), + exprFirst, exprNullable, atLevelBp, selfAtLevelEnd, ctxObserve, + holeEq: ((h) => (h !== undefined ? ctxEquation(h, grammar.params) : null))(grammar.tokens.find((t) => t.template?.holeCtx !== undefined)?.template?.holeCtx), + ledWhen: new Map((grammar.ledPrecs ?? []).flatMap((lp) => (lp.when !== undefined ? [[lp.connector, whenTest(lp.when, grammar.params)] as const] : []))), unaryRows: [...prattClassified.entries()].some(([name, { nuds }]) => nuds.some((nud) => selfAtLevelEnd(nud, name))), markupContainer: markupContainerOf(grammar), }; @@ -608,7 +622,7 @@ class Emitter { // ref, or a single rule ref — possibly wrapped in a transparent group / one-item seq), // return a body that just delegates to the (already pushing) matcher call — skipping // the save/restore (a failing single matcher consumes nothing and pushes nothing). - // Else null. Excludes template-token refs (two-branch) and suppress-groups. + // Else null. Excludes template-token refs (two-branch) and context groups. private singleLeafBody(expr: RuleExpr): string | null { const a = this.a; // Unwrap transparent wrappers that don't themselves emit/consume. @@ -713,31 +727,27 @@ class Emitter { const name = (expr.body as { name: string }).name; return `if (!parseRuleEntry(${this.memoIndex(name)}, ${this.a.grammar.rules.findIndex((r) => r.name === name)}, ${this.ruleFn(name)}_pratt, ${lvl})) { ${onFail} }`; } - // A suppress-carrying group stages the LED-connector exclusion for the next - // parseRule (the index of its connector set, grammar-analysis suppressSets), then - // matches its body (same as matchExpr 'group'). - // The staging ends with the group, matched or not (interpreter.ts matchExpr 'group'). // A `when` group exists only where its condition holds over the word in force (interpreter.ts). if (expr.when !== undefined) { - const w = whenTest(expr.when); + const w = whenTest(expr.when, this.a.grammar.params); return [`if ((ctx & ${w.mask}) !== ${w.val}) { ${onFail} }`, this.matchInto(expr.body, onFail)].join('\n'); } - // A context marker parses its body in its word, then puts back the one in force. - if (expr.ctxMode) { - const c = this.id(); - return [`const ${c} = ctx; ctx = ${ctxWordOfMode(expr.ctxMode, this.a.splitSync)};`, this.matchInto(expr.body, `{ ctx = ${c}; ${onFail} }`), `ctx = ${c};`].join('\n'); + // A `ctx` group parses its body in the word its equations make, then puts back the one in force. + if (expr.ctx !== undefined) { + const c = this.id(), q = ctxEquation(expr.ctx, this.a.grammar.params); + return [`const ${c} = ctx; ctx = ${q.keep === 0 ? q.set : `(ctx & ${q.keep}) | ${q.set}`};`, this.matchInto(expr.body, `{ ctx = ${c}; ${onFail} }`), `ctx = ${c};`].join('\n'); } - if (!expr.suppress || !expr.suppress.length) return this.matchInto(expr.body, onFail); - return [`suppressNext = ${this.a.suppressSetOf(expr.suppress)};`, this.matchInto(expr.body, `{ suppressNext = 0; ${onFail} }`), `suppressNext = 0;`].join('\n'); + return this.matchInto(expr.body, onFail); } case 'not': { // Zero-width negative lookahead: succeed (no children) iff body does NOT match. - const kinds = this.notKwKinds(expr.body); - if (expr.reservable && !kinds) throw new Error('jsTarget: a reservable guard must test keywords'); + const words = notCtxWords(expr.body, this.a.grammar.params); + const kinds = this.notKwKinds(notStaticBody(expr.body)); + if (words.length && !kinds) throw new Error('jsTarget: a guard with context words must test keywords'); if (kinds) { // Fast: one keyword-kind membership test (no body matcher, nothing pushed). A reserved-word - // guard also refuses each word the context in force reserves (grammar-utils.ts CTX_WORDS). - const ctxWords = expr.reservable ? CTX_WORDS.flatMap((w, i) => { const k = this.a.symtab.kwLitKind.get(w); return k === undefined ? [] : [`((ctx & ${1 << i}) !== 0 && _tt === ${k})`]; }) : []; + // guard also refuses each word it refuses only in a context (its `when` items: notCtxWords). + const ctxWords = words.flatMap((w) => { const k = this.a.symtab.kwLitKind.get(w.text); return k === undefined ? [] : [`((ctx & ${w.mask}) === ${w.val} && _tt === ${k})`]; }); const cond = [...kinds.map(k => `_tt === ${k}`), ...ctxWords].join(' || '); return `if (pos < cap && tkK[pos] >= K_NAMED_MIN) { const _tt = tkT[pos]; if (${cond}) { ${onFail} } }`; } @@ -863,14 +873,21 @@ class Emitter { const item = items[k]; if (item.type !== 'literal') return 0; const comp = new Set(); - for (let j = k - 1; j >= 0; j--) { - const pj = items[j]; - if (pj.type === 'op' || pj.type === 'prefix' || pj.type === 'postfix') continue; - if (pj.type === 'quantifier' && pj.kind !== '?') { this.nullPrefixLits(pj.body, comp); continue; } - if (pj.type === 'quantifier' || pj.type === 'sep' || pj.type === 'not' || pj.type === 'sameLine' || pj.type === 'noCommentBefore') continue; - if (pj.type === 'group' && this.nullPrefixLits(pj.body, new Set())) continue; - break; - } + // true: every item of `list` up to `from` was crossed. A `ctx` group builds nothing of its own: + // its items are walked as the sequence's (`[ ctx(E, many(',', E)) ]` still offers `,`). + const back = (list: readonly RuleExpr[], from: number): boolean => { + for (let j = from; j >= 0; j--) { + const pj = list[j]!; + if (pj.type === 'op' || pj.type === 'prefix' || pj.type === 'postfix') continue; + if (pj.type === 'quantifier' && pj.kind !== '?') { this.nullPrefixLits(pj.body, comp); continue; } + if (pj.type === 'quantifier' || pj.type === 'sep' || pj.type === 'not' || pj.type === 'sameLine' || pj.type === 'noCommentBefore') continue; + if (pj.type === 'group' && pj.ctx !== undefined) { const body = pj.body.type === 'seq' ? pj.body.items : [pj.body]; if (back(body, body.length - 1)) continue; return false; } + if (pj.type === 'group' && this.nullPrefixLits(pj.body, new Set())) continue; + return false; + } + return true; + }; + back(items, k - 1); comp.delete(item.value); if (comp.size === 0) return 0; const msg = [...comp, item.value].map(v => "'" + v + "'").join(' or '); @@ -1587,7 +1604,7 @@ let rowCount = new Int32Array(8192); // validity across edits compares q + rowExt + slack against the damage start. let rowExt = new Int32Array(8192); // adoption eligibility: set ONLY where the old parse MEMOIZED the node — a row built -// under a suppress (no-'in') or parseLimit-capped context is a context-dependent +// under a parseLimit-capped context is a context-dependent // parse and must never be adopted into a normal entry (the memo carry never stored // those; adoption must not widen the contract). let rowOK = new Uint8Array(8192); @@ -1826,11 +1843,7 @@ let parseLimit = -1; // cap = the exclusive lookahead bound: min(parseLimit-or-∞, tokN), maintained at the // parseLimit set/restore sites. let cap = 0; -// Indices into the grammar's suppress sets (grammar-analysis suppressSets; 0 = none): the set a -// suppress group stages for the next pratt/left-rec parseRule, and the set in force in the current one. -let suppressNext = 0; -let suppressCur = 0; -// The context word in force (grammar-utils.ts CTX_PARAMS): set by a context marker for its body, +// The context word in force (Grammar.params, grammar-utils.ts whenTest): set by a ctx group for its body, // read by a \`when\`, a gated prefix operator and a reserved-word guard. let ctx = 0; @@ -1902,7 +1915,8 @@ function parseTemplateExpr(hole: () => boolean) { // expression and every span must continue (middle) or close (tail) — an // unterminated template is a parse failure, not a shorter match while (true) { - if (!hole() || pos >= cap) { pos = save; scn = mark; return false; } + ${e.a.holeEq ? `const _hc = ctx; ctx = ${e.a.holeEq.keep === 0 ? e.a.holeEq.set : `(ctx & ${e.a.holeEq.keep}) | ${e.a.holeEq.set}`}; const _hok = hole(); ctx = _hc; + if (!_hok || pos >= cap) { pos = save; scn = mark; return false; }` : 'if (!hole() || pos >= cap) { pos = save; scn = mark; return false; }'} const nk = tkK[pos]; if (nk === K_TEMPLATE_MIDDLE) { scPush(~(pos << 2)); @@ -1961,7 +1975,7 @@ function emitRuleFns(e: Emitter, a: ReturnType) { case 'group': // a context marker or a `when` between the container and its rep: the elements would not // be parsed in the container's word - if ((x.suppress && x.suppress.length) || x.ctxMode || x.when !== undefined) { bad = true; return; } + if (x.ctx !== undefined || x.when !== undefined) { bad = true; return; } walk(x.body); return; case 'literal': case 'ref': case 'op': case 'prefix': case 'postfix': return; case 'quantifier': @@ -2074,7 +2088,7 @@ function emitLeftRecRule(e: Emitter, a: ReturnType, rule: RuleDe const sn = sanitize(rule.name); const { atoms, continuations, contNotLeftLeaf } = a.leftRecClassified.get(rule.name)!; const contMix = a.contMeta.get(rule.name)!; - // A left-rec rule, like a Pratt rule, goes through parseRule's memo + suppress wrapper + // A left-rec rule, like a Pratt rule, goes through parseRule's memo + context wrapper // in the interpreter. const rid = a.grammar.rules.indexOf(rule); e.emit(`function ${ruleFn}() { return parseRuleEntry(${e.memoIndex(rule.name)}, ${rid}, ${ruleFn}_lr); }`); @@ -2257,9 +2271,10 @@ function emitPrattRule(e: Emitter, a: ReturnType, rule: RuleDecl const ftc = e.ftCond(meta.first[i], 'pos'); // pos < cap here (the loop breaks above) if (ftc) conds.push(ftc); } - // suppress: skip a LED while the set in force holds its first literal connector (tested - // once the next token is that connector); no gate for a led no set holds. - for (const set of a.suppressedIn(led.items[0]?.type === 'literal' ? led.items[0].value : null)) conds.push(`suppressCur !== ${set}`); + // a gated led (LedPrec.when): tried only where the word passes its test (once the next + // token is its connector). + const gate = led.items[0]?.type === 'literal' ? a.ledWhen.get(led.items[0].value) : undefined; + if (gate) conds.push(`(ctx & ${gate.mask}) === ${gate.val}`); e.emit(` // led ${i}`); e.emit(` if (${['!matched', ...conds].join(' && ')}) {`); e.emit(` pos = ledSaved; scn = ledMark;`); @@ -2452,7 +2467,9 @@ function emitMixfixLed(e: Emitter, a: ReturnType, fnName: string e.emit(` const saved = pos; const _sn = scn;`); e.emit(` if (!${e.matchLiteralCall(info.openLit)}) { pos = saved; scn = _sn; return false; }`); e.emit(` const afterOpen = pos; const aoMark = scn;`); - e.emit(` if (!${ruleFn}()) { pos = saved; scn = _sn; return false; }`); + // The operand under its `ctx` group's equations (MixfixInfo.eq), the word put back after. + const operandCall = info.eq === null ? `${ruleFn}()` : `((_c) => { ctx = ${info.eq.keep === 0 ? info.eq.set : `(ctx & ${info.eq.keep}) | ${info.eq.set}`}; const _r = ${ruleFn}(); ctx = _c; return _r; })(ctx)`; + e.emit(` if (!${operandCall}) { pos = saved; scn = _sn; return false; }`); e.emit(` const greedyEnd = pos;`); e.emit(` if (${e.matchLiteralCall(info.sepLit)}) { pos = saved; scn = _sn; return false; }`); const pu = (lit: string) => a.symtab.puLitKind.get(lit) ?? -1; @@ -2471,7 +2488,7 @@ function emitMixfixLed(e: Emitter, a: ReturnType, fnName: string e.emit(` for (const sepIdx of candidates) {`); e.emit(` pos = afterOpen; scn = aoMark;`); e.emit(` const prevLimit = parseLimit; parseLimit = sepIdx; cap = sepIdx;`); - e.emit(` const reOperand = ${ruleFn}();`); + e.emit(` const reOperand = ${operandCall};`); e.emit(` parseLimit = prevLimit; cap = prevLimit >= 0 ? prevLimit : tokN;`); e.emit(` if (!reOperand || pos !== sepIdx) continue;`); e.emit(` if (!${e.matchLiteralCall(info.sepLit)}) continue;`); @@ -2490,7 +2507,7 @@ function emitMixfixLed(e: Emitter, a: ReturnType, fnName: string // parseRule's pratt/left-rec branch) and the parse() driver. function emitDriver(e: Emitter) { e.emit(String.raw` -// parseRule for a pratt/left-rec rule: memo + context + suppress, then the core. +// parseRule for a pratt/left-rec rule: memo + context, then the core. // The memo is per-rule arrays indexed by start pos (lazily sized to the token count, // undefined-holed): a lookup is two array loads, a store allocates nothing — no Map // hashing and no {node, end} wrapper per store. The core returns a node ID (or -1); @@ -2505,12 +2522,10 @@ function emitDriver(e: Emitter) { // current frontier, so the value is tight on the dominant flow and only OVER- // invalidates (soundly) near big-backtrack clusters. // bp > 0: the rule read at an operator's level (atLevel): no memo (it is keyed by position only), -// the enclosing frame's no-in context kept, the recovery cycle refusal as for any entry. +// the recovery cycle refusal as for any entry. function parseRuleEntry(idx: number, rid: number, core: (minBp: number) => number, bp = 0) { const cx = ctx & RULE_OBS[rid]; idx += cx; - const mySup = suppressNext; - suppressNext = 0; const capped = parseLimit >= 0 || bp !== 0; const start = pos; let me = memoEnd[idx]; @@ -2522,7 +2537,7 @@ function parseRuleEntry(idx: number, rid: number, core: (minBp: number) => numbe // only, and whoever reuses it inherits the taint), or — across recovery attempts // of one sequence — any earlier attempt's entry whose probe window is bar-free // (strict, context-free behavior; see memoRecFloor) and untainted. - if (mySup === 0 && !capped && me !== undefined && (mgs === memoGenCur + if (!capped && me !== undefined && (mgs === memoGenCur || (recovering && (mgs === -memoGenCur || (mgs >= memoRecFloor && mgs < memoGenCur && !recoverFree && barFreeWin(start, mx[start])))))) { const e = me[start]; @@ -2556,7 +2571,7 @@ function parseRuleEntry(idx: number, rid: number, core: (minBp: number) => numbe return false; } } - if (mySup === 0 && !capped && adoptRoot >= 0) { + if (!capped && adoptRoot >= 0) { // map the new position into OLD token coordinates; inside the damage = no mapping const q = start < adoptDmgStart ? start : start >= adoptDmgOldEnd + adoptDelta ? start - adoptDelta : -1; @@ -2617,8 +2632,6 @@ function parseRuleEntry(idx: number, rid: number, core: (minBp: number) => numbe mySerial = ++recSerial; recRunning.set(recKey, mySerial); } - const prevSup = suppressCur; - if (bp === 0) suppressCur = mySup; const fm0 = frameMax; frameMax = start; const cm0 = cycleMinSerial; @@ -2627,7 +2640,6 @@ function parseRuleEntry(idx: number, rid: number, core: (minBp: number) => numbe try { result = core(bp); } finally { - suppressCur = prevSup; if (recKey >= 0) recRunning.delete(recKey); } let tainted = false; @@ -2639,7 +2651,7 @@ function parseRuleEntry(idx: number, rid: number, core: (minBp: number) => numbe if (cm0 < cycleMinSerial) cycleMinSerial = cm0; } if (result < 0 && recovering) { result = missRule(rid); _prattCapped = false; } // a synthesized $missing is no capped node - if (mySup === 0 && !capped) { + if (!capped) { if (me === undefined || me.length < tokN + 1) { me = new Array(tokN + 1); mn = new Array(tokN + 1); @@ -2715,8 +2727,6 @@ function runParse(entryRule?: string) { cycleMinSerial = 0x7fffffff; parseLimit = -1; cap = tokN; - suppressNext = 0; - suppressCur = 0; ctx = 0; scn = 0; const entry = entryRule ?? ENTRY; @@ -3301,7 +3311,6 @@ function trySurgery(dmgA: number, dmgB: number, tokD: number, chrD: number) { : dmgA; const s0 = pos; maxPos = pos; frameMax = pos; scn = 0; parseLimit = -1; cap = tokN; - suppressNext = 0; suppressCur = 0; // the elements are parsed in D's word (no context marker lies between D and its rep: SURG_ELEM) ctx = rowCtx[D]; const genAt = memoGenCur; diff --git a/src/targets/target-rust.ts b/src/targets/target-rust.ts index 5ca6372e..196b6de5 100644 --- a/src/targets/target-rust.ts +++ b/src/targets/target-rust.ts @@ -14,11 +14,11 @@ import { dropUnreferencedRs } from './rs-unreferenced.ts'; import { type ParserIR, type RdRule, type PrattRule, type NodeCap, type RuleIR, type NudRef, type Step, type Alt, type LexTok, type NewlineCfg, type FirstSig, type Guard, type LeadTest, type Dispatch, type LexFirstBytes, type LexIdPlan, type ArenaIdPlan, type ReusePlan, type AssignTargetsIR } from '../ir/parser-ir.ts'; import type { ArmForm } from '../ir/assign-targets.ts'; -import { prattTail, hasRebind, nudLowForm, demandTwinCond, demandLids, DEFER_SHIFT, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, CTX_WORD_BITS, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, TT_SKIP_PUNCT, isFirstGuardable, groupByPreserveOrder, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; +import { prattTail, hasRebind, nudLowForm, demandTwinCond, demandLids, DEFER_SHIFT, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, buildLidTables, lidWordByte, buildArenaIdPlan, withReservedRules, lidOf, lidDeltaTable, ctxWordLids, ctxWordBits, ctxWord, kidOf, lidFlagTable, kidFlagTable, ttIdOf, ruleIdOf, TT_SKIP_PUNCT, isFirstGuardable, groupByPreserveOrder, tokenSetBits, prattOpTables, prattOpRow, OP_ROW, binLeftOps, stepExpr as walkExpr, stepStmts as walkStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, type PortableFacts, type StepLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; import type { Grammar } from '../grammar/types.ts'; import { defineParserTarget, type SharedAlgorithms } from './define-parser-target.ts'; import type { EmitOptions } from './target.ts'; -import { ST_CAPPED, ST_FORM, ST_TAIL, ST_SUP_NEXT, ST_SUP_CUR, RM_DIAGS, RM_FAIL, RM_PROBE, RM_SP, RM_ATT, RM_AMAX, nativeCases, shorterDispatch } from '../ir/recovery-family.ts'; +import { ST_CAPPED, ST_FORM, ST_TAIL, RM_DIAGS, RM_FAIL, RM_PROBE, RM_SP, RM_ATT, RM_AMAX, nativeCases, shorterDispatch } from '../ir/recovery-family.ts'; import { beginRsShape, RS_SLOT, rsIsPlanFn, rsPlanFns, rsShapeCall, rsShapeLowering, rsShapeRuntime, setRsShape, type RsShape } from './rust-shape.ts'; import { ATOM, COMPARISON, findAnyName, stopBytes, unitMask, isList, isNum, isOpt, isRec, isRecList, isValList, isValTy, recName, type BinOp, type ListTy, type Lowering, type MetaInt, type MkMeta, type R, type TokInt } from '../ir/algo-ir.ts'; import { uniIdentPlan, uniLookup } from '../grammar/uni-ident.ts'; @@ -52,7 +52,7 @@ const guardCond = (g: Guard, t: string, keyed: boolean, recv = 'self'): string[] ...(g.pairs ?? []).map((x) => `${recv}.${rsLib('pair_in')}(${x.when.id}, &${t}, ${x.second.id})`)]; // A guard's lead test (parser-ir.ts LeadTest) on the buffered token t. const leadRs = (l: LeadTest, t: string, recv: string): string => { - const inS = l.ctx ? `(in_token_set(${l.set}, &${t}) || (${recv}.${rsLib('ctx')} & ${CTX_WORD_BITS} != 0 && in_ctx_words(${recv}.ctx, &${t})))` : `in_token_set(${l.set}, &${t})`; + const inS = l.ctx ? `(in_token_set(${l.set}, &${t}) || (${recv}.${rsLib('ctx')} & ${l.ctx} != 0 && in_ctx_words(${recv}.ctx, &${t})))` : `in_token_set(${l.set}, &${t})`; return l.is ? inS : `!${inS}`; }; // `if ` as one statement (just the body when there is no condition). @@ -148,9 +148,9 @@ const rsNeed = (name: string): boolean => rsLibUses.has(name); // (head_leaf_text alone reads it). Without `src` nothing borrows the input, so the struct, its impls // and the guard that holds it take no lifetime: rsLt is the lifetime argument, `'a, ` or nothing. // Spanned's `off` / `tok_start` likewise (read by a Pratt rule's finish and the recovery engine). -// The Pratt frame's state (capped, form, tail, the suppress sets): read by Pratt rules, target +// The Pratt frame's state (capped, form, tail): read by Pratt rules, target // contexts and the recovery engine; a grammar with none of them has no such fields. -const rsPrattInit = (ir: ParserIR): string => (rsNeed('pratt_state') ? ` capped: false, form: 0,${targetInitRs(ir)} tail: false, suppress_next: 0, suppress_cur: 0,` : ''); +const rsPrattInit = (ir: ParserIR): string => (rsNeed('pratt_state') ? ` capped: false, form: 0,${targetInitRs(ir)} tail: false,` : ''); // A finish's (handle, offset, present) as Spanned: bound by name where a Pratt rule reads the span // (the offset then always is), else by position, so that a module's recovery form (which reads // the offset) only adds tokens to it (test/portable-lists.ts, the default prefix). @@ -1233,7 +1233,7 @@ const finRs = (id: number | string, rest: string, p = 'self'): string => (SHAPE_ // that took `let p = self`; `r`: in recognize form (ParserIR.forms), advancing and building // nothing. Rust: a body is a non-capturing closure `|p| …` (a `fn(&mut Parser) -> bool`, so no // environment is allocated), whose receiver is its own `p` (inner); a choice's statements are a -// closure called in place; a suppress / ctx body is a block expression. +// closure called in place; a ctx body is a block expression. function rsSteps(ids: LexIdPlan, recv: 'self' | 'p', r: boolean, guards = true): StepLowering { const R = r ? '_r' : ''; const L: StepLowering = { @@ -1292,9 +1292,8 @@ function rsSteps(ids: LexIdPlan, recv: 'self' | 'p', r: boolean, guards = true): when: (mask, val) => `(${recv}.${rsLib('ctx')} & ${mask} == ${val})`, inPlace: (kind, stmts) => (kind === 'alt' ? `(|p: &mut Self| -> bool { ${stmts} })(${recv})` : stmts), ret: (cond) => cond, - suppress: (set, cond) => `{ ${recv}.suppress_next = ${set}; let _r = (${cond}); ${recv}.suppress_next = 0; _r }`, // The body is a boolean expression (no `?`, no return), so the context is put back on either outcome. - ctx: (ctx, cond) => `{ let _c = ${recv}.${rsLib('ctx')}; ${recv}.ctx = ${ctx}; let _r = (${cond}); ${recv}.ctx = _c; _r }`, + ctx: (keep, set, cond) => `{ let _c = ${recv}.${rsLib('ctx')}; ${recv}.ctx = ${ctxWord(keep, set, '_c')}; let _r = (${cond}); ${recv}.ctx = _c; _r }`, branch: (cond, clean) => branchRs(cond, r, clean), guarded: (first, branch) => `if let Some(t) = _ft { if ${firstCond(first, 't', ids)} ${branch} }`, choice: (peek, tries, total) => `${peek ? `let _ft = ${recv}.peek(); ` : ''}${tries.join(' ')}${total ? '' : ' false'}`, @@ -1697,7 +1696,7 @@ function prattRule(r: PrattRule, ir: ParserIR, ids: LexIdPlan, ar: ArenaIdPlan): lbpAbove: (lbp) => `${lbp} > min_bp`, sameLine: '!t.nl', notLeftLeaf: (words) => `!self.${rsLib('nll_blocked')}(&[${words.map(J).join(', ')}], &left)`, - notSuppressed: (set) => `self.suppress_cur != ${set}`, + when: (mask, val) => `self.ctx & ${mask} == ${val}`, ifAll: (parts) => (parts.length ? `if ${parts.join(' && ')} ` : ''), }, ledArm: (i, cond, form, closes, exit, clean, rebind, capsFromTail) => { const fin = finK(`led${i}`); return `{ @@ -1742,12 +1741,7 @@ ${kids.map((k) => ` ${k} => { if !tail_closed { let sb = self.scr form = ${binF};${prattTail(r) === 'none' ? '' : ' tail_closed = true;'} }`; }, entry: (bp) => ` fn parse_${r.name}(&mut self) -> Option> { - let prev = self.suppress_cur; - self.suppress_cur = self.suppress_next; - self.suppress_next = 0; - let r = self.${r.name}_bp(${bp ? '0' : ''}); - self.suppress_cur = prev; - r + self.${r.name}_bp(${bp ? '0' : ''}) } /// The operator row per lid (parser-ir prattOpRow: binary lbp / rbp / flags, postfix lbp / target, composite lead, led index). const ${r.name}_ROW: [u32; ${row.size}] = [${row.rows.join(', ')}]; @@ -2237,7 +2231,7 @@ function emitParserMachine(ir: ParserIR, ids: LexIdPlan, ar: ArenaIdPlan, shapeB let save = self.pos; let sb = self.scratch.len(); let ck = self.b.checkpoint(); self.push_leaf(${ttIdOf(ar, '$templateHead')}, self.pos as u32, t.off, t.end); self.pos += 1; loop { - let expr = match interp(self) { Some(e) => e, None => { self.back(save); self.scratch.truncate(sb); self.b.restore(ck); return None; } }; + let expr = match ${ir.tpl?.holeCtx ? `{ let _hc = self.ctx; self.ctx = ${ctxWord(ir.tpl.holeCtx.keep, ir.tpl.holeCtx.set, '_hc')}; let _hr = interp(self); self.ctx = _hc; _hr }` : 'interp(self)'} { Some(e) => e, None => { self.back(save); self.scratch.truncate(sb); self.b.restore(ck); return None; } }; if expr.present { self.scratch.push(expr.h); } let next = match self.peek() { Some(x) => x, None => { self.back(save); self.scratch.truncate(sb); self.b.restore(ck); return None; } }; if next.kid == ${kidOf(ids, "$templateMiddle")} { self.push_leaf(${ttIdOf(ar, '$templateMiddle')}, self.pos as u32, next.off, next.end); self.pos += 1; continue; } @@ -2649,12 +2643,8 @@ struct Parser<${rsLt()}B: Builder = CstBuilder> { /// Assignment-target form of the node the last nud/bp call returned. form: u8,${targetFieldsRs(ir)} /// Whether the node the last nud call returned closes the access tail. - tail: bool, - /// Indices into the grammar's suppress sets (ParserIR.suppressSets; 0 = none): the set a - /// \`suppress\` step stages for the next Pratt call, and the set in force in the current one. - suppress_next: u16, - suppress_cur: u16,` : ''}${rsNeed('ctx') ? ` - /// The [Await]/[Yield] context word in force (bit 1 await, bit 2 yield; see ParserIR's Ctx). + tail: bool,` : ''}${rsNeed('ctx') ? ` + /// The context word in force (a bit per context parameter; see parser-ir.ts's context word). /// A \`ctx\` step sets it for its body and puts back what it found, so outside every such body it is 0. ctx: u8,` : ''}${rsNeed('head_leaf_text') ? ` src: &'a str,` : ''} @@ -2695,7 +2685,7 @@ ${rsNeed('ahead') ? ` #[inline(always)] fn ahead(&mut self, k: usize, is: bool) -> bool { match self.peek() { Some(t) => in_token_set(k, &t) == is, None => !is } } ` : ''}${rsNeed('ctx_word') ? ` #[inline(always)] /// Whether the next token is a word the context in force reserves; outside every context it reads nothing. - fn ctx_word(&mut self) -> bool { ${ctxWordLids(ir, ids).length ? `self.ctx & ${CTX_WORD_BITS} != 0 && match self.peek() { Some(t) => in_ctx_words(self.ctx, &t), None => false }` : 'false'} } + fn ctx_word(&mut self) -> bool { ${ctxWordLids(ir, ids).length ? `self.ctx & ${ctxWordBits(ir)} != 0 && match self.peek() { Some(t) => in_ctx_words(self.ctx, &t), None => false }` : 'false'} } ` : ''}${rsNeed('second_in') ? ` /// Whether the token after the current one is in token set k (a longest-match candidate's SECOND guard). #[inline(always)] fn second_in(&mut self, k: usize) -> bool { @@ -3071,7 +3061,6 @@ function rustShapeFirstOfSteps(steps: Step[]): FirstSig { return 'done'; } case 'seq': - case 'suppress': case 'ctx': return walkSeq(s.steps); case 'look': case 'ahead': @@ -3344,7 +3333,6 @@ function emitRustAstRdAltSteps( case 'star': return visible(s.step); case 'opt': case 'seq': - case 'suppress': case 'ctx': return s.steps.some(visible); case 'sep': return visible(s.elem); case 'altlit': return s.opts.some((o) => !rustLeafDropped(o.ttype, leaves)); @@ -3361,7 +3349,7 @@ function emitRustAstRdAltSteps( * pos/vals (so a surrounding txn can use the 2-field light snapshot). * lit/tok/altlit touch pos + vals only; sameLine is read-only; look is * self-restoring (full ck/restore inside) and externally transparent; - * suppress self-restores suppress_next, ctx the context. Visible star/opt/sep/alt write + * ctx self-restores the context. Visible star/opt/sep/alt write * the arena via shape_pack_range/shape_list_from on success paths — * impure. rule/ruleBp call parse_ast_* which may write the arena * (customs/pack) — always impure. */ @@ -3376,7 +3364,6 @@ function emitRustAstRdAltSteps( case 'ahead': return true; case 'aheadCtx': return true; case 'look': return true; - case 'suppress': return s.steps.every(pure); case 'ctx': return s.steps.every(pure); case 'seq': return s.steps.every(pure); case 'star': return !visible(s.step) && pure(s.step); @@ -3390,8 +3377,8 @@ function emitRustAstRdAltSteps( /** M18: txn snapshot pair — pure guarded steps get a light snapshot of the * three mutable channels a pure txn can touch (pos, vals, ap_stack — the * alt-branch shell pushes ap_stack inside the guarded region, so the light - * restore must rewind it too); anything that can touch the arena, suppress - * state or capped keeps the full ShapeCk. */ + * restore must rewind it too); anything that can touch the arena or capped + * keeps the full ShapeCk. */ const txnCk = (v: string, light: boolean): string => light ? `let ${v} = (self.pos, self.vals.len(), self.ap_stack.len());` : `let ${v} = self.shape_ck();`; const txnRestore = (v: string, light: boolean): string => @@ -3439,7 +3426,7 @@ function emitRustAstRdAltSteps( case 'ahead': return `if ${okVar} && self.toks.get(self.pos).map_or(false, |t| in_token_set(${s.set}, t)) != ${s.is} { ${okVar} = false; }`; case 'aheadCtx': - return `if ${okVar} && self.toks.get(self.pos).map_or(false, |t| in_token_set(${s.set}, t) || (self.ctx & ${CTX_WORD_BITS} != 0 && in_ctx_words(self.ctx, t))) != ${s.is} { ${okVar} = false; }`; + return `if ${okVar} && self.toks.get(self.pos).map_or(false, |t| in_token_set(${s.set}, t) || in_ctx_words(self.ctx, t)) != ${s.is} { ${okVar} = false; }`; case 'look': { // Gate on okVar to match TS `&&` short-circuit — otherwise probe still // runs after a failed predecessor and can re-enter recursive rules. @@ -3456,23 +3443,12 @@ function emitRustAstRdAltSteps( if _probe_hit != ${s.is} { ${okVar} = false; } }`; } - case 'suppress': { - const sok = local('sup_ok'); - return `if ${okVar} { - let _sn_save = self.suppress_next; - self.set_suppress_next(${s.set}); - let mut ${sok} = true; - ${emitSteps(s.steps, sok)} - self.set_suppress_next(_sn_save); - if !${sok} { ${okVar} = false; } - }`; - } case 'ctx': { // The steps hold no return and no \`?\`, so the context is put back on either outcome. const cok = local('ctx_ok'); return `if ${okVar} { let _ctx_save = self.ctx; - self.ctx = ${s.ctx}; + self.ctx = ${ctxWord(s.keep, s.set, '_ctx_save')}; let mut ${cok} = true; ${emitSteps(s.steps, cok)} self.ctx = _ctx_save; @@ -4030,7 +4006,7 @@ function emitRustPrattMethod( let mut kids: Vec> = vec![SVal::Str(t.off, t.end - t.off)]; self.pos += 1; loop { - let accept_hole = match self.parse_ast_${holeRule}() { + let accept_hole = match ${ir.tpl?.holeCtx ? `{ let _hc = self.ctx; self.ctx = ${ctxWord(ir.tpl.holeCtx.keep, ir.tpl.holeCtx.set, '_hc')}; let _hr = self.parse_ast_${holeRule}(); self.ctx = _hc; _hr }` : `self.parse_ast_${holeRule}()`} { Some(v) => v, None => { self.shape_tpl_restore(&save_snap); return None; } }; @@ -4578,7 +4554,7 @@ function emitRustPrattMethod( const stepsCloseWithGt = (steps: Step[]): boolean => { for (const s of steps) { if (s.t === 'lit' && s.value === '>') return true; - if (s.t === 'seq' || s.t === 'suppress' || s.t === 'ctx') { if (stepsCloseWithGt(s.steps)) return true; } + if (s.t === 'seq' || s.t === 'ctx') { if (stepsCloseWithGt(s.steps)) return true; } } return false; }; @@ -4604,7 +4580,8 @@ function emitRustPrattMethod( const set = rule.ledNotLeftLeaf[i]!; parts.push(`{ let _ht = self.shape_head_text(left); !matches!(Self::shape_sval_str(&self.arena, _ht), ${set.map((x) => J(x)).join(' | ')}) }`); } - for (const set of rule.ledSuppressedIn[i]!) parts.push(`self.suppress_cur != ${set}`); + const gate = rule.ledWhen[i]; + if (gate) parts.push(`self.ctx & ${gate.mask} == ${gate.val}`); const st = emptySteps(b.steps); let finish: string; if (ledSlot.kind === 'custom') { @@ -4677,16 +4654,7 @@ function emitRustPrattMethod( const hasLoop = !!(ledCode || postfixCode || postfixTokCode || binaryBody); return `${tplHelperCode} fn parse_ast_${rule.name}(&mut self) -> Option<${ret}> { - // Fast path: no pending suppress swap — skip the log traffic. - if self.suppress_next == 0 && self.suppress_cur == 0 { - return self.parse_ast_${rule.name}_bp(0); - } - let prev = self.suppress_cur; - let _sn = self.take_suppress_next(); - self.set_suppress_cur(_sn); - let r = self.parse_ast_${rule.name}_bp(0); - self.set_suppress_cur(prev); - r + self.parse_ast_${rule.name}_bp(0) } fn parse_ast_${rule.name}_bp(&mut self, min_bp: i64) -> Option<${ret}> { let _off = self.current_off(); @@ -4723,7 +4691,7 @@ function rustShapeUnsupported(ir: ParserIR, shapeIR: ShapeIR): Array<{ rule: str if (!supportedLeaf(step.name) || shapeIR.leaves[step.name]?.action === 'drop') note(rule, `step:tok-policy:${step.name}`); } else if (step.t === 'alt') { for (const branch of step.branches) for (const s of branch) walkStep(rule, s); - } else if (step.t === 'opt' || step.t === 'seq' || step.t === 'suppress' || step.t === 'ctx') { + } else if (step.t === 'opt' || step.t === 'seq' || step.t === 'ctx') { for (const s of step.steps) walkStep(rule, s); } else if (step.t === 'look') { for (const s of ir.lookaheads[step.id]!) walkStep(rule, s); @@ -5030,9 +4998,6 @@ pub trait ShapeCustoms<'a> { pub struct DefaultShapeCustoms; impl ShapeCustoms<'_> for DefaultShapeCustoms {} -// suppress_next / suppress_cur are indices into the grammar's suppress sets -// (ParserIR.suppressSets; 0 = none): no allocation, and the undo log just -// records old values (SH3-6 M3). #[derive(Clone, Copy)] struct ShapeCk { pos: usize, @@ -5049,7 +5014,6 @@ struct ShapeCk { // reclaimed), not a dangling-ref bug. strings is near-unused in this grammar // (head_text is rare), so the leak is negligible. ap_len: usize, - suppress_log_len: usize, capped: bool, // events_len is only meaningful when emit_events (parse_ast_with_buf / // parse_stream_buf). With emit_events=false events never grows, so shape_ck @@ -5060,8 +5024,6 @@ struct ShapeCk { #[derive(Clone, Copy)] struct ShapeTplSnap { pos: usize, - suppress_next: u16, - suppress_cur: u16, capped: bool, events_len: usize, } @@ -5078,10 +5040,7 @@ struct ShapeParser<'a, 'c, C: ShapeCustoms<'a>> { vals: Vec>, /// Global alt_path stack: rule alt index + nested alt-step branch picks. ap_stack: Vec, - suppress_next: u16, - suppress_cur: u16, - suppress_log: Vec<(u8, u16)>, - /// The [Await]/[Yield] context word in force (see Parser::ctx); a \`ctx\` step restores it itself. + /// The context word in force (see Parser::ctx); a \`ctx\` step restores it itself. ctx: u8, capped: bool, /// Assignment-target form of the node the last nud/bp call returned. @@ -5128,35 +5087,15 @@ impl<'a, 'c, C: ShapeCustoms<'a>> ShapeParser<'a, 'c, C> { self.pos += 1; Some(span) } - #[inline(always)] - fn set_suppress_next(&mut self, v: u16) { - let old = std::mem::replace(&mut self.suppress_next, v); - self.suppress_log.push((0, old)); - } - #[inline(always)] - fn set_suppress_cur(&mut self, v: u16) { - let old = std::mem::replace(&mut self.suppress_cur, v); - self.suppress_log.push((1, old)); - } - #[inline(always)] - fn take_suppress_next(&mut self) -> u16 { - let old = std::mem::take(&mut self.suppress_next); - self.suppress_log.push((0, old)); - old - } fn shape_tpl_snap(&self) -> ShapeTplSnap { ShapeTplSnap { pos: self.pos, - suppress_next: self.suppress_next, - suppress_cur: self.suppress_cur, capped: self.capped, events_len: self.events.len(), } } fn shape_tpl_restore(&mut self, snap: &ShapeTplSnap) { self.pos = snap.pos; - self.suppress_next = snap.suppress_next; - self.suppress_cur = snap.suppress_cur; self.capped = snap.capped; self.events.truncate(snap.events_len); } @@ -5167,7 +5106,6 @@ impl<'a, 'c, C: ShapeCustoms<'a>> ShapeParser<'a, 'c, C> { vals_len: self.vals.len(), lists_len: self.arena.lists.len(), ap_len: self.ap_stack.len(), - suppress_log_len: self.suppress_log.len(), capped: self.capped, // events_len is structurally 0 when emit_events=false (events never // grows); gating the load here keeps the parse_ast snapshot cheaper @@ -5181,13 +5119,6 @@ impl<'a, 'c, C: ShapeCustoms<'a>> ShapeParser<'a, 'c, C> { self.vals.truncate(ck.vals_len); self.arena.lists.truncate(ck.lists_len); self.ap_stack.truncate(ck.ap_len); - while self.suppress_log.len() > ck.suppress_log_len { - match self.suppress_log.pop() { - Some((0, old)) => self.suppress_next = old, - Some((_, old)) => self.suppress_cur = old, - None => break, - } - } self.capped = ck.capped; // Only the emit_events walk (parse_ast_with_buf / parse_stream_buf) // populates self.events, so only that path needs the rollback truncate. @@ -5495,7 +5426,7 @@ fn parse_ast_impl<'a, 'c, C: ShapeCustoms<'a>>(src: &'a str, customs: &'c C, emi }, vals: Vec::with_capacity(1024), ap_stack: Vec::with_capacity(256), - suppress_next: 0, suppress_cur: 0, ctx: 0, suppress_log: Vec::with_capacity(64), capped: false, form: 0,${targetInitRs(ir)} tail: false, + ctx: 0, capped: false, form: 0,${targetInitRs(ir)} tail: false, emit_events, events: events_init, }; @@ -5927,6 +5858,7 @@ ${decls.join('')}${shared.recoveryFamily(ir, true).split('\n').map((l) => (l ? ` fn en_ahead(&mut self, set: isize, is: bool) -> bool { self.p.ahead(set as usize, is) } fn en_ctx_word(&mut self) -> bool { self.p.ctx_word() } fn en_when(&mut self, mask: isize, val: isize) -> bool { (self.p.ctx as isize) & mask == val } + fn en_ctx_set(&mut self, keep: isize, set: isize) { self.p.ctx = (((self.p.ctx as isize) & keep) | set) as u8; } fn en_second_in(&mut self, set: isize) -> bool { self.p.second_in(set as usize) } fn en_look(&mut self, id: isize) -> bool { ${dLook} } fn en_rule(&mut self, r: isize) -> bool { ${dRule} } @@ -5983,11 +5915,11 @@ ${decls.join('')}${shared.recoveryFamily(ir, true).split('\n').map((l) => (l ? ` } fn en_st(&mut self, k: isize) -> isize { let p = &*self.p; - match k { ${ST_CAPPED} => p.capped as isize, ${ST_FORM} => p.form as isize, ${ST_TAIL} => p.tail as isize, ${ST_SUP_NEXT} => p.suppress_next as isize, ${ST_SUP_CUR} => p.suppress_cur as isize, _ => p.ctx as isize } + match k { ${ST_CAPPED} => p.capped as isize, ${ST_FORM} => p.form as isize, ${ST_TAIL} => p.tail as isize, _ => p.ctx as isize } } fn en_set_st(&mut self, k: isize, v: isize) { let p = &mut *self.p; - match k { ${ST_CAPPED} => p.capped = v != 0, ${ST_FORM} => p.form = v as u8, ${ST_TAIL} => p.tail = v != 0, ${ST_SUP_NEXT} => p.suppress_next = v as u16, ${ST_SUP_CUR} => p.suppress_cur = v as u16, _ => p.ctx = v as u8 } + match k { ${ST_CAPPED} => p.capped = v != 0, ${ST_FORM} => p.form = v as u8, ${ST_TAIL} => p.tail = v != 0, _ => p.ctx = v as u8 } } fn en_tick(&mut self) { self.steps += 1; } ${hasRebind(ir) ? ` // The re-bind (rebind-family.ts): the parser's marks and token read; the capped operand interpreted. @@ -6075,7 +6007,7 @@ pub fn parse_total_work<'a, B: Builder + Default>(src: &'a str, b: &mut B) -> (O p.scratch.clear(); p.pos = 0; p.look_reset(); - p.capped = false; p.form = 0; p.tail = false; p.suppress_next = 0; p.suppress_cur = 0; p.ctx = 0; + p.capped = false; p.form = 0; p.tail = false; p.ctx = 0; let tab_rt: &'static [isize] = TAB_RT.get_or_init(|| unpack_ints(TABS_RT)); let mut rv = Recov { p, marks: Vec::new(), rm: fresh_rm(), tab_rt, fin_off: 0, op_n: 0, op_end: 0, steps: 0 }; rv.ri_total(); diff --git a/src/targets/target-ts.ts b/src/targets/target-ts.ts index ad5000f5..8ed4154f 100644 --- a/src/targets/target-ts.ts +++ b/src/targets/target-ts.ts @@ -5,9 +5,9 @@ // is checked byte-for-byte against the interpreter (createParser), so a divergence in the // portable logic surfaces here before Go/Rust are compiled. import { type ParserIR, type RdRule, type PrattRule, type NodeCap, type NudRef, type Step, type Alt, type LexTok, type NewlineCfg, type FirstSig, type Guard, type Dispatch, type LexFirstBytes, type LexIdPlan, type ReusePlan, type ShapeInhVal, type AssignTargetsIR } from '../ir/parser-ir.ts'; -import { prattTail, hasRebind, nudLowForm, demandTwinCond, demandLids, DEFER_SHIFT, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, lidOf, lidDeltaTable, ctxWordLids, CTX_WORD_BITS, kidOf, lidFlagTable, kidFlagTable, groupByPreserveOrder, tokenSetBits, prattOpTables, OP_ROW, prattOpRow, binLeftOps, stepExpr, stepStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, buildArenaIdPlan, withReservedRules, type PortableFacts, type StepLowering, type RuleLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; +import { prattTail, hasRebind, nudLowForm, demandTwinCond, demandLids, DEFER_SHIFT, blockBody, elementBraceSteps, elementSkipsText, regionKids, portableIR, sepDelimLid, buildLexDispatchPlan, lexTokFirstBytes, punctFirstBytes, buildLexIdPlan, buildLidPrefilter, lidOf, lidDeltaTable, ctxWordLids, ctxWordBits, ctxWord, kidOf, lidFlagTable, kidFlagTable, groupByPreserveOrder, tokenSetBits, prattOpTables, OP_ROW, prattOpRow, binLeftOps, stepExpr, stepStmts, ruleShell, prattShell, entryShell, gtCompLit, compLeadLids, buildArenaIdPlan, withReservedRules, type PortableFacts, type StepLowering, type RuleLowering, type DispatchLowering, type PrattLowering, type CommitLowering } from '../ir/parser-ir.ts'; import type { ArmForm } from '../ir/assign-targets.ts'; -import { ST_CAPPED, ST_FORM, ST_TAIL, ST_SUP_NEXT, ST_SUP_CUR, RM_DIAGS, RM_ATT, RM_AMAX, RM_FAIL, RM_PROBE, RM_SP, nativeCases, shorterDispatch } from '../ir/recovery-family.ts'; +import { ST_CAPPED, ST_FORM, ST_TAIL, RM_DIAGS, RM_ATT, RM_AMAX, RM_FAIL, RM_PROBE, RM_SP, nativeCases, shorterDispatch } from '../ir/recovery-family.ts'; import type { EmitOptions } from './target.ts'; import type { Grammar } from '../grammar/types.ts'; import type { @@ -703,7 +703,7 @@ function lexAll(src: string): [Tok[], LexErr | null] { }`; } -// Lifted steps. A step printed as a function — the body of a star / opt / sep, an `alt`, `suppress`, +// Lifted steps. A step printed as a function — the body of a star / opt / sep, an `alt`, // `ctx` or `sameLine` step — reads no local of the function around its site (its state is the // cursor and the child stack), so it is one module-level function, printed once per distinct body, // instead of a closure allocated at every evaluation of its site. Per emit (keyed by its id plan): @@ -807,8 +807,7 @@ function tsSteps(ids: LexIdPlan, m: Mode): StepLowering { when: (mask, val) => `((_ctx & ${mask}) === ${val})`, inPlace: (_kind, stmts) => `${lift(ids, stmts)}()`, ret: (cond) => `return ${cond};`, - suppress: (set, cond) => `_suppressNext = ${set}; const _r = (${cond}); _suppressNext = 0; return _r;`, - ctx: (ctx, cond) => `const _c = _ctx; _ctx = ${ctx}; const _r = (${cond}); _ctx = _c; return _r;`, + ctx: (keep, set, cond) => `const _c = _ctx; _ctx = ${ctxWord(keep, set, '_c')}; const _r = (${cond}); _ctx = _c; return _r;`, // A branch that fails clean (Step.clean) has nothing to undo: no frame. branch: (cond, clean) => (clean ? `{ if (${cond}) return true; }` : branchTs(cond, m)), guarded: (first, branch) => `if (_ft !== null && ${firstCond(first, '_ft', ids)}) ${branch}`, @@ -1092,7 +1091,7 @@ function prattRuleW(r: PrattRule, ir: ParserIR, ids: LexIdPlan): string { lbpAbove: (lbp) => `${lbp} > minBp`, sameLine: '!t.nl', notLeftLeaf: (words) => `!${liftConst(ids, J(words))}.includes(headLeafTextW(b))`, - notSuppressed: (set) => `_suppressCur !== ${set}`, + when: (mask, val) => `(_ctx & ${mask}) === ${val}`, ifAll: (parts) => (parts.length ? `if (${parts.join(' && ')}) ` : ''), }, ledArm: (i, cond, form, closes, exit, _clean, rebind, capsFromTail) => { @@ -1140,10 +1139,7 @@ ${kids.map((k) => ` case ${k}: }`, entry: (bp) => `${tsPrattOpTables(r, ids)} function parse${r.name}W(): boolean { - const prev = _suppressCur; _suppressCur = _suppressNext; _suppressNext = 0; - const r = ${r.name}_bpW(${bp ? '0' : ''}); - _suppressCur = prev; - return r; + return ${r.name}_bpW(${bp ? '0' : ''}); }`, bpOpen: (label, nudBp, bp, tail) => `function ${r.name}_bpW(${bp ? 'minBp: number' : ''}): boolean { const b = _n;${rsOf(r.name) ? ' const p0 = pos; let nr = 0;' : dem.length ? ' const p0 = pos;' : ''} @@ -1275,7 +1271,8 @@ function matchTemplateW(interp: () => boolean): boolean { const save = pos, c = _n; leafSlotW('$templateHead', t); pos++; for (;;) { - if (!interp()) { back(save); _n = c; return false; } + ${ir.tpl?.holeCtx ? `const _hc = _ctx; _ctx = ${ctxWord(ir.tpl.holeCtx.keep, ir.tpl.holeCtx.set, '_hc')}; const _ok = interp(); _ctx = _hc; + if (!_ok) { back(save); _n = c; return false; }` : 'if (!interp()) { back(save); _n = c; return false; }'} const next = peek(); if (next === null) { back(save); _n = c; return false; } if (next.kid === ${kidOf(ids, '$templateMiddle')}) { leafSlotW('$templateMiddle', next); pos++; continue; } @@ -1768,7 +1765,7 @@ ${reuseFns}`; type ShapeStepKind = | 'lit' | 'tok' | 'rule' | 'ruleBp' | 'star' | 'opt' | 'sep' - | 'altlit' | 'alt' | 'look' | 'ahead' | 'aheadCtx' | 'seq' | 'sameLine' | 'when' | 'suppress' | 'ctx'; + | 'altlit' | 'alt' | 'look' | 'ahead' | 'aheadCtx' | 'seq' | 'sameLine' | 'when' | 'ctx'; type ShapePrattKind = | 'atom' | 'group' | 'prefix' | 'binary' | 'postfix' | 'postfixTok' | 'led' | 'nudSeq' | 'nudCapped' | 'template'; @@ -1776,7 +1773,7 @@ type ShapeUnsupported = { rule: string; construct: string }; const SHAPE_STEP_KINDS: readonly ShapeStepKind[] = [ 'lit', 'tok', 'rule', 'ruleBp', 'star', 'opt', 'sep', - 'altlit', 'alt', 'look', 'ahead', 'aheadCtx', 'seq', 'sameLine', 'when', 'suppress', 'ctx', + 'altlit', 'alt', 'look', 'ahead', 'aheadCtx', 'seq', 'sameLine', 'when', 'ctx', ]; const SHAPE_PRATT_KINDS: readonly ShapePrattKind[] = [ 'atom', 'group', 'prefix', 'binary', 'postfix', 'postfixTok', @@ -1971,7 +1968,6 @@ function emitAstRdAltSteps( case 'star': return visible(s.step); case 'opt': case 'seq': - case 'suppress': case 'ctx': return s.steps.some(visible); case 'sep': return visible(s.elem); case 'altlit': return s.opts.some((o) => !leafDropped(o.ttype, leaves)); @@ -2026,10 +2022,8 @@ function emitAstRdAltSteps( const nv = local('Not'); return `(() => { const ${nv}: unknown[] = []; return ${s.is ? '' : '!'}_shapeProbe(${nv}, _ap, () => ${emitSteps(ctx.look[s.id]!, nv)}); })()`; } - case 'suppress': - return `(() => { _suppressNext = ${s.set}; const _r = (${emitSteps(s.steps, sink)}); _suppressNext = 0; return _r; })()`; case 'ctx': - return `(() => { const _c = _ctx; _ctx = ${s.ctx}; const _r = (${emitSteps(s.steps, sink)}); _ctx = _c; return _r; })()`; + return `(() => { const _c = _ctx; _ctx = ${ctxWord(s.keep, s.set, '_c')}; const _r = (${emitSteps(s.steps, sink)}); _ctx = _c; return _r; })()`; case 'altlit': { const arms = s.opts.map((o) => `if (t.lid === ${lidOf(ids, o.value)}) { pos++; ${visible(s) ? `${sink}.push(${leafDropped(o.ttype, leaves) ? 'null' : J(o.value)});` : ''} return true; }`, @@ -2719,7 +2713,8 @@ ${code} if (r.ledLbp[i] !== null && r.ledLbp[i] !== undefined) parts.push(`${r.ledLbp[i]} > minBp`); if (r.ledSameLine[i]) parts.push('!t.nl'); if (r.ledNotLeftLeaf[i]) parts.push(`!${J(r.ledNotLeftLeaf[i])}.includes(_shapeHeadText(left))`); - for (const set of r.ledSuppressedIn[i]!) parts.push(`_suppressCur !== ${set}`); + const gate = r.ledWhen[i]; + if (gate) parts.push(`(_ctx & ${gate.mask}) === ${gate.val}`); return parts.length ? `if (${parts.join(' && ')}) ` : ''; // the `if` before the led's block; none when nothing gates it }; // A lid that ALSO has a binary entry (`<` is both a type-arg LED and the @@ -2897,8 +2892,6 @@ ${hasBin ? '' : (j === g.members.length - 1 ? ' break ledLoop;' : '')} } } - // Binary `$ op $` path must NOT consult `_suppressCur` — exclude/suppress only - // disables literal-headed LEDs (e.g. `[$, 'in', $]`), matching CST / interpreter. let binaryCode = ' break;'; if (binarySlot) { if (binarySlot.kind === 'node') { @@ -2942,12 +2935,7 @@ ${hasBin ? '' : (j === g.members.length - 1 ? ' break ledLoop;' : '')} // Capped NUD returns early with _capped=true BEFORE the IIFE (CST oracle). // Non-capped path forces _capped=false after the IIFE — only the capped arms above produce a capped node. return finalize(`function parseAst${r.name}(): ${retType} | null { - const prev = _suppressCur; - _suppressCur = _suppressNext; - _suppressNext = 0; - const r = parseAst${r.name}_bp(0); - _suppressCur = prev; - return r; + return parseAst${r.name}_bp(0); } function parseAst${r.name}_bp(minBp: number): ${retType} | null { let left = parseAst${r.name}_nud(minBp); @@ -2994,11 +2982,11 @@ function emitShapeParseHelpers(ir: ParserIR, ids: LexIdPlan): string { // Shape template kids helper. CST matchTemplate is untouched (byte-identical). // interp: the rule that parses each hole and yields its AST — the one the matching // reference declares (≡ CST matchTemplate). - const tplHelper = tpl ? `function _shapeTplSnap(): { pos: number; capped: boolean; sn: number; sc: number } { - return { pos, capped: _capped, sn: _suppressNext, sc: _suppressCur }; + const tplHelper = tpl ? `function _shapeTplSnap(): { pos: number; capped: boolean } { + return { pos, capped: _capped }; } -function _shapeTplRestore(s: { pos: number; capped: boolean; sn: number; sc: number }): void { - pos = s.pos; _capped = s.capped; _suppressNext = s.sn; _suppressCur = s.sc; +function _shapeTplRestore(s: { pos: number; capped: boolean }): void { + pos = s.pos; _capped = s.capped; } function matchTemplateAstKids(interp: () => unknown | null): { kids: unknown[]; save: number } | null { const t = peek(); @@ -3009,7 +2997,7 @@ function matchTemplateAstKids(interp: () => unknown | null): { kids: unknown[]; kids.push(_shapeLeafString(t)); pos++; for (;;) { - const holeAst = interp(); + ${ir.tpl?.holeCtx ? `const _hc = _ctx; _ctx = ${ctxWord(ir.tpl.holeCtx.keep, ir.tpl.holeCtx.set, '_hc')}; const holeAst = interp(); _ctx = _hc;` : 'const holeAst = interp();'} if (holeAst === null) { _shapeTplRestore(saveSnap); return null; } kids.push(holeAst); const next = peek(); @@ -3092,13 +3080,11 @@ function _shapeTxn(kids: unknown[], altPath: number[], body: () => boolean): boo const sp = pos; const kk = kids.length; const ak = altPath.length; - const sn = _suppressNext; const cap = _capped; if (body()) return true; pos = sp; kids.length = kk; altPath.length = ak; - _suppressNext = sn; _capped = cap; return false; } @@ -3107,13 +3093,11 @@ function _shapeProbe(kids: unknown[], altPath: number[], body: () => boolean): b const sp = pos; const kk = kids.length; const ak = altPath.length; - const sn = _suppressNext; const cap = _capped; const ok = body(); pos = sp; kids.length = kk; altPath.length = ak; - _suppressNext = sn; _capped = cap; return ok; } @@ -3509,13 +3493,13 @@ function ahead(k: number, is: boolean): boolean { // Whether the next token is a word the context in force reserves (ParserIR.ctxWords): with the // \`ahead\` test of the guard's own set, an \`aheadCtx\` test. Outside every context it reads nothing. function ctxWord(): boolean { - if ((_ctx & ${CTX_WORD_BITS}) === 0) return false; + if ((_ctx & ${ctxWordBits(ir)}) === 0) return false; const t = peek(); return t !== null && inCtxWords(t); } // Whether t is a word the context in force reserves (a guard's lead test reads the buffered token). function inCtxWords(t: Tok): boolean { - return (_ctx & ${CTX_WORD_BITS}) !== 0 && (false${ctxWordLids(ir, ids).map((w) => ` || ((_ctx & ${w.bit}) !== 0 && t.lid === ${w.lid})`).join('')}); + return (_ctx & ${ctxWordBits(ir)}) !== 0 && (false${ctxWordLids(ir, ids).map((w) => ` || ((_ctx & ${w.bit}) !== 0 && t.lid === ${w.lid})`).join('')}); } // Whether the token after the current one is in set k (a longest-match candidate's SECOND guard). function secondIn(k: number): boolean { @@ -3554,12 +3538,9 @@ let _form = 0; // assignment-target form of the node the last _nud/_bp call re ${ir.assignTargets ? targetRuntimeTs(ir.assignTargets) : ''}let _tail = false; // whether the node the last _nud call returned closes the access tail // A NUD that matched nothing, from its commit switch: the state its frame leaves then. function nudNone(): boolean { _capped = false; _form = 0; _tail = false; return false; } -// Indices into the grammar's suppress sets (ParserIR.suppressSets; 0 = none): the set a \`suppress\` -// step stages for the next Pratt call, and the set in force in the current one. -let _suppressNext = 0; -let _suppressCur = 0; -// The [Await]/[Yield] context word in force (ParserIR's Ctx: bit 1 await, bit 2 yield). A \`ctx\` step -// sets it for its body and puts back what it found, so outside every such body it is 0. +// The context word in force (parser-ir.ts's context word: a bit per context parameter, set where it differs from +// its entry value). A \`ctx\` step sets it for its body and puts back what it found, so outside +// every such body it is 0. let _ctx = 0; let _src = ''; function peek(): Tok | null { peekEnd = pos + 1; return pos < toks.length ? toks[pos] : null; } @@ -3641,6 +3622,7 @@ function enTok(k: number): boolean { return matchTokW(k); } function enAhead(set: number, is: boolean): boolean { return ahead(set, is); } function enCtxWord(): boolean { return ctxWord(); } function enWhen(mask: number, val: number): boolean { return (_ctx & mask) === val; } +function enCtxSet(keep: number, set: number): void { _ctx = (_ctx & keep) | set; } function enSecondIn(set: number): boolean { return secondIn(set); } function enLook(id: number): boolean { ${disp('id', nc.look, (i) => `look${i}`, (f) => `${f}()`)} @@ -3683,8 +3665,8 @@ function enLeafOpN(): void { opLeafW(peek()!, _ropLid); pos += _opN; } function enLeafOp(): void { leafSlotW('$operator', peek()!); pos++; } function enLeafKid(): void { const t = peek()!; leafSlotW(tok_kind(t), t); pos++; } function enHeadLid(sb: number): number { return sb < _n ? lid_of(headLeafTextW(sb)) : 0; } -function enSt(k: number): number { return k === ${ST_CAPPED} ? (_capped ? 1 : 0) : k === ${ST_FORM} ? _form : k === ${ST_TAIL} ? (_tail ? 1 : 0) : k === ${ST_SUP_NEXT} ? _suppressNext : k === ${ST_SUP_CUR} ? _suppressCur : _ctx; } -function enSetSt(k: number, v: number): void { if (k === ${ST_CAPPED}) _capped = v !== 0; else if (k === ${ST_FORM}) _form = v; else if (k === ${ST_TAIL}) _tail = v !== 0; else if (k === ${ST_SUP_NEXT}) _suppressNext = v; else if (k === ${ST_SUP_CUR}) _suppressCur = v; else _ctx = v; } +function enSt(k: number): number { return k === ${ST_CAPPED} ? (_capped ? 1 : 0) : k === ${ST_FORM} ? _form : k === ${ST_TAIL} ? (_tail ? 1 : 0) : _ctx; } +function enSetSt(k: number, v: number): void { if (k === ${ST_CAPPED}) _capped = v !== 0; else if (k === ${ST_FORM}) _form = v; else if (k === ${ST_TAIL}) _tail = v !== 0; else _ctx = v; } function enTick(): void { _rsteps++; } ${hasRebind(ir) ? '// The re-bind\'s capped operand, interpreted (rebind-family.ts; the marks are the native forms\'): the cap is `toks` sliced for the call.\nfunction riRbCapped(led: number, i: number, d: number): boolean { const full = toks; toks = full.slice(0, i); const ok = riRbStep(led, 1, d); toks = full; return ok; }\n' : ''}/** * parseInterpreted: the strict interpreter of the parse plan (the recovery family) from the entry @@ -3770,7 +3752,7 @@ export function parseTotal(src: string, builder: Builder): { root: H | nul lookReset(); _builder = builder; _n = 0; - _capped = false; _form = 0; _tail = false; _suppressNext = 0; _suppressCur = 0; _ctx = 0; + _capped = false; _form = 0; _tail = false; _ctx = 0; _rmarks = []; _rmFresh(); _rsteps = 0; diff --git a/test/fixtures/lookrec.ts b/test/fixtures/lookrec.ts index e3fbcd8d..514ba561 100644 --- a/test/fixtures/lookrec.ts +++ b/test/fixtures/lookrec.ts @@ -10,13 +10,13 @@ // • a lookahead that reaches a Pratt rule (`go`: `not([Expr, '='])`), directly or through an rd // rule (`at`: `Wrap` calls `Expr`), runs the Pratt rule's building form and drops the node, // undoing what it built along with the position. -// • a `suppress` step inside a lookahead (`in`: `exclude('in', Expr)`) disables its connector (the -// led `[$, 'in', $]`) there as it does anywhere: `in a in b;` is refused because the lookahead's `Expr` stops +// • a `ctx` step inside a lookahead (`in`: `ctx({ in: false }, Expr)`) clears the parameter its +// led `[$, 'in', $]` is gated on there as it does anywhere: `in a in b;` is refused because the lookahead's `Expr` stops // before the second `in`. // • a left-recursive rule whose continuations end in a POSITIVE lookahead (`Target`, Python's // t_primary: `&t_lookahead`) asserts that a trailer follows, so the tail stays open: `set a.b.c[1] = x;` // (only a trailing negative lookahead closes it: interpreter.ts negativeLook). -import { token, rule, defineGrammar, left, op, seq, oneOf, range, star, many, opt, not, exclude, alt } from '../../src/api.ts'; +import { token, rule, defineGrammar, left, op, seq, oneOf, range, star, many, opt, not, ctx, alt } from '../../src/api.ts'; const idStart = oneOf(range('a', 'z'), range('A', 'Z'), '_'); const idCont = oneOf(range('a', 'z'), range('A', 'Z'), range('0', '9'), '_'); @@ -26,7 +26,7 @@ const Number_ = token(seq(range('0', '9'), star(range('0', '9'))), { scope: 'con const Expr = rule(($) => [ Ident, Number_, - ['(', $, ')'], + ['(', ctx({ in: true }, $), ')'], [$, op, $], [$, 'in', $], ]); @@ -54,7 +54,7 @@ const Stmt = rule(() => [ ['go', not([Expr, '=']), Expr, ';'], ['go', Expr, '=', Expr, ';'], ['at', not(not([Wrap, '!'])), Wrap, '!', ';'], - ['in', not(not([exclude('in', Expr), ';'])), Expr, ';'], + ['in', not(not([ctx({ in: false }, Expr), ';'])), Expr, ';'], ['set', Target, alt(['.', Ident], ['[', Number_, ']']), not(trailer), '=', Expr, ';'], ]); const Program = rule(() => [many(Stmt)]); @@ -64,5 +64,7 @@ export default defineGrammar({ scopeName: 'source.lookrec', tokens: { Ident, Number: Number_ }, prec: [left('+', '-')], + params: { in: true }, + ledPrec: [{ connector: 'in', when: '+in' }], rules: { Expr, Head, Only, Wrap, Target, Stmt, Program }, }); diff --git a/test/fixtures/noinjs.ts b/test/fixtures/noinjs.ts index 14a39c03..8ba87bd2 100644 --- a/test/fixtures/noinjs.ts +++ b/test/fixtures/noinjs.ts @@ -1,9 +1,9 @@ -// Exercises the no-`in` (suppress) context. In a `for (binding in iterable)` head, the -// binding is parsed with the `in` LED DISABLED — `exclude('in', Expr)` — so the `in` belongs -// to the for-head, not to a relational expression inside the binding. Outside a for-head, `in` -// binds normally. The portable parser threads a suppressed-connector set into the led loop. +// Exercises the [In] context parameter. In a `for (binding in iterable)` head, the binding is +// parsed with `in` cleared — `ctx({ in: false }, Expr)` — so its gated `in` led is not read +// and the `in` belongs to the for-head, not to a relational expression inside the binding. +// Outside a for-head, and inside brackets (which set `in` again), `in` binds normally. import { - token, rule, defineGrammar, left, op, exclude, + token, rule, defineGrammar, left, op, ctx, seq, oneOf, range, star, many, opt, } from '../../src/api.ts'; @@ -16,16 +16,16 @@ const jsPrec = [left('||'), left('<', '>'), left('+', '-')]; const Expr = rule(($) => [ Number_, Ident, - ['(', $, ')'], + ['(', ctx({ in: true }, $), ')'], [$, op, $], [$, 'in', $], [$, '.', Ident], ]); -// The C-style head stages the suppress set for an init that may be absent: when the init never -// starts (`for (; a in b)`), the staging ends with its group, so the test after `;` reads `in`. +// The C-style head clears `in` for an init that may be absent: when the init never starts +// (`for (; a in b)`), the word is put back with its group, so the test after `;` reads `in`. const ForHead = rule(() => [ - ['for', '(', exclude('in', Expr), 'in', Expr, ')', Stmt], - ['for', '(', opt(exclude('in', Expr)), ';', opt(Expr), ')', Stmt], + ['for', '(', ctx({ in: false }, Expr), 'in', Expr, ')', Stmt], + ['for', '(', opt(ctx({ in: false }, Expr)), ';', opt(Expr), ')', Stmt], ]); const Stmt = rule(() => [ForHead, [Expr, ';']]); const Program = rule(() => [many(Stmt)]); @@ -35,6 +35,7 @@ export default defineGrammar({ scopeName: 'source.noinjs', tokens: { Ident, Number: Number_ }, prec: jsPrec, - ledPrec: [{ connector: 'in', sameAs: '<', chainRhs: true }], + params: { in: true }, + ledPrec: [{ connector: 'in', sameAs: '<', chainRhs: true, when: '+in' }], rules: { Expr, ForHead, Stmt, Program }, }); diff --git a/test/fixtures/shape-toy.ts b/test/fixtures/shape-toy.ts index 4834d051..f7f4bc07 100644 --- a/test/fixtures/shape-toy.ts +++ b/test/fixtures/shape-toy.ts @@ -6,7 +6,7 @@ */ import { token, rule, defineGrammar, left, right, prefix, postfix, op, - seq, oneOf, range, star, many, opt, sep, not, alt, sameLine, exclude, + seq, oneOf, range, star, many, opt, sep, not, alt, sameLine, ctx, capExpr, notLeftLeaf, } from '../../src/api.ts'; import type { ShapeSpec } from '../../src/shape/v1/shape-schema.ts'; @@ -67,9 +67,9 @@ const LinePair = rule(() => [ ['line', Ident, sameLine, Ident], ]); -/** suppress: parse Expr with '*' disabled at its top-level LED loop. */ +/** ctx: parse Expr with the context parameter `tern` cleared, so its gated `?` led is not read. */ const Suppressed = rule(() => [ - ['noplus', exclude('*', Expr)], + ['noplus', ctx({ tern: false }, Expr)], ]); const Repeated = rule(() => [ @@ -115,7 +115,8 @@ export const toyGrammar = defineGrammar({ left(prefix('-')), left(postfix('++')), ], - ledPrec: [{ connector: '?', below: '=' }], + params: { tern: true }, + ledPrec: [{ connector: '?', below: '=', when: '+tern' }], rules: { Atom, Bang, Expr, Tagged, Guarded, Transaction, LinePair, Suppressed, Repeated, OptionalRepeated, Separated, NotAny, Item, Program, @@ -628,8 +629,8 @@ export function buildToyCorpus(seed = 0x5a2_2026): { src: string; source: string } if (r < .50) return `txn ${pick(ids)}${rng() < .6 ? `:${pick(ids)}` : ''}${pick(['!', '.', '?'])}`; if (r < .58) return `line ${pick(ids)} ${pick(ids)}`; - // SH3-1b: suppress only disables literal LEDs — binary `*`/`/` must still parse - // under exclude('*', Expr). Mix ops + grouping so the arm is not `+`-only. + // SH3-1b: the context gates only the `?` led — binary `*`/`/` must still parse + // under ctx({ tern: false }, Expr). Mix ops + grouping so the arm is not `+`-only. if (r < .66) { const op = pick(['+', '-', '*', '/', '+', '*']); const form = rng(); @@ -698,11 +699,11 @@ export function buildToyCorpus(seed = 0x5a2_2026): { src: string; source: string 'tag x:;', 'tag x=;', 'guard bad;', 'guard good;', 'guard good:a;', 'args();', 'args(1,);', 'args(1,2);', 'f();', 'f(1,);', 'f(1)(2);', '1+2*3;', '-x(1);', 'tag t:f(1,2); bang !!7;', - // SH2-1: nested alt/altlit, sameLine, suppress, star(alt), opt(star), sep(alt), not(alt) + // SH2-1: nested alt/altlit, sameLine, ctx, star(alt), opt(star), sep(alt), not(alt) 'txn a:b?;', 'txn a:b!;', 'txn a.;', 'line a b;', 'line a\nb;', 'noplus 1+2;', 'repeat a 1 b 2;', 'maybe;', 'maybe a 1;', 'pairs();', 'pairs(a:1,2,b:3,);', 'notany good;', 'notany bad;', - // SH3-1b: suppress must not block prec-binary `*` (LED-only exclude) + // SH3-1b: the context gates only the `?` led, not a prec-binary operator 'noplus 1 * 2;', 'noplus 1 * 2 * 3;', 'noplus (1*2);', 'noplus 1*2;', 'noplus 1/2;', 'noplus 1*2+3;', 'noplus (1*2)*3;', 'noplus 1*(2*3);', // SH3-1b: well-formed sep+alt diff --git a/test/grammar-names-transparent.ts b/test/grammar-names-transparent.ts index edc15999..af0f2919 100644 --- a/test/grammar-names-transparent.ts +++ b/test/grammar-names-transparent.ts @@ -89,7 +89,7 @@ const stepFields = (steps: readonly Step[]): string[] => steps.flatMap((s): stri switch (s.t) { case 'star': return [...own, ...stepFields([s.step])]; case 'sep': return [...own, ...stepFields([s.elem])]; - case 'opt': case 'seq': case 'suppress': case 'ctx': return [...own, ...stepFields(s.steps)]; + case 'opt': case 'seq': case 'ctx': return [...own, ...stepFields(s.steps)]; case 'alt': return [...own, ...s.branches.flatMap(stepFields)]; default: return own; } diff --git a/test/guard-lead.ts b/test/guard-lead.ts index 431cdabd..abdff30b 100644 --- a/test/guard-lead.ts +++ b/test/guard-lead.ts @@ -60,7 +60,7 @@ for (const path of paths) { for (let ctx = 0; ctx < 4; ctx++) for (let lid = 0; lid < ids.lids.length; lid++) for (let kid = 0; kid < ids.kids.length; kid++) { checks++; const want = taken.every((s) => stepOk(s, lid, kid, ctx)); - const got = g.lead.every((l) => ((inSet(l.set, lid, kid) || (l.ctx && ctxWord(ctx, lid))) === l.is)); + const got = g.lead.every((l) => ((inSet(l.set, lid, kid) || (l.ctx !== 0 && ctxWord(ctx, lid))) === l.is)); // A lead test may refuse MORE than the steps it took over (a refusal by the complement of the // candidate's FIRST: test/guard-refutation.ts proves those); it must never admit what they refuse. if (got && !want) { fail(`${where}: token (lid ${JSON.stringify(ids.lids[lid])}, kind ${JSON.stringify(ids.kids[kid])}) in context ${ctx}: steps ${want}, lead ${got}`); return; } diff --git a/test/ir-engine.ts b/test/ir-engine.ts index 12058f6f..1e5ffefc 100644 --- a/test/ir-engine.ts +++ b/test/ir-engine.ts @@ -41,7 +41,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { const setLid = ir.tokenSets.map((s) => { const a = new Uint8Array(ids.lids.length); for (const l of s.lits) { const i = ids.lids.indexOf(l); if (i <= 0) throw new Error('lit ' + l); a[i] = 1; } return a; }); const setKid = ir.tokenSets.map((s) => { const a = new Uint8Array(ids.kids.length); for (const k of s.toks) { const i = ids.kids.indexOf(k); if (i <= 0) throw new Error('kid ' + k); a[i] = 1; } return a; }); const inSet = (k: number, t: Tok) => setLid[k]![t.lid] === 1 || setKid[k]![t.kid] === 1; - const ctxWordLids = ir.ctxWords.map((w, i) => ({ bit: 1 << i, lid: lidOf(w) })); + const ctxWordLids = ir.ctxWords.flatMap((w, i) => (w === undefined ? [] : [{ bit: 1 << i, lid: lidOf(w) }])); const firstCond = (f: NonNullable, t: Tok) => f.lits.some((l) => t.lid === lidOf(l)) || f.toks.some((k) => t.kid === kidOf(k)); const ruleByName = new Map(ir.rules.map((r) => [r.name, r])); const ruleId = (name: string) => ar.ruleNames.indexOf(name); @@ -49,7 +49,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { // ── parser state ── let toks: Tok[] = []; - let pos = 0, capped = false, form = 0, tail = false, suppressNext = 0, suppressCur = 0, ctx = 0; + let pos = 0, capped = false, form = 0, tail = false, ctx = 0; // children under construction (a node handle >= 0, a leaf < 0) and the built nodes const scratch: number[] = []; type NodeRec = { rule: number; kids: number[] }; @@ -124,15 +124,15 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { const ahead = (k: number, is: boolean): boolean => { const t = peek(); return t !== null ? inSet(k, t) === is : !is; }; // A prefix operator at lid; a gated one (`await`: its `when`) only where the context word passes. const preAt = (r: PrattRule, lid: number) => { const p = pre.get(r)!.get(lid); return p !== undefined && p.when !== undefined && (ctx & p.when.mask) !== p.when.val ? undefined : p; }; - const ctxWordT = (t: Tok) => (ctx & 3) !== 0 && ctxWordLids.some((w) => (ctx & w.bit) !== 0 && t.lid === w.lid); + const ctxWordT = (t: Tok) => ctxWordLids.some((w) => (ctx & w.bit) !== 0 && t.lid === w.lid); const ctxWord = () => { const t = peek(); return t !== null && ctxWordT(t); }; const callRule = (x: Sp | null): boolean => { if (x === null) return false; scratch.push(x.h); return true; }; const guardSteps = (g: Guard, steps: Step[]): Step[] => steps.slice(g?.skip ?? 0); // ── checks ── // The state a refused attempt starts from and must leave untouched. - const saveState = () => ({ pos, sb: scratch.length, ck: checkpoint(), ctx, capped, form, tail, suppressNext, suppressCur }); - const putState = (s: ReturnType) => { pos = s.pos; scratch.length = s.sb; restore(s.ck); ctx = s.ctx; capped = s.capped; form = s.form; tail = s.tail; suppressNext = s.suppressNext; suppressCur = s.suppressCur; }; + const saveState = () => ({ pos, sb: scratch.length, ck: checkpoint(), ctx, capped, form, tail }); + const putState = (s: ReturnType) => { pos = s.pos; scratch.length = s.sb; restore(s.ck); ctx = s.ctx; capped = s.capped; form = s.form; tail = s.tail; }; // Attempt `body` from here as if unrefused; the position it ends at, or -1 when it fails. The // parser's state is put back after. function attempt(body: () => boolean): number { @@ -145,10 +145,10 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { const bad = (msg: string) => { if (unsound.length < 20) unsound.push(msg); else unsound.length = 20; }; // ── elided marks ── // The state a body that fails clean must leave as it found it: what a mark puts back (position, - // scratch list, nodes) and the context and suppress sets (their steps put them back on either + // scratch list, nodes) and the context word (its steps put them back on either // outcome). capped / form / tail are not in it: they describe the last Pratt call's node, are // read only right after a call that matched, and no mark puts them back. - const stateKey = () => `${pos},${scratch.length},${nodes.length},${ctx},${suppressNext},${suppressCur}`; + const stateKey = () => `${pos},${scratch.length},${nodes.length},${ctx}`; // The step after each step of every step list (what follows a repetition, which may doom its body). const nextOf = new Map>(); { @@ -160,7 +160,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { const walk = (l: Step[]): void => l.forEach((s, k) => { const a = nextOf.get(s); if (a) a.push(l[k + 1]); else nextOf.set(s, [l[k + 1]]); if (s.t === 'star') walk([s.step]); else if (s.t === 'sep') walk([s.elem]); - else if (s.t === 'opt' || s.t === 'seq' || s.t === 'suppress' || s.t === 'ctx') walk(s.steps); + else if (s.t === 'opt' || s.t === 'seq' || s.t === 'ctx') walk(s.steps); else if (s.t === 'alt') s.branches.forEach(walk); }); lists.forEach(walk); @@ -204,8 +204,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { case 'seq': return all(s.steps, r); case 'sameLine': { const t = peek(); return t !== null && !t.nl; } case 'when': return (ctx & s.mask) === s.val; - case 'suppress': { suppressNext = s.set; const ok = all(s.steps, r); suppressNext = 0; return ok; } - case 'ctx': { const c0 = ctx; ctx = s.ctx; const ok = all(s.steps, r); ctx = c0; return ok; } + case 'ctx': { const c0 = ctx; ctx = (ctx & s.keep) | s.set; const ok = all(s.steps, r); ctx = c0; return ok; } // Not modelled (no grammar this engine runs declares a target context): say so, not a silent reject. case 'assignTarget': throw new Error(`ir-engine: the declared assignment-target check (${s.ctx}) is not modelled`); } @@ -221,10 +220,10 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { }; // `f` runs under a mark that saves the position and the scratch list only (MarkForm 'leaves'): // failing, it must have left everything else as it found it, the builder's nodes above all - // (what the full mark's checkpoint would have dropped), and the context and suppress sets. + // (what the full mark's checkpoint would have dropped), and the context word. function leavesOnly(st: Step, f: () => boolean): boolean { if (checking) return f(); - const key = () => `${nodes.length},${ctx},${suppressNext},${suppressCur}`; + const key = () => `${nodes.length},${ctx}`; const k0 = key(), n0 = nodes.length, p0 = pos, s0 = stateKey(); const ok = f(); if (ok) return true; @@ -340,7 +339,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { if (mut?.guard === g && t !== null && t.lid === mut.lid && pos === mut.pos) return false; if (!keyed && g.first) { if (t === null || !inSet(g.first.id, t)) return false; } if (g.second !== null) { const i = pos + 1; if (!(i < toks.length && inSet(g.second.id, toks[i]!))) return false; } - for (const l of g.lead) { if (t === null) return false; const x = inSet(l.set, t) || (l.ctx && ctxWordT(t)); if (x !== l.is) return false; } + for (const l of g.lead) { if (t === null) return false; const x = inSet(l.set, t) || (l.ctx !== 0 && ctxWordT(t)); if (x !== l.is) return false; } for (const x of g.pairs ?? []) if (!pairOk(x, t, g)) return false; return true; }; @@ -388,7 +387,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { if (x.all) return guardOk(g, t, false); if (x.first && !inSet(g.first!.id, t)) return false; if (g.second !== null) { const i = pos + 1; if (!(i < toks.length && inSet(g.second.id, toks[i]!))) return false; } - for (const k of x.lead) { const l = g.lead[k]!; const v = inSet(l.set, t) || (l.ctx && ctxWordT(t)); if (v !== l.is) return false; } + for (const k of x.lead) { const l = g.lead[k]!; const v = inSet(l.set, t) || (l.ctx !== 0 && ctxWordT(t)); if (v !== l.is) return false; } for (const k of x.pairs ?? []) if (!pairOk(g.pairs![k]!, t, g)) return false; return true; }; @@ -508,10 +507,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { postfixKids.set(r, new Set(r.postfixToks.map(kidOf))); } function parsePratt(r: PrattRule): Sp | null { - const prev = suppressCur; suppressCur = suppressNext; suppressNext = 0; - const x = prattBp(r, 0); - suppressCur = prev; - return x; + return prattBp(r, 0); } function matchTemplate(hole: string): Sp | null { const t = peek(); @@ -577,7 +573,8 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { if (r.ledSameLine[i] && t.nl) continue; const nl = r.ledNotLeftLeaf[i]; if (nl && nl.includes(headLeafText(src, left.h))) continue; - if (r.ledSuppressedIn[i]!.includes(suppressCur)) continue; + const gate = r.ledWhen[i]; + if (gate && (ctx & gate.mask) !== gate.val) continue; const ledSave = pos, sb = scratch.length, ck = checkpoint(); scratch.push(left.h); // A clean led arm (PrattRule.ledClean) takes no builder checkpoint: failing, it must have built no node. @@ -792,7 +789,7 @@ export function engine(ir: ParserIR, mut: Mutation = null, obs: Observer = {}) { // `entry`: the rule the run parses the whole input as (the grammar's entry by default). return function run(tokens: Tok[], text: string, entry: string = ir.entry): Outcome { toks = tokens; src = text; - pos = 0; capped = false; form = 0; tail = false; suppressNext = 0; suppressCur = 0; ctx = 0; + pos = 0; capped = false; form = 0; tail = false; ctx = 0; scratch.length = 0; nodes.length = 0; opEnd.clear(); checking = base; checked = 0; cleanChecked = 0; leavesChecked = 0; unsound = []; found = {}; const root = parseRule(entry); const accept = root !== null && pos === toks.length; diff --git a/test/portable-cases.ts b/test/portable-cases.ts index 1044ae95..77e8909f 100644 --- a/test/portable-cases.ts +++ b/test/portable-cases.ts @@ -17,10 +17,10 @@ import { CTX_CASES } from './context-cases.ts'; // `parts`: the module's `textDialect(parts)` builds the grammar (a stage of the text dialect) // instead of its default export. export type Case = { grammar: string; path: string; parts?: Record; accept: string[]; reject: string[]; tsOnly?: boolean }; -// A for-head's no-`in` region (`exclude('in', Expr)`, a `suppress` step): it holds for the Pratt call -// it wraps, a nested call (parentheses, arguments, an object, array or template, a function or arrow -// block body) has `in` again, and every alternative of the head that fails inside or after it backs -// out of it. Each verdict is tsc's parser's too. +// A for-head's no-`in` region (`ctx({ in: false }, Expr)`, the [~In] parameter): it holds for what +// the expression reaches but brackets (parentheses, arguments, an object, array or template, a +// function or arrow block body), which set `in` again, and every alternative of the head that fails +// inside or after it backs out of it. Each verdict is tsc's parser's too. // Cap propagation (the interpreter's, interpreter.ts): an ArrowFunction is an AssignmentExpression, // so it admits no operator after it, and an operator whose right operand is an arrow admits none // either (`x = () => {} || a` is no derivation); a parenthesized or nested arrow (an argument, an @@ -71,6 +71,21 @@ const NO_IN_HEADS = { 'for (let [a = b in c] of d);', 'for (var a = { b: c in d } in e);', 'for (var a = `${b in c}` in d);', 'for (x = (() => a in b);;);', 'for (x = (a in b) in c in d);', ], + // A for-in left side that is no LeftHandSideExpression (14.7.5: `for ( LeftHandSideExpression in + // Expression )`): no derivation in JavaScript, which reads `accept` without them and rejects them; + // tsc's parser reads any expression there (its checker reports it), so TypeScript's grammar, whose + // oracle that parser is, accepts them. + nonLhsLeft: [ + 'for (a = (b in c) in d);', 'for (x = (y = (a in b)) in c);', + 'for (x = () => { a in b; } in c);', 'for (x = function () { return a in b; } in c);', + 'for (x = () => { for (a in b); } in c);', 'for (x = (a in b) in c in d);', + ], + // The same brackets, in a left side that is one (JavaScript). + jsLhsLeft: [ + 'for (x[() => { a in b; }] in c);', 'for (x[function () { return a in b; }] in c);', + 'for (x[(a in b)].y in c);', 'for (x[`${a in b}`] of c);', + ], + jsNonLhsLeft: ['for (a = x in b) c;', 'for (a = x + y in b) c;', 'for (a + b in x);', 'for (a = b ? x in c : y in d) e;', 'for (a ? b : c in d);', 'for (x => x in y);'], reject: ['for (var a = b in c;;);', 'for (var a = b in c in d;;);', 'for (var a = b, c = d in e;;);'], }; // The restrictions of a `for` head (14.7.4, 14.7.5), the same in both grammars: the C-style head's @@ -659,16 +674,14 @@ export const CASES: Case[] = [ 'function f() { return /re/.test(x); }', 'x = typeof /re/;', 'switch (a) { case /re/: break; }', 'x.y.z++;', '(a++).b;', 'a++ instanceof B;', 'a++\n(x);', 'for (a in b) c;', - 'for (a = x in b) c;', 'for (a in b) { d = c in e; }', 'new a.b();', '((((x))));', - 'for (a = x + y in b) c;', - ...CAP_PROPAGATION.accept, ...NO_IN_HEADS.accept, ...FOR_HEADS.accept, ...RESERVED_EXPRS.accept, ...CALL_ARGS.accept, ...EXPORT_DECLS.accept, + ...CAP_PROPAGATION.accept, ...NO_IN_HEADS.accept.filter((c) => !NO_IN_HEADS.nonLhsLeft.includes(c)), ...NO_IN_HEADS.jsLhsLeft, ...FOR_HEADS.accept, ...RESERVED_EXPRS.accept, ...CALL_ARGS.accept, ...EXPORT_DECLS.accept, ...CTX_CASES.javascript.accept, ...JS_DECORATORS.accept, ...TEMPLATE_STEPS.js.accept, ...JS_MODULES.accept, ...TRY_STATEMENTS.accept, // An assignment / update operand needs only a LeftHandSideExpression's shape; target validity is a consumer's. '-x++;', '(a) = 1;', 'a = b = c;', '1 = 2;', '1++;', '++1;', 'f() = 1;', 'f()++;', '++f();', 'this = 1;', '(a + b) = c;', '(a, b) = 1;', 'a?.b = 1;', 'a?.b++;', '[a + b] = c;', '({a: 1} = c);', 'new.target = 1;', - 'for (1 of x);', 'for (a + b in x);', 'for (f() in x);', + 'for (1 of x);', 'for (f() in x);', // Postfix `++`/`--` is a restricted production (`LeftHandSideExpression [no LineTerminator // here] ++`): after a line break the operator is the prefix of the NEXT statement. 'x\n++\ny;', 'x\n--\ny;', 'x ++\n++\ny;', 'x\n++y\n--\nz;', 'a = b\n++c;', 'f()\n++\ny.z;', @@ -750,8 +763,7 @@ export const CASES: Case[] = [ 'function f() { return x\n++\n++\ny; }', 'f()\n++\n++\ny;', 'a[0]\n--\n--y;', '{ x\n++\n++\ny }', 'x\n++;', 'x\n--', '(x\n++);', 'a = [x\n++];', 'x\n++\n-y;', 'x\n++\ny++;', 'x\n++ ++y;', 'class C { p = x\n++ }', 'class C { p = x\n++\ny }', 'for (a = (x in b)) c;', - 'for (a = b ? x in c : y in d) e;', - 'new a?.b;', ...CAP_PROPAGATION.reject, ...NO_IN_HEADS.reject, ...FOR_HEADS.reject, ...RESERVED_EXPRS.reject, ...CALL_ARGS.reject, ...EXPORT_DECLS.reject, + 'new a?.b;', ...CAP_PROPAGATION.reject, ...NO_IN_HEADS.reject, ...NO_IN_HEADS.nonLhsLeft, ...NO_IN_HEADS.jsNonLhsLeft, ...FOR_HEADS.reject, ...RESERVED_EXPRS.reject, ...CALL_ARGS.reject, ...EXPORT_DECLS.reject, ...CTX_CASES.javascript.reject, ...TEMPLATE_STEPS.js.reject, // An assignment / update operand (prefix ++/-- included) without a LeftHandSideExpression's shape has no parse. 'a + b = c;', 'a++ = 1;', '-a = 1;', '++ -x;', '++x++;', '++ ++x;', diff --git a/test/portable-recovery.ts b/test/portable-recovery.ts index e5528eb4..fcfd8dfd 100644 --- a/test/portable-recovery.ts +++ b/test/portable-recovery.ts @@ -105,9 +105,11 @@ const FARTHEST_HINT = / \[farthest: offset (\d+) near [\s\S]*\]$/; // 'for (get of of x);' (`get => of => of => x in x`): the same class, an arrow body taking the `in`. // land/recovery-guard-1 (an rd rule no candidate matched may follow an extra token): typescript's // 'for (x = () => { for (accessor a in b); } in c);' holds now (the extra `accessor` is skipped). +// land/contexts-3 ([In] a context parameter): an arrow body keeps the head's [~In] +// (ConciseBody[?In]), so it no longer takes the `in`: every entry of both grammars holds. const P10_GREEDY_CAPTURE: Record = { - javascript: ['for (async of x);', 'for (async of => 1 of x);', 'for (of of as y);'], - typescript: ['for (of y);', 'for ( of x);', 'for (async of x);', 'for (async of => 1 of x);', 'for (x = (y = (a in b)) constructor c);', 'for (get of of x);'], + javascript: [], + typescript: [], }; // LOOKAHEAD BYPASS: a lookahead passed on the real tokens, and a repair then supplied a token among // the tokens it read, so the substituted text is not the one it judged. `class C { default class) diff --git a/test/predictive-first.ts b/test/predictive-first.ts index a507c90a..0307a3ec 100644 --- a/test/predictive-first.ts +++ b/test/predictive-first.ts @@ -56,7 +56,7 @@ for (const path of paths) { const walkLits = (steps: Step[]): void => { for (const s of steps) { if (s.t === 'lit') lits.add(s.value); else if (s.t === 'altlit') s.opts.forEach((o) => lits.add(o.value)); else if (s.t === 'sep') { lits.add(s.delim); walkLits([s.elem]); } else if (s.t === 'star') walkLits([s.step]); - else if (s.t === 'opt' || s.t === 'seq' || s.t === 'ctx' || s.t === 'suppress') walkLits(s.steps); else if (s.t === 'alt') s.branches.forEach(walkLits); + else if (s.t === 'opt' || s.t === 'seq' || s.t === 'ctx') walkLits(s.steps); else if (s.t === 'alt') s.branches.forEach(walkLits); } }; for (const r of ir.rules) { if (r.kind === 'rd') r.alts.forEach(walkLits); @@ -106,7 +106,7 @@ for (const path of paths) { case 'opt': return { syms: seqF(s.steps).syms, empty: true }; case 'sep': return { syms: stepF(s.elem).syms, empty: true }; case 'alt': return union(s.branches.map(seqF)); - case 'seq': case 'ctx': case 'suppress': return seqF(s.steps); + case 'seq': case 'ctx': return seqF(s.steps); case 'look': case 'ahead': case 'aheadCtx': case 'sameLine': case 'when': case 'assignTarget': return { syms: new Set(), empty: true }; } }; @@ -157,7 +157,7 @@ for (const path of paths) { if (s.t === 'star') checkBody(at, [s.step], s.guard); else if (s.t === 'sep') checkBody(at, [s.elem], s.guard); else if (s.t === 'opt') checkBody(at, s.steps, s.guard); if (s.t === 'alt') { if (s.predictive) check(`${at} (alt)`, s.branches, s.firsts ?? []); s.branches.forEach((b, j) => walk(`${at}|${j}`, b)); } else if (s.t === 'star') walk(at, [s.step]); else if (s.t === 'sep') walk(at, [s.elem]); - else if (s.t === 'opt' || s.t === 'seq' || s.t === 'ctx' || s.t === 'suppress') walk(at, s.steps); + else if (s.t === 'opt' || s.t === 'seq' || s.t === 'ctx') walk(at, s.steps); }); for (const r of ir.rules) { if (r.kind === 'rd') { diff --git a/test/shape-parity.ts b/test/shape-parity.ts index 1012f446..12e986d0 100644 --- a/test/shape-parity.ts +++ b/test/shape-parity.ts @@ -428,7 +428,7 @@ async function main(): Promise { const requiredRdKinds = [ 'lit', 'tok', 'rule', 'star', 'opt', 'sep', 'altlit', 'alt', - 'look', 'seq', 'sameLine', 'suppress', + 'look', 'seq', 'sameLine', 'ctx', ]; check( requiredRdKinds.every((k) => toyMod.shapeCoverage.step[k] > 0) @@ -1167,7 +1167,7 @@ async function main(): Promise { } - // ── SH3-1b: suppress is LED-only; prec-binary survives exclude('*', Expr) ─ + // ── SH3-1b: the context gates only the `?` led; prec-binary survives ctx({ tern: false }, Expr) ─ const sh31bNoplus = [ 'noplus 1 * 2;', 'noplus 1 * 2 * 3;', 'noplus (1*2);', 'noplus 1*2;', 'noplus 1/2;', 'noplus 1*2+3;', 'noplus (1*2)*3;', 'noplus 1*(2*3);', @@ -1175,7 +1175,7 @@ async function main(): Promise { for (const src of sh31bNoplus) { check( accepts(toyMod, src, false) && accepts(toyMod, src, true), - `SH3-1b suppress/binary accept ${JSON.stringify(src)}`, + `SH3-1b ctx/binary accept ${JSON.stringify(src)}`, ); } diff --git a/test/shape-rust.ts b/test/shape-rust.ts index 3d541998..b410ed61 100644 --- a/test/shape-rust.ts +++ b/test/shape-rust.ts @@ -535,7 +535,7 @@ async function main(): Promise { check('toy CST≡AST accept equivalence', toyAcceptDiv === 0, `${toyCorpus.length} cases, ${toyAcceptDiv} divergences`); check('toy TS↔Rust event types iso (corpus)', toyIsoBad === 0, `${toyIsoN} compared, ${toyIsoBad} divergences`); - // SH3-1b: suppress is LED-only — prec-binary under exclude('*') must accept + iso + // SH3-1b: the context gates only the `?` led — prec-binary under ctx({ tern: false }) must accept + iso const sh31bNoplus = [ 'noplus 1 * 2;', 'noplus 1 * 2 * 3;', 'noplus (1*2);', 'noplus 1*2;', 'noplus 1/2;', 'noplus 1*2+3;', 'noplus (1*2)*3;', 'noplus 1*(2*3);', diff --git a/test/template-holes.ts b/test/template-holes.ts index 78b92c80..aad57296 100644 --- a/test/template-holes.ts +++ b/test/template-holes.ts @@ -25,7 +25,7 @@ import { goTarget } from '../src/targets/target-go.ts'; import { generateTreeSitter } from '../src/editor/gen-tree-sitter.ts'; import { token, rule, defineGrammar, left, op, seq, oneOf, range, star, plus, many, - altPattern, noneOf, notFollowedBy, withHoles, awaitCtx, reservableNot, alt, + altPattern, noneOf, notFollowedBy, withHoles, ctx, when, not, alt, } from '../src/api.ts'; import type { Grammar, RuleExpr } from '../src/grammar/types.ts'; import { asGoMain } from './go-main.ts'; @@ -53,16 +53,16 @@ function fixture() { const Ty = rule(($) => [Ident, [$, '[', ']'], [$, '|', $], withHoles(Template, $)]); const Callee = rule(($) => [Ident, Template, [$, '.', Ident], [$, Template]]); const Ex = rule(($) => [ - // the keywords are not identifiers; inside an await context neither is `await` (the fork - // extends this guard), so `await` with no operand has no parse there - [reservableNot(alt('new', 'async', 'type')), Ident], + // the keywords are not identifiers; inside an await context neither is `await` (the guard's + // context word), so `await` with no operand has no parse there + [not(alt('new', 'async', 'type', when('+await', 'await'))), Ident], Num, Template, [$, op, $], [$, 'as', Ty], [$, Template], - ['new', Callee], ['async', '(', awaitCtx($), ')'], ['await', $], + ['new', Callee], ['async', '(', ctx({ await: true }, $), ')'], ['await', $], ]); const Stmt = rule(() => [['type', Ident, '=', Ty, ';'], [Ex, ';']]); const Program = rule(() => [[many(Stmt)]]); return defineGrammar({ - name: 'tplholes', tokens: { WS, Ident, Num, Template }, + name: 'tplholes', tokens: { WS, Ident, Num, Template }, params: { await: false }, prec: [left('+')], rules: { Ty, Callee, Ex, Stmt, Program }, entry: Program, expression: Ex, }); diff --git a/test/test262-record.txt b/test/test262-record.txt index aefdfd9f..8b7fd5d2 100644 --- a/test/test262-record.txt +++ b/test/test262-record.txt @@ -411,7 +411,6 @@ language/statements/for-of/head-const-init.js language/statements/for-of/head-let-init.js language/statements/for-of/head-using-init.js language/statements/for-of/head-var-init.js -annexB/language/statements/for-in/bare-initializer.js annexB/language/statements/for-in/const-initializer.js annexB/language/statements/for-in/let-initializer.js annexB/language/statements/for-in/strict-initializer.js @@ -426,10 +425,6 @@ language/expressions/coalesce/cannot-chain-head-with-logical-and.js language/expressions/coalesce/cannot-chain-head-with-logical-or.js language/expressions/coalesce/cannot-chain-tail-with-logical-and.js language/expressions/coalesce/cannot-chain-tail-with-logical-or.js -## accept/in-operator-in-for-init -language/expressions/conditional/in-branch-2.js -language/expressions/yield/in-iteration-stmt.js -language/expressions/yield/star-in-iteration-stmt.js ## accept/switch-statement-outside-clause language/statements/switch/S12.11_A3_T5.js ## accept/numeric-literal-lexical diff --git a/test/textmate-completeness.ts b/test/textmate-completeness.ts index 3c08cd7e..0251c684 100644 --- a/test/textmate-completeness.ts +++ b/test/textmate-completeness.ts @@ -37,8 +37,8 @@ // # ledger region (CI's artifact drift step checks it) // ───────────────────────────────────────────────────────────────────────────── import { - token, rule, defineGrammar, sep, opt, many, many1, alt, exclude, not, reservableNot, - treeSitterRelax, capExpr, awaitCtx, yieldCtx, asyncGenCtx, resetCtx, op, prefix, postfix, + token, rule, defineGrammar, sep, opt, many, many1, alt, not, + treeSitterRelax, capExpr, ctx, when, op, prefix, postfix, sameLine, noCommentBefore, noMultilineFlowBefore, notLeftLeaf, oneOf, noneOf, seq, altPattern, optPattern, star, plus, repeat, followedBy, notFollowedBy, precededBy, notPrecededBy, start, end, never, anyChar, range, none, left, @@ -106,12 +106,12 @@ function checkRuleExprClosure(): void { const Alt = rule(() => [alt(['p'], ['q', 'r'])]); // alt + seq const Sep = rule(() => [[sep(A, ','), ';']]); // sep const Group = rule(() => [[ // group (4 flavours) - exclude('in', A), // group.suppress - awaitCtx(A), yieldCtx(A), asyncGenCtx(A), resetCtx(A), // group.ctxMode + ctx({ p: true }, A), // group.ctx + when('+p', A), // group.when treeSitterRelax(A, B), // group.treeSitterRelaxed capExpr('||', A), // group.capBelow ]]); - const Nots = rule(() => [[not(A), reservableNot(['kw']), B]]); // not (+ reservable) + const Nots = rule(() => [[not(A), not(alt('kw', when('+p', 'kw2'))), B]]); // not (+ a context word) const Markers = rule(() => [[ // zero-width markers sameLine, noCommentBefore, noMultilineFlowBefore, notLeftLeaf('void', 'null'), A, ]]); @@ -121,7 +121,7 @@ function checkRuleExprClosure(): void { let threw = false; let g: Grammar; try { g = defineGrammar({ - name: 'closure', tokens: { A, B }, + name: 'closure', tokens: { A, B }, params: { p: false }, rules: { Leaf, Refs, Quant, Alt, Sep, Group, Nots, Markers, Pratt, Entry }, entry: Entry, }); } catch (e) { threw = true; g = null as any; } @@ -442,8 +442,8 @@ function checkCollectLiteralsClosure(): void { ['alt', { type: 'alt', items: [ref, lit] }, true], ['quantifier(*)', { type: 'quantifier', body: lit, kind: '*' }, true], ['group', { type: 'group', body: lit }, true], - ['group(suppress)', { type: 'group', body: lit, suppress: ['in'] }, true], - ['group(ctxMode)', { type: 'group', body: lit, ctxMode: 'await' }, true], + ['group(ctx)', { type: 'group', body: lit, ctx: { p: true } }, true], + ['group(when)', { type: 'group', body: lit, when: '+p' }, true], ['sep.element', { type: 'sep', element: lit, delimiter: ',' }, true], ['sep.delimiter', { type: 'sep', element: ref, delimiter: S }, true], ['not (non-consuming → omit)', { type: 'not', body: lit }, false], diff --git a/test/tree-sitter-record.txt b/test/tree-sitter-record.txt index 5b4f63d9..c4097273 100644 --- a/test/tree-sitter-record.txt +++ b/test/tree-sitter-record.txt @@ -64,7 +64,6 @@ javascript | test262 | rejects | import-attributes-not-rendered | test/language/ javascript | test262 | rejects | marker-wins-over-marker-free-reading | test/language/statements/await-using/syntax/await-using-declaring-let-split-across-two-lines.js javascript | test262 | rejects | marker-wins-over-marker-free-reading | test/language/statements/generators/yield-as-generator-declaration-binding-identifier.js javascript | test262 | rejects | non-ascii-whitespace-not-skipped | test/language/module-code/source-phase-import/import-source-newlines_FIXTURE.js -javascript | test262 | rejects | unclassified | test/annexB/language/statements/for-in/bare-initializer.js javascript | test262 | rejects | unclassified | test/annexB/language/statements/for-in/const-initializer.js javascript | test262 | rejects | unclassified | test/annexB/language/statements/for-in/let-initializer.js javascript | test262 | rejects | unclassified | test/annexB/language/statements/for-in/nonstrict-initializer.js @@ -192,7 +191,7 @@ javascript | test262 | rejects | unclassified | test/language/white-space/after- javascript | test262 | rejects | unclassified | test/language/white-space/after-regular-expression-literal-zwnbsp.js javascript | test262 | rejects | unclassified | test/language/white-space/between-nbsp.js javascript | test262 | spans | other | files 30 -javascript | test262 | spans | totals | span-equal 23199 of 23229, interpreter spans missing 14, extra tree-sitter spans 29 +javascript | test262 | spans | totals | span-equal 23196 of 23226, interpreter spans missing 14, extra tree-sitter spans 29 javascriptreact | line breaks | rejects | unclassified | "function f() { return\n/a/ }" javascriptreact | lookaheads | accepts | unclassified | "try {}" javascriptreact | lookaheads | accepts | unclassified | "x = () => {}.x;" diff --git a/typescript.ts b/typescript.ts index 3d516805..b2695795 100644 --- a/typescript.ts +++ b/typescript.ts @@ -2,7 +2,7 @@ import { rule, defineGrammar, op, prefix, postfix, sameLine, sep, opt, many, many1, alt, not, treeSitterRelax, capExpr, atLevel, notLeftLeaf, withHoles, - awaitCtx, yieldCtx, asyncGenCtx, resetCtx, arm, field, + arm, field, type Element, } from './src/api.ts'; @@ -14,10 +14,10 @@ import { // Param/Block/Type/TypeParams resolve at thunk-eval time (defined below). function tsFnArms(nameParts: Element[], body: Element) { return [ - arm('function_', 'function', ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(resetCtx(field('parameter', Param)), ','), ')', opt(":", ReturnType), resetCtx(field('body', body))), - arm('generator', 'function', field('asterisk', '*'), ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(yieldCtx(field('parameter', Param)), ','), ')', opt(":", ReturnType), yieldCtx(field('body', body))), - arm('asyncFunction', field('asyncKeyword', 'async'), sameLine, 'function', ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(awaitCtx(field('parameter', Param)), ','), ')', opt(":", ReturnType), awaitCtx(field('body', body))), - arm('asyncGenerator', field('asyncKeyword', 'async'), sameLine, 'function', field('asterisk', '*'), ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(asyncGenCtx(field('parameter', Param)), ','), ')', opt(":", ReturnType), asyncGenCtx(field('body', body))), + arm('function_', 'function', ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(fnCtx.plain(field('parameter', Param)), ','), ')', opt(":", ReturnType), fnCtx.plain(field('body', body))), + arm('generator', 'function', field('asterisk', '*'), ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(fnCtx.generator(field('parameter', Param)), ','), ')', opt(":", ReturnType), fnCtx.generator(field('body', body))), + arm('asyncFunction', field('asyncKeyword', 'async'), sameLine, 'function', ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(fnCtx.async(field('parameter', Param)), ','), ')', opt(":", ReturnType), fnCtx.async(field('body', body))), + arm('asyncGenerator', field('asyncKeyword', 'async'), sameLine, 'function', field('asterisk', '*'), ...nameParts, opt(field('typeParameters', TypeParams)), '(', sep(fnCtx.asyncGenerator(field('parameter', Param)), ','), ')', opt(":", ReturnType), fnCtx.asyncGenerator(field('body', body))), ]; } @@ -41,6 +41,7 @@ import { notReserved, notReservedExpr, bindingIdentifier, bindingName, asi, expressionStatement, conciseBody, classHeritageArms, newTargetArms, ecmaPrec, jsLedPrecs, jsScopes, jsBaseCanonical, forBindingArms, forHeadArms, forAwaitHeadArms, forStatement, memberStart, memberAhead, memberWordRules, memberWord, exportDeclaration, variableDeclaration, moduleSpecifier, bracketIndex, + jsParams, fnCtx, arrowBodyCtx, inCtx, noInCtx, } from './javascript.ts'; // ── Type query reference (typeof's argument: just dotted identifiers) ── @@ -65,20 +66,20 @@ const TypeofRef = rule($ => [ // `@dec[...]` (tsc rejects a real `@arr[0]` decorator). `many` so a whole chain is allowed. const DecoratorExpr = rule(() => [ // Not `@new`: `new` is a reserved word, so it names no decorator; `@new …` is the NewExpression arm below. - [alt([not('@new'), Decorator], ['@', alt([notReservedExpr, Ident], ['(', Expr, many(',', Expr), ')'])]), many(alt( - ['(', sep(Expr, ','), ')'], // call: (args) - [...typeArgsInExpr(), '(', sep(Expr, ','), ')'], // typed call: (args) + [alt([not('@new'), Decorator], ['@', alt([notReservedExpr, Ident], ['(', inCtx(Expr, many(',', Expr)), ')'])]), many(alt( + ['(', inCtx(sep(Expr, ',')), ')'], // call: (args) + [...typeArgsInExpr(), '(', inCtx(sep(Expr, ',')), ')'], // typed call: (args) '!', // non-null assertion ['.', alt(Ident, PrivateField)], // member access // optional chain: ?.y | ?.#y | ?.(args) | ?.[i] — unlike plain element access, // `?.[` is unambiguous (a computed class member never starts with `?.`), so tsc // parses it in decorator position and we mirror. - ['?.', alt(Ident, PrivateField, ['(', sep(Expr, ','), ')'], bracketIndex(Expr))], // `?.#y` is valid current ES (see Expr `?.` below) + ['?.', alt(Ident, PrivateField, ['(', inCtx(sep(Expr, ',')), ')'], bracketIndex(Expr))], // `?.#y` is valid current ES (see Expr `?.` below) Template, // tagged template: @x`…` ))], // `@new x`: the decorator expression is a NewExpression. The lexer reads `@new` as ONE Decorator // token (it cannot know `new` is reserved): the arm takes that token by its text, or `@` and `new`. - [alt('@new', ['@', 'new']), NewTarget, opt('(', sep(Expr, ','), ')')], + [alt('@new', ['@', 'new']), inCtx(NewTarget), opt('(', inCtx(sep(Expr, ',')), ')')], ]); // ── Types ── @@ -389,12 +390,12 @@ const Prop = rule(() => { const sig = (ctx: (...items: Element[]) => Element) => [opt(field('typeParameters', TypeParams)), '(', sep(ctx(field('parameter', Param)), ','), ')', opt(':', ReturnType), ctx(field('body', fnBodyOrAsi()))]; const marks = [opt(field('question', '?')), opt(field('exclamation', '!'))]; const members = (generator: (...items: Element[]) => Element, method: (...items: Element[]) => Element) => field('member', alt( - arm('accessor', field('kind', alt('get', 'set')), field('key', MemberName), ...sig(resetCtx)), + arm('accessor', field('kind', alt('get', 'set')), field('key', MemberName), ...sig(fnCtx.plain)), arm('generatorMethod', field('asterisk', '*'), field('key', MemberName), ...marks, ...sig(generator)), arm('named', field('key', MemberName), ...marks, field('tail', alt(arm('method', ...sig(method)), arm('init', ':', field('value', Expr))))), arm('shorthand', notReserved, field('name', Ident), ...marks, opt(field('equals', '='), field('value', Expr))), )); - const plain = members(yieldCtx, resetCtx), withAsync = members(asyncGenCtx, awaitCtx); + const plain = members(fnCtx.generator, fnCtx.plain), withAsync = members(fnCtx.asyncGenerator, fnCtx.async); // tsc reads one decorator run inside the modifier run, after a word (only `export` / `default` // may precede it: `modifierWord`'s `secondRun` followers), and a member never starts with one // (`@` begins no element of tsc's object literal list: `{ @d m() {} }` has no parse). The run is @@ -458,7 +459,7 @@ const ClassHeritage = rule($ => classHeritageArms($, Expr, NewTarget, const heritageFollowers = alt(',', '{', 'extends', 'implements'); // Named: each clause `heritage` (`extends_` / `implements`); its elements `element` (the first, in // the branch that starts with one) and `elementRest`; an element's expression `base`. -const heritageElement = alt([not(alt('extends', 'implements')), not(['{', '}', not(heritageFollowers)]), field('base', ClassHeritage)]); +const heritageElement = alt([not(alt('extends', 'implements')), not(['{', '}', not(heritageFollowers)]), inCtx(field('base', ClassHeritage))]); const heritageList = [treeSitterRelax(field('elements', alt( arm('list', not(alt(['{', not('}')], ['{', '}', heritageFollowers])), sep(field('elementRest', heritageElement), ',')), arm('first', field('element', heritageElement), opt(',', sep(field('elementRest', heritageElement), ','))), @@ -506,7 +507,7 @@ const Expr = rule($ => [ // `super = …` are all parse errors. Modeling super as a bare atom would let the generic // LEDs (type-arg call, optional chain, tagged template, assignment) attach and re-open // that whole class; further access chains off the RESULT normally (`super.x()`). - [field('superKeyword', 'super'), alt(['(', sep($, ','), ')'], ['.', alt(Ident, PrivateField)], bracketIndex($))], + [field('superKeyword', 'super'), alt(['(', inCtx(sep($, ',')), ')'], ['.', alt(Ident, PrivateField)], bracketIndex($))], // A standalone identifier expression (IdentifierReference): never a reserved word (see // notReservedExpr), so `catch(x){}` with no `try`, `void ;`, `throw ;`, and a failed `super` / // `new` arm (`new Foo()` is no `(new < T) > Foo()`) are no expression. @@ -524,7 +525,7 @@ const Expr = rule($ => [ ['...', $], // typed call / tagged template: f(…) | f`…` — a call/tag may itself be // continued by member access (`f().x`), so this is an ordinary access tail. - [$, ...typeArgsInExpr(), alt(['(', sep($, ','), ')'], Template)], + [$, ...typeArgsInExpr(), alt(['(', inCtx(sep($, ',')), ')'], Template)], // bare instantiation `f` (no call/tag): allowed only where tsc's // canFollowTypeArgumentsInExpression allows it (`instantiationEnd`) — otherwise `<`/`>` // were comparisons (`f < a, b > 7`). Ending in a negative lookahead, this LED closes the @@ -532,7 +533,7 @@ const Expr = rule($ => [ // it: `Foo.Bar` is rejected (TS1477 — a bare instantiation is not a valid base for // property access). [$, ...typeArgsInExpr(), instantiationEnd], - [$, '(', sep($, ','), ')'], + [$, '(', inCtx(sep($, ',')), ')'], [$, '.', alt(Ident, PrivateField)], // optional chaining: ?.x | ?.#x | ?.(args) | ?.[i] | ?.`…` | ?.(args). A private member // `a?.#x` IS valid current ECMAScript (V8 + Babel accept; tsc's lone parse rejection is a bug @@ -540,10 +541,10 @@ const Expr = rule($ => [ // a tsc-only restriction. Any "no private in optional chain" rule, were it real, would be a // Static-Semantics check in a CST consumer, never a parse-level exclusion here. // Owed: `a?.[0, 1]` (tsc accepts): one expression here, as in JavaScript's Expr (the v1 shape). - [$, field('questionDot', '?.'), alt(Ident, PrivateField, ['(', sep($, ','), ')'], ['[', $, ']'], Template, [...typeArgsInExpr(), '(', sep($, ','), ')'])], // optional typed call `a?.(args)` + [$, field('questionDot', '?.'), alt(Ident, PrivateField, ['(', inCtx(sep($, ',')), ')'], ['[', inCtx($), ']'], Template, [...typeArgsInExpr(), '(', inCtx(sep($, ',')), ')'])], // optional typed call `a?.(args)` [$, ...bracketIndex($)], [$, sameLine, '!'], // TS non-null assertion — RESTRICTED (no line break before `!`, like postfix ++/--); a LHS-chain tail (access can follow: `x!.y`, `x!()`) - [$, field('question', '?'), field('then', $), field('colon', ':'), field('otherwise', $)], + [$, field('question', '?'), inCtx(field('then', $)), field('colon', ':'), field('otherwise', $)], [$, 'as', Type], [$, field('instanceofKeyword', 'instanceof'), $], [$, field('inKeyword', 'in'), $], @@ -560,17 +561,17 @@ const Expr = rule($ => [ // `new class{}?.x`, `new new a()?.x` have no parse tree (tsc + V8 + babel all reject). The // `not('?.')` guards exactly the no-call exits; `new a()?.b` (Arguments consumed) chains via // the outer `?.` LED unchanged. - arm('construct', 'new', NewTarget, alt( - [...typeArgsInExpr(), alt(['(', sep($, ','), ')'], not('?.'))], - ['(', sep($, ','), ')'], + arm('construct', 'new', inCtx(NewTarget), alt( + [...typeArgsInExpr(), alt(['(', inCtx(sep($, ',')), ')'], not('?.'))], + ['(', inCtx(sep($, ',')), ')'], not('?.'), )), - ['new', 'class', ...bindingIdentifier, opt(TypeParams), opt('extends', ClassHeritage), opt('implements', sep(Type, ',')), '{', many(ClassMember), '}', alt(['(', sep($, ','), ')'], not('?.'))], - ['new', 'class', opt(TypeParams), opt('extends', ClassHeritage), opt('implements', sep(Type, ',')), '{', many(ClassMember), '}', alt(['(', sep($, ','), ')'], not('?.'))], - arm('array', field('bracket', '['), opt(field('element', $)), many(field('comma', ','), opt(field('elementRest', $))), ']'), // array literal: each element parsed once (see javascript.ts) - arm('object', '{', sep(field('property', Prop), ','), '}'), + ['new', 'class', ...bindingIdentifier, opt(TypeParams), opt('extends', inCtx(ClassHeritage)), opt('implements', sep(Type, ',')), '{', many(ClassMember), '}', alt(['(', inCtx(sep($, ',')), ')'], not('?.'))], + ['new', 'class', opt(TypeParams), opt('extends', inCtx(ClassHeritage)), opt('implements', sep(Type, ',')), '{', many(ClassMember), '}', alt(['(', inCtx(sep($, ',')), ')'], not('?.'))], + arm('array', field('bracket', '['), inCtx(opt(field('element', $)), many(field('comma', ','), opt(field('elementRest', $)))), ']'), // array literal: each element parsed once (see javascript.ts) + arm('object', '{', inCtx(sep(field('property', Prop), ',')), '}'), // Arrow functions, async/non-async SPLIT so the [Await] grammar parameter routes - // each arm's params + body to the right context word (awaitCtx / resetCtx): an async + // each arm's params + body to the right context word (fnCtx / arrowBodyCtx): an async // arrow's params and body are await-context (`async (a = await) =>` rejects), a // plain arrow's body resets. Type params/annotations stay PLAIN (not await-context). // capExpr('?'): an ArrowFunction is the LOWEST-precedence AssignmentExpression — neither a @@ -582,17 +583,17 @@ const Expr = rule($ => [ // isParenthesizedArrowFunctionExpression: after `<` an identifier or `const`, else the `<` is // a type assertion's), so `<>() => 1` and `() => 1` are no arrows; a declaration's or a // function type's list may be empty (`function f<>() {}`, `type F = <>() => void`). - arm('asyncArrow', capExpr('?', field('asyncKeyword', 'async'), notArrowTypeParams, opt(field('typeParameters', TypeParams)), '(', sep(awaitCtx(field('parameter', Param)), ','), ')', opt(":", ReturnType), field('arrow', '=>'), awaitCtx(field('body', conciseBody(Block, $))))), - arm('arrow', capExpr('?', notArrowTypeParams, opt(field('typeParameters', TypeParams)), '(', sep(field('parameter', Param), ','), ')', opt(":", ReturnType), field('arrow', '=>'), resetCtx(field('body', conciseBody(Block, $))))), + arm('asyncArrow', capExpr('?', field('asyncKeyword', 'async'), notArrowTypeParams, opt(field('typeParameters', TypeParams)), '(', sep(fnCtx.async(field('parameter', Param)), ','), ')', opt(":", ReturnType), field('arrow', '=>'), arrowBodyCtx.async(field('body', conciseBody(Block, $))))), + arm('arrow', capExpr('?', notArrowTypeParams, opt(field('typeParameters', TypeParams)), '(', inCtx(sep(field('parameter', Param), ',')), ')', opt(":", ReturnType), field('arrow', '=>'), arrowBodyCtx.plain(field('body', conciseBody(Block, $))))), // async arrow with a BARE parameter: `async err => …`. tsc requires async and the // parameter on the same line (`async\nx => …` is `async;` then a plain arrow — ASI). // Without this arm the bare form only "parsed" by splitting into two statements. - arm('asyncArrowIdentifier', capExpr('?', field('asyncKeyword', 'async'), sameLine, awaitCtx(notReservedExpr, field('parameter', Ident)), field('arrow', '=>'), awaitCtx(field('body', conciseBody(Block, $))))), - arm('arrowIdentifier', capExpr('?', notReservedExpr, field('parameter', Ident), field('arrow', '=>'), resetCtx(field('body', conciseBody(Block, $))))), + arm('asyncArrowIdentifier', capExpr('?', field('asyncKeyword', 'async'), sameLine, fnCtx.async(notReservedExpr, field('parameter', Ident)), field('arrow', '=>'), arrowBodyCtx.async(field('body', conciseBody(Block, $))))), + arm('arrowIdentifier', capExpr('?', notReservedExpr, field('parameter', Ident), field('arrow', '=>'), arrowBodyCtx.plain(field('body', conciseBody(Block, $))))), arm('yield_', capExpr('?', 'yield', alt(arm('star', sameLine, field('asterisk', '*'), $), arm('expr', opt(sameLine, $))))), // yield e | yield* e (delegate) | yield: an AssignmentExpression, capped as javascript.ts's - ['(', field('first', $), many(field('comma', ','), field('rest', $)), ')'], + ['(', inCtx(field('first', $), many(field('comma', ','), field('rest', $))), ')'], [$, 'satisfies', Type], - arm('import_', field('importKeyword', 'import'), field('form', alt(arm('call', '(', field('source', $), ')'), arm('meta', '.', field('metaKeyword', alt('meta', 'defer', 'source'))), arm('typeArguments', ...typeArgsInExpr(), opt('(', sep($, ','), ')'))))), // import(e) | import.meta | import.defer / import.source (tsc's parser reads `import.` and a name as a MetaProperty; a call after it is the call LED) | import(args) (instantiation-expression; checker rejects) + arm('import_', field('importKeyword', 'import'), field('form', alt(arm('call', '(', inCtx(field('source', $)), ')'), arm('meta', '.', field('metaKeyword', alt('meta', 'defer', 'source'))), arm('typeArguments', ...typeArgsInExpr(), opt('(', inCtx(sep($, ',')), ')'))))), // import(e) | import.meta | import.defer / import.source (tsc's parser reads `import.` and a name as a MetaProperty; a call after it is the call LED) | import(args) (instantiation-expression; checker rejects) PrivateField, HexNumber, OctalNumber, BinaryNumber, BigInt_, ...tsFnArms([opt(...bindingName)], Block), @@ -696,8 +697,8 @@ const Param = rule(() => { ]; }); -const ForHead = rule(() => forHeadArms(Expr, ForBinding)); -const ForAwaitHead = rule(() => forAwaitHeadArms(Expr, ForBinding)); +const ForHead = rule(() => forHeadArms(Expr, ForBinding, noInCtx(field('left', Expr)))); // tsc's parser: any expression without `in` (the checker requires a reference) +const ForAwaitHead = rule(() => forAwaitHeadArms(Expr, ForBinding, noInCtx(field('left', Expr)))); const SwitchCase = rule(() => [ ['case', Expr, many(',', Expr), ':'], @@ -824,7 +825,7 @@ const TypeMember = rule(() => { // a block, after which nothing is needed, or none, and then the member ends as the others // do (parseFunctionBlockOrSemicolon). No modifier before it: tsc's isTypeMemberStart reads // `get` after a modifier as the member's name, so `readonly get x(): T` is not a member start. - [accessorMod, MemberName, ...sig, alt(resetCtx(Block), [not('{'), typeMemberEnd()])], + [accessorMod, MemberName, ...sig, alt(fnCtx.plain(Block), [not('{'), typeMemberEnd()])], // named / computed member (MemberName includes `[Expr]`) — branch method | property // (bare = implicit any). `get` / `set` before a member name is the accessor keyword (tsc // commits to the accessor), so it is not a name there: `get⏎x: T` rejects. A bracket that @@ -850,7 +851,7 @@ const MemberName = rule(() => [ OctalNumber, BinaryNumber, BigInt_, - arm('computed', field('bracket', '['), field('expr', Expr), many(field('comma', ','), field('exprRest', Expr)), field('bracketClose', ']')), + arm('computed', field('bracket', '['), inCtx(field('expr', Expr), many(field('comma', ','), field('exprRest', Expr))), field('bracketClose', ']')), ]); // An index signature is one form wherever a member may be one: parseTypeMember and @@ -904,7 +905,7 @@ const staticTwice = [many(alt(classMods.rest, asyncMod)), classMods.stat, many(a // '@' as belonging to THIS property ("Decorators must precede the name and all keywords") — // `x @dec y()` and `x = 1 @dec y()` reject, `x; @dec` and newline accept. The `!` sits on the // name's line (tsc takes it only without a line break). -const fieldTail = [opt(sameLine, field('exclamation', '!')), opt(field('question', '?')), opt(':', field('type', Type)), opt('=', resetCtx(field('value', Expr))), asi()]; +const fieldTail = [opt(sameLine, field('exclamation', '!')), opt(field('question', '?')), opt(':', field('type', Type)), opt('=', fnCtx.plain(field('value', Expr))), asi()]; // Class member ( params ): T body, params+body routed to a [Await]/[Yield] family: // plain methods reset (a method body has its OWN, non-inherited context — the spec's // implicit function boundary), generators yield, async await, async-generators both. @@ -916,7 +917,7 @@ const fieldTail = [opt(sameLine, field('exclamation', '!')), opt(field('question const memTail = (ctx: (...items: Element[]) => Element) => ['(', sep(ctx(field('parameter', Param)), ','), ')', opt(":", ReturnType), ctx(field('body', fnBodyOrAsi()))]; const ClassMember = rule(() => [ arm('empty', ';'), // tsc's SemicolonClassElement: `class C { ; }` is parse-clean - arm('staticBlock', many(field('decorator', DecoratorExpr)), many(field('modifier', Modifier)), field('staticKeyword', 'static'), awaitCtx(field('block', Block))), // static block body is [+Await] (await reserved); decorators/modifiers parse (SEMANTIC errors) + arm('staticBlock', many(field('decorator', DecoratorExpr)), many(field('modifier', Modifier)), field('staticKeyword', 'static'), fnCtx.async(field('block', Block))), // static block body is [+Await] (await reserved); decorators/modifiers parse (SEMANTIC errors) // decorators PREFIX a member, before any modifier — tsc parse-rejects // `public @dec method()` ("Decorators are not valid here") and an orphan // `@dec` with no member, which a standalone sibling alternative tolerated. @@ -933,12 +934,12 @@ const ClassMember = rule(() => [ // `async` is order-free among modifiers (tsc parses any order; the checker // validates), so it carries its own inner modifier run and an async member's // body is [+Await]/[+Await,+Yield]. - arm('asyncGeneratorMethod', field('asyncWord', asyncMod), asyncWords, field('asterisk', '*'), field('key', MemberName), opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(asyncGenCtx)), // async generator method - arm('asyncAccessor', field('asyncWord', asyncMod), asyncWords, field('kind', accessorMod), field('key', MemberName), opt(field('typeParameters', TypeParams)), '(', opt(sep(awaitCtx(field('parameter', Param)), ',')), ')', opt(":", ReturnType), awaitCtx(field('body', fnBodyOrAsi()))), // async accessor (semantic error; parses) - arm('asyncStaticBlock', field('asyncWord', asyncMod), asyncWords, field('staticKeyword', 'static'), awaitCtx(field('block', Block))), // `async static { }` (semantic error; parses) - arm('asyncMethod', field('asyncWord', asyncMod), asyncWords, not(accessorMod), ...propertyOrMethodName, opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(awaitCtx)), // async method - arm('generatorMethod', field('asterisk', '*'), field('key', MemberName), opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(yieldCtx)), // generator method - arm('accessor', field('kind', accessorMod), field('key', MemberName), opt(field('typeParameters', TypeParams)), '(', opt(sep(resetCtx(field('parameter', Param)), ',')), ')', opt(":", ReturnType), resetCtx(field('body', fnBodyOrAsi()))), // accessor (type params parse; semantic error) + arm('asyncGeneratorMethod', field('asyncWord', asyncMod), asyncWords, field('asterisk', '*'), field('key', MemberName), opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(fnCtx.asyncGenerator)), // async generator method + arm('asyncAccessor', field('asyncWord', asyncMod), asyncWords, field('kind', accessorMod), field('key', MemberName), opt(field('typeParameters', TypeParams)), '(', opt(sep(fnCtx.async(field('parameter', Param)), ',')), ')', opt(":", ReturnType), fnCtx.async(field('body', fnBodyOrAsi()))), // async accessor (semantic error; parses) + arm('asyncStaticBlock', field('asyncWord', asyncMod), asyncWords, field('staticKeyword', 'static'), fnCtx.async(field('block', Block))), // `async static { }` (semantic error; parses) + arm('asyncMethod', field('asyncWord', asyncMod), asyncWords, not(accessorMod), ...propertyOrMethodName, opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(fnCtx.async)), // async method + arm('generatorMethod', field('asterisk', '*'), field('key', MemberName), opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(fnCtx.generator)), // generator method + arm('accessor', field('kind', accessorMod), field('key', MemberName), opt(field('typeParameters', TypeParams)), '(', opt(sep(fnCtx.plain(field('parameter', Param)), ',')), ')', opt(":", ReturnType), fnCtx.plain(field('body', fnBodyOrAsi()))), // accessor (type params parse; semantic error) // index signature, after any modifiers (`async` among them, as in tsc): the type member's // one form (`indexSignature`), so a bracket that starts one is no method or field name. arm('indexSignature', opt(field('asyncWord', asyncMod), asyncWords), ...indexSignature), @@ -949,11 +950,11 @@ const ClassMember = rule(() => [ // so it stays a valid field (the `not('constructor')` generic arm below covers it). // Every constructor is this branch: bare (`constructor() {}`), decorated, modified or an // overload without a body. - arm('constructor', field('constructorKeyword', 'constructor'), opt(field('typeParameters', TypeParams)), ...memTail(resetCtx)), + arm('constructor', field('constructorKeyword', 'constructor'), opt(field('typeParameters', TypeParams)), ...memTail(fnCtx.plain)), // `get` / `set` before an accessor name IS the accessor keyword (tsc commits to the // accessor), so it is not available as a field name there: `get⏎x = 1` rejects. arm('named', not('constructor'), not(accessorMod), ...propertyOrMethodName, field('tail', alt( - arm('method', opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(resetCtx)), // method (requires `(`) + arm('method', opt(field('question', '?')), opt(field('typeParameters', TypeParams)), ...memTail(fnCtx.plain)), // method (requires `(`) arm('field', ...fieldTail), ))), // `async` is a modifier like any other to tsc, so it may also precede a field @@ -1162,6 +1163,7 @@ const Program = rule(() => [ export default defineGrammar({ name: 'typescript', scopeName: 'source.ts', + params: jsParams, // `>` closes type arguments (`f>(x)`, `a as Map>= b`), so `>>`, `>=` … are composed by // the parser from single `>` tokens (tsc's reScanGreaterToken). composeGt: true,