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