Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/CORRECTNESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
67 changes: 40 additions & 27 deletions docs/GRAMMAR.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
Loading
Loading