Implementation status

syntax.md describes the language. It is a specification, not a report: it says what .Gram is, in the present tense, whether or not the compiler does it yet. This file is the report.

Read a row as a pipeline. A construct is only usable when it survives all the way across — the failures worth knowing about are the ones that parse, bind, normalize and then quietly mean nothing.

Parse Bind Normalize Emit Runs
character and string literals ✓ ✓ ✓ ✓ ✓
a literal marked case-insensitive, "text"i ✓ ✓ ✓ ✓ ✓
element sets, ranges, complement ✓ ✓ ✓ ✓ ✓
Unicode categories \p{Lu}, groups \p{L} ✓ ✓ ✓ ✓ ✓
references to elementary rules in a set ✓ ✓ ✓ ✓ ✓
sequence & ✓ ✓ ✓ ✓ ✓
ordered choice \| ✓ ✓ ✓ ✓ ✓
computed switch over a C# integral/string result ✓ ✓ ✓ ✓ ✓
quantifiers ? * + {n} {n,m} ✓ ✓ ✓ ✓ ✓
lookahead ?= ?! ✓ ✓ ✓ ✓ ✓
a capture of what a lookahead saw §3.4 ✓ ✓ ✓ ✓ ✓
rules calling rules, recursion ✓ ✓ ✓ ✓ ✓
namespaces, using, shadowing ✓ ✓ ✓ ✓ ✓
the same rule name in two namespaces ✓ ✓ ✓ ✓ ✓
rebinding namespace N with (A = B) { ... } §5.1 ✓ ✓ ✓ ✓ ✓
the same, expression-scoped, Expr with (A = B) §5.1 ✓ ✓ ✓ ✓ ✓
the same, on a publication, parse R with (A = B) as X §5.1/§6 ✓ ✓ ✓ ✓ ✓
the same, either side a parameterized rule §5.1 ✓ ✓ ✓ ✓ ✓
standard library any none eol eof ✓ ✓ ✓ ✓ ✓
Std's runs atomic, and its numbers refusing a number too wide for their type §5.2 ✓ ✓ ✓ ✓ ✓
eos, the end of a segment, and a sequence of segments read as the input §3.1.1/§6.3 ✓ ✓ ✓ ✓ ✓
the same, text across a boundary, tokens and buffered forms refused (GRAM4048–GRAM4050) §3.1.1 ✓ ✓ ✓ — —
Std.Nested(open, close), read with a counter in a scanner and in a token the lexer begins §5.2 ✓ ✓ ✓ ✓ ✓
the same given arguments a counter cannot tell apart, refused (GRAM4037) §5.2 ✓ ✓ ✓ — —
trivia by shadowing ✓ ✓ ✓ ✓ ✓
publication parse and find §6 ✓ ✓ ✓ ✓ ✓
a directive naming an expression rather than a rule §6 ✓ ✓ ✓ ✓ ✓
the same declaring its type, as Name : @T §6 ✓ ✓ ✓ ✓ ✓
an expression on the right of a rebinding §5.1 ✓ ✓ ✓ ✓ ✓
a qualified name on the left of a rebinding, X with (Std.Digit = HexDigit) §5.1 ✓ ✓ ✓ ✓ ✓
a name two imports supply, read unqualified, refused (GRAM3023) §5 ✓ ✓ — — —
the position a refusal names — — — ✓ ✓
what a refusal says was expected, first tier §0/§11 — — — ✓ ✓
captures name: ✓ ✓ ✓ ✓ ✓
repeated captures of a rule, items: Row* ✓ ✓ ✓ ✓ ✓
construction => at the end of a rule ✓ ✓ ✓ ✓ ✓
construction => per alternative ✓ ✓ ✓ ✓ ✓
nested constructing groups with contextual result types ✓ ✓ ✓ ✓ ✓
rule types : @T ✓ ✓ ✓ ✓ ✓
a generic C# type, : @KeyValuePair<string, Row>, asked about as its definition and arguments ✓ ✓ ✓ ✓ ✓
: @string as the extent §4.1 case 4 ✓ ✓ ✓ ✓ ✓
: @SourceSpan as the bounds §4.1 case 4 ✓ ✓ ✓ ✓ ✓
publishing a rule whose value is a SourceSpan §6.1 ✓ ✓ ✓ ✓ ✓
a span reaching a streamed publication, refused §8.2 — — ✓ — —
rule types naming another rule §4.1 case 3 ✓ ✓ ✓ ✓ ✓
a sequence result : T[] §4.1 case 2 ✓ ✓ ✓ ✓ ✓
the same collecting operands inside a group §4.1 case 2 ✓ ✓ ✓ ✓ ✓
the same with several operands in one repetition, in the order read §4.1 case 2 ✓ ✓ ✓ ✓ ✓
an operand of one captured by hand, reported §4.1 case 2 — — ✓ — —
guards when §8.1 ✓ ✓ ✓ ✓ ✓
inline C# @(...) in when and => ✓ ✓ ✓ ✓ ✓
a condition about the grammar, when A is B §3.6 ✓ ✓ ✓ ✓ ✓
the same with is not, and, or and brackets §3.6 ✓ ✓ ✓ ✓ ✓
the same beside a C# guard in one when §3.6 ✓ ✓ ✓ ✓ ✓
the same answered through with, one parser per reading §5.1 ✓ ✓ ✓ ✓ ✓
the same over regular languages that are not listable, said and kept (GRAM4021) ✓ ✓ — — —
C# names inside @(...), e.g. @int.Parse ✓ ✓ ✓ ✓ ✓
[@Name] as an element predicate §7.1 ✓ ✓ ✓ ✓ ✓
bare @Name as a recognizer over a span §7.1 ✓ ✓ ✓ ✓ ✓
the same handing back a value of its own §7.1 ✓ ✓ ✓ ✓ ✓
direct left recursion §4.3 ✓ ✓ ✓ ✓ ✓
binding powers << n >> n §4.3.1 ✓ ✓ ✓ ✓ ✓
indirect left recursion, through rules that only forward §4.3 ✓ ✓ ✓ ✓ ✓
the same where the tail captures ✓ ✓ ✓ ✓ ✓
the same through several rules that recurse through each other ✓ ✓ refused ✗ ✗
the same, through a rule that does something of its own ✓ ✓ refused ✗ ✗
parameterized rules §4.2 ✓ ✓ ✓ ✓ ✓
a numeric argument, Digits(4) §4.2 ✓ ✓ ✓ ✓ ✓
a value parameter n: int given a number §4.2 ✓ ✓ ✓ ✓ ✓
a value parameter given a literal of its type §4.2 ✓ ✓ ✓ ✓ ✓
a value parameter's name read by the C# it was written in §4.2 ✓ ✓ ✓ ✓ ✓
a value parameter given something the parse produces ✓ ✓ refused ✗ ✗
a sequence result naming a parameter, : item[] §4.2 ✓ ✓ ✓ ✓ ✓
one capture name over rules of one declared type §7.3 — — ✓ ✓ ✓
the scalar form of it, : item §4.2 ✓ ✓ ✓ ✓ ✓
keyword boundaries §4.6 — ✓ ✓ ✓ ✓
recover on a repetition, with => §8.2 ✓ ✓ ✓ ✓ ✓
the names recover supplies §8.2 — — — ✓ ✓
offsets are long, extents are int §6.3 — — — ✓ ✓
recover without =>, dropped and reported §8.3 ✓ ✓ ✓ ✓ ✓
a second recover in one rule, a plan each §8.2 ✓ ✓ ✓ ✓ ✓
the same in a rule read from a TextReader §6.3 ✓ ✓ reported — —
a recover inside a lookahead, refused (GRAM4038) — a rule called from one recovers §8.2 ✓ ✓ ✓ — —
a recover inside another one's element or synchronization, as if its own rule there §8.2 ✓ ✓ ✓ ✓ ✓
a recover in a rule the lexer reads, refused (GRAM4044) §8.2 ✓ ✓ ✓ — —
a value crossing a nested recover that its own rule could not carry, refused (GRAM4045) §8.2 ✓ ✓ ✓ — —
a => that throws inside recover leaves the parse §8.2 — — — ✓ ✓
C# recognizer calls emitted without generator resolution §7.1 ✓ ✓ ✓ ✓ ✓
a value type generated for a rule that has none §7.3 — — ✓ ✓ ✓
captures matched to an existing type's constructor §7.3 — ✓ ✓ ✓ ✓
captures matched to init/required properties §7.3 — ✓ ✓ ✓ ✓
a C# type named beside the grammar, nested in the host — ✓ ✓ ✓ ✓
a declared type found under the grammar's @using §7.3 — — ✓ ✓ ✓
C# in => and when emitted without generator resolution §7.4 ✓ ✓ ✓ ✓ ✓
#line from the generated file back to the grammar §7.6 — — ✓ ✓ ✓
Match<T> and its Outcome §7.5 — — — ✓ ✓
an outcome for a failure past a commit point §8.2 — — — ✗ ✗
leading and trailing trivia §4.5 — — — ✓ ✓
trivia between operands and not between iterations §4.5 — — ✓ ✓ ✓
a C# name as an argument of @M(…), behind @ §7.1 ✓ ✓ ✓ ✓ ✓
retention: what a rule takes, in lines §6.3 — — ✓ — —
retention: where the window may move §6.3 — — ✓ — —
find over a TextReader §6.3 — — ✓ ✓ ✓
parse over a TextReader §6.3 — — ✓ ✓ ✓
a streamed feed of records of differing lengths — — — ✓ ✓
recover stepping over a bad record in a stream — — — ✓ ✓
a repetition that cannot tell its own end §6.3 — — ✓ — —
a repetition of something other than a rule §6.3 — — ✓ — —
IEnumerable<string> input §6.3 — — — ✓ ✓
the §8.3 hook over a streamed parse — — — ✓ ✓
context : @T, handed over by the caller §7.7 — — — ✓ ✓
the same reaching a when, a => and every rendering §7.7 — — — ✓ ✓
state : @T and Expr with state @(...) §7.8 — — — ✓ ✓
a mark read by a construction as parserState §7.8 — — — ✓ ✓
a context strengthened, a state shared, across a composition (GRAM3019, GRAM3020) §7.7/§7.8 — — ✓ ✓ ✓
a host inheriting the grammar of its base class — — — ✓ ✓
the same naming itself with [Gram(DefaultAlias = "…")] — — — ✓ ✓
[GramInclude(typeof(X), Alias = "…")], several at once §6.7 — — — ✓ ✓
a base or an include in a referenced assembly, read from its [GramSource] §6.7 — — — ✓ ✓
[GramParserVariant("…")], a second reading of one grammar §6.6 — — — ✓ ✓
a rule's own refusal message, on fail "…", in every reading §4/§7.5 ✓ ✓ ✓ ✓ ✓
internal parse, private find §6 ✓ — — ✓ ✓
positional parse: TryParseR(input, at) and TryParseR(input, at, length) §6.3 ✓ — ✓ ✓ ✓
bool TryParseR(input, out R value), the quiet form §6/§6.1 — — — ✓ ✓
the publications of one rule sharing a machine, told apart by the reading §5.1 — — ✓ ✓ ✓
a publication another reaches, joined into that one's machine — — — ✓ ✓
a grammar cut into a lexer and a syntactic half, Lexical = true §4 — — ✓ ✓ ✓
a terminal the lexer begins and a rule or the host ends, '<' & @M §7.1 ✓ ✓ ✓ ✓ ✓
the carrier left to the generator (Immediate unless refused), or named, Carrier = GramCarrier.… — — — ✓ ✓
a trace build, Trace = true or DotGramTrace: the sink, its scope and three sinks §6.9 — — ✓ ✓ ✓
the same reporting a rule that only forwards where it was collapsed §6.9 — — ✓ ✓ ✓
the same over a reading on the engine, flat, buffered or streamed, and a rule retracted by the engine §6.9 — — — ✓ ✓
a @Name or [@Name] the parser cannot call, said on the grammar (GRAM4025) §7.1 — — ✓ — —
a binding and its back-reference, $q: X … $q §3.5.1 ✓ ✓ ✓ ✓ ✓
a count by the length of a binding, X{#q} {#q,} {n,#q} §3.5.1 ✓ ✓ ✓ ✓ ✓
a binding read where it may not have happened, ($q: X)? then $q, refused with the fix §3.5.1 ✓ ✓ ✓ — —
a binding inside a lookahead, or over a recovery point, refused §3.5.1 ✓ ✓ ✓ — —
a binding and its back-reference in an atomic terminal the lexer reads: begun by the lexer, read whole by its rule, lexed again without it where the rule refuses §3.5.1/§7.1 ✓ ✓ ✓ ✓ ✓
a terminal that binds nothing but that the automaton reads wider than its rule (a guard, an atomic group read with a way back, a choice whose earlier alternative is a prefix of a later one): begun by the lexer, measured by its rule from the token's start, lexed again without it where the rule refuses §7.1 ✓ ✓ ✓ ✓ ✓
the same beside a token or trivia that can read on past its beginning, or not atomic: read over characters, GRAM5004 naming the fix §7.1 ✓ ✓ ✓ — —
a binding in what trivia is made of once the grammar is cut in two, refused, not yet supported §3.5.1 ✓ ✓ ✓ — —
a binding and its back-reference read through a TextReader or a stream, bytes included §3.5.1 ✓ ✓ ✓ ✓ ✓

Two things this table used to carry as rows are decisions rather than gaps, and a row of crosses read as neither. Repairing a document — searching a broken input for the edit its author most likely meant — is out of scope by syntax.md §11, and by more than omission: it was tried and put down, and the engine plan's own section about it was removed rather than corrected. recover (§8.2) is not a smaller version of it; the two answer different questions, one about a document and one about the hundred-millionth record of a feed. Incremental parsing is not started, and has one known prerequisite rather than a design: the arena would have to record each entry's size instead of its position, so that a tail nothing touched stays valid when an edit shifts everything after it (docs/internal/next.md, the Nitra reading).

Recovery in yielded collections

Rule* recover Sync and Rule+ recover Sync can be published with yield. A constructing group can replace the element rule: (pattern => @(value))*. Its type is the enclosing collection's element type; lowering creates an internal rule before recursion rewriting, so captures, factories, recovery and location handling use the ordinary rule machinery. Nested scalar groups take the enclosing rule's scalar type. No type annotation or inference behavior changes for existing rules. GroupValueTests covers eager and lazy strings, buffered characters/bytes, legacy readers, templates, lexical parsing and discarded alternatives. Recognition uses one committed recovery iteration at a time; it does not parse the whole collection before yielding. A recovery factory returns one scalar result without allocating a one-element collection. Without a factory, the rejected iteration reports through the existing hook and yields no value. Ordinals and positions continue across iterations, and EOF retains ordinary recovery behavior. Character and byte buffered input support recovery factories with native span arguments. Existing restrictions on byte input and line/column tracking still apply.

Computed switch dispatch

switch @(expression) { case 1: Body default: Other } selects one branch using an integral or string C# result. Selectors support preceding captures, context and span access on character and byte inputs, including yielded streams. A selected branch never falls through to a sibling on failure. Ordinary result inference is unchanged. Numeric/string labels, shared bodies and an optional default are supported.

Computed dispatch is supported by both the shared machine and the direct-reader emitter. The direct reader uses the same capture and value-materialization machinery as guards; the usual guard restrictions still apply. Computed selection alone does not cause a GRAM5005 fallback. On replay inside a selected case, the reader retains the selected branch in its existing backtracking tape. Computed switches inside token patterns cannot be compiled into the lexer's static tables. Buffered input retains its existing restriction on token-kind input (GRAM4026).

Backtracking, and where it stops

Backtracking is full across ordinary rule calls. The generated parser is one automaton; calls record continuations in its arena instead of becoming C# calls. Entering an alternative records the next one, and taking another repetition records the option of having stopped. Failing anywhere resumes the most recent available path, including one inside a called rule. So 'a'? & 'a' matches "a", and both the inline and extracted forms below match "xy":

Start = Name & 'y'
Name  = "xy" | "x"

The inline form is Start = ("xy" | "x") & 'y'. Extracting the choice into Name does not change its meaning, and a whole parse keeps alternatives available until the end-of-input condition is satisfied.

A publication needing none of this compiles without the automaton at all. No recursion, no backtracking its proofs cannot discharge, no record a local cannot hold — a qualifying publication compiles to a plain method: captures as position locals, the one construction run after the whole-input check, a captured call to another such rule compiled as that rule's body in place. A choice that genuinely needs coming back to — ("http" | "https") & "s" — is no longer disqualifying: its way back is three locals (the position, the next alternative, the site pending before it), and the method's failure path resumes the innermost open site before giving up — the engine's unwinding, without the engine. A repetition over such a choice would need one pending record per turn, which locals cannot hold, and keeps the arena. The question is asked per machine, of the rules it actually reaches — a recovery or a climb elsewhere in the grammar is some other machine's business — and where every publication of a machine qualifies, neither the arena nor the pooled parser is emitted for it. Inside the engine the same proofs shrink what is written: a possessive repetition is a loop with no entry, a one-character lookahead is its test, an atomic group over silent alternatives is a chain through one checkpoint local, and a captured call to a flat-valued rule is a site — the callee's body in place, its spans in slots of the site's own, its factory called at Accept, with no Call entry and no dispatch. What follows in this section is about what remains.

{ ... } is the explicit exception. After an atomic group succeeds, alternatives made inside it are discarded; { "xy" | "x" } & 'y' therefore fails on xy. A rule boundary never commits implicitly.

Recursion uses the same arena frames and is not bounded by the C# call stack. Direct and mutual-recursion stress tests run to tens of thousands of levels; recognition and typed materialization are both iterative.

Recovery is determined by the continuation, not by consumption. At each element boundary, a recovering repetition first tries the complete continuation, provided its minimum has been met. When that fails, a failed element with remaining input is an error, even when its first token does not match. Both ab1 and 1bad are recovered in:

Start = rows: Row* recover eol => @(...) & eof
Row   = t: ['a'..'z']+ & eol

An invalid final fragment is recovered through EOF. No empty error element is created at EOF, so a missing required element or trailer still fails. Atomic groups only close internal alternatives; a { ?=any } discriminator is not needed for recovery. Contiguous, buffered character/byte, yielded, and line-window inputs follow the same boundary rule.

A repetition marked recover commits each element it actually takes. Before asking for another element, it first tries the complete continuation after the repetition. That continuation therefore gets first refusal at every element boundary:

Row   = name: ['a'..'z']+ & eol
Start = rows: Row*                        & tail: ['a'..'z']+ & eol   // matches "aa\nbb\n"
Start = rows: Row* recover eol => @(…)    & tail: ['a'..'z']+ & eol   // also matches

The marked form does not first take bb and later hand it back. At the boundary before bb, it tries tail together with everything following it; because that complete path succeeds, no second Row is attempted. If the continuation failed, Row would be tried. Once that Row either matched or was explicitly recovered, it would not be offered back to a later path. This preserves a valid trailer or other continuation without using atomic groups to classify a failed element.

A part in front of a rule that recovers does not give back for its bad first element. With Rows = Row+ recover ';' & '.', Rows reads ;. by stepping over the ;, and ';'* & Rows refuses it: the part is taken never to need a shorter reading on the strength of what a good element begins with, and keeps the ; the recovery would have stepped over. An option, a count or a choice of literals in front does the same.

What a rejection is told

All fourteen names the parser supplies are there — the eleven a recovery names, and parserInput, parserState and parserMarks (§7.8), which a construction may ask for too (SuppliedNames). Two differ from the specification in ways worth knowing:

  • parserText and parserSpan stop where the synchronization point begins. eol separates the elements and is not part of one, so a rejected b1b\n is three characters, not four.
  • What would have fit is the parse's furthest refusal. parserExpected and the message are what was refused where reading the element stopped, since its turn began, where that place is the furthest, which is the usual case. Where a continuation tried at the same boundary read further than the element and failed there, the message says only that the input does not match the rule, Input does not match 'Row' at 4:1., and parserExpected is the rule's name.
  • Each reading of a recovering repetition keeps its own count of where its turn began. One read inside the element of another, or in the synchronization another looks for, keeps to its own, and so does one reached again inside its own element — a rule that calls itself through it, by recursion or through a look ahead: the engine keeps such a repetition's turns on its arena, where unwinding finds them, and the enclosing turn is told what its own element wanted.

Which of the eleven a factory asked for is read out of its C#, because §8.2 has counting lines cost a scan and only a factory that named parserLine should pay for one. The reading is a whole-word search over the text, so it over-approximates: parserLine inside a string literal counts as asked for. That direction is the safe one — a name that was written is always found, and a name that was not costs an unused parameter. Reading it exactly means lexing C#, which is the host's job and not the grammar half's.

A recovering repetition hands back its sequence: each rejection is either built by recover … => … and put in its place, which is §8.3's first row (failures as the author's own types), or dropped and reported, which is the second.

Without a => the element is dropped and reported to a partial void, which is §8.3's second row — successful records only, failures to a log, nothing declared. The generated class declares the channel and the consumer may implement it:

static partial void OnRecovered(
    string rule, string text, long position, int line, int column, int ordinal, string message);

The classic C# 3 form, not the C# 9 one: an implementation is optional, and where there is none the compiler removes the declaration, every call to it, and everything in the argument lists. So the element's text is never materialized and its line never counted unless somebody is listening — which is why every argument is an expression and none is computed into a local first, and why LineAt and ColumnAt are two functions rather than one method with two out parameters. A test compiles a grammar with no implementing half and asserts the method cannot be found on the type at all, so the erasure is checked rather than assumed.

It is also why this is a partial void and not an event, a delegate or an ILogger: those cost something even when null, and the premise of a streamed feed is that nobody is usually listening.

The cost is that the hook is static and per host class, so what it reports cannot be scoped to one call, and one hook serves every recovering rule in the grammar — hence the rule parameter. LoggingFeedExample shows the ordinary way round the first: gather into a [ThreadStatic] for the duration of a read.

A => that throws is not caught, inside a recovering repetition or anywhere else. This was the one place the specification and the code disagreed, and it was settled by changing the specification: §8.2 used to promise the throw would be caught and treated as a failed parse outcome. Catching would mean catching Exception, because no type tells "this quantity is not a number" from NullReferenceException, and a parser that reports a bug in the author's own C# as "row 400 was malformed" is worse than one that stops. The generator does not infer a parser outcome from the signature of the C# called by =>. Where a grammar says ConstructionsMayThrow = true, the immediate carrier holds the exception while the reading it was raised in may still be given up, and throws it where the deferred carrier would have built the value (§7.5); it is never an outcome, and one from a reading the parse abandons is never seen.

DecimalCalculator.Evaluate("1 . 5") in the examples throws FormatException out of a decimal.Parse in a =>, and a test asserts exactly that.

Associativity

Direct left recursion works and means left-associative, as §4.3 says. R = left: R & op & right | base is rewritten into base & (op & right)*: the leading self-call is what makes an alternative recursive and what the rewrite takes away, and left stops being a capture and becomes the value built so far, which that alternative's own => receives.

The loop is an ordinary repetition, so backtracking, forgetting and the rest apply to it unchanged.

Nothing decides associativity, and nothing computes it. The only structural question asked of an alternative is the one that has to be asked — does it begin with a call to its own rule, which cannot be compiled as written. Everything else is an ordinary call, and how it groups falls out of the order the calls return in. So in a grammar of levels the author says associativity by choosing which operand is parsed at the rule's own level:

Sum   = left: Sum     & op  & right: Product   // left at this level  → left-associative
Power = left: Primary & '^' & right: Unary     // right at this level → right-associative

Unary is the looser level and comes back down to Power, so the right operand of ^ can be another ^ and the left one cannot. There is no "right-recursive" in the compiler because there is nothing for it to do: Power never calls Power at all.

Deferred, nothing is built while matching, folds included. What a match records is a number: which alternative it came through, and — for a chain — which step followed which. Both ride on the backtracking frame, so an alternative or a step given back is forgotten with everything else it did, and the factories run at the accepting state in the recorded order. The immediate carrier is the exception, and says so: there a construction runs where it is read (Carriers, below).

That is what lets a rule have as many recursive alternatives as it likes. Accumulating built values instead would need one type to hold them all, which would have capped a rule at one — and a postfix chain wants three: member access, call, index. What is collected instead is each alternative's own captures, one entry per iteration, which needs no common type at all.

Refused: indirect left recursion except through rules that only forward, which is the one shape of it that is not arbitrary and is rewritten (GrammarNormalizer.Recursion); a rule whose every alternative is left-recursive, which has nothing to start from; and an alternative recursive on both sides, which ordered choice cannot settle — -1-2 under E = E & '-' & E answered 1 rather than -3 until that was checked.

Binding powers

Built, and they are the same rewrite. E << 1 | E >> 3 | … folds into bases & (tails)* exactly as §4.3 does, and two numbers ride beside it: which strength a tail may be entered at, and which strength its own operand is parsed at. The recognizer takes the first as a parameter and tests it before matching anything of an alternative; the second is a constant at the call site, n + 1 for << and n for >>. That difference of one is the whole of left against right.

Only a rule that says << or >> takes the parameter. A grammar that never reaches for them is generated exactly as it was before they existed, which is why no snapshot moved.

An alternative recursive on both sides is the ordinary case here, and refused under levels. The refusal is not about the shape — it is that ordered choice has nothing to settle the grouping with. A strength is exactly the missing information, so the same left: E & op & right: E is a diagnostic in one convention and the point of the other.

A strength is not symmetric, and that is what makes one number enough. It says only what the operand to the right is read at. A prefix has no left operand, so it is a base — one of the alternatives that start an expression — and a base is entered whatever strength was asked for, because there is nothing to its left for anything to bind more tightly than.

So the asymmetry that looks as though it needs two numbers does not. Python's ** binds tighter than unary minus on its left (-2**2 is -4) and looser on its right (2**-1 parses); levels say that by naming two different rules either side of it, left: Primary & '^' & right: Unary. Strengths say it by giving ^ and unary minus the same number. examples/ has the same calculator both ways and a test that runs them against each other expression by expression, that pair included.

Refused with GRAM4009: a rule with a strength on one recursive alternative and none on another (§4.3.1 — one convention or the other), and a strength on an alternative with no operand of its own to read at it.

What a publication answers with

TryParseR hands back a Match<T> — value, error, position, length. Beside it stands the one form that takes an out parameter, bool TryParseR(input, out R value), for a caller who asks only whether: it reads once, quietly, and says nothing about a refusal (§6.1). FindR hands back a lazy IEnumerable<Match<T>>, so "the first one" and "the ones that satisfy this" are LINQ's rather than more directives. match and find all are gone: one word meant three different things across ecosystems, and the other was a sequence method wearing a directive's clothes.

The position it reports was always zero until now. It is now the furthest the input could be followed before the match gave up — which, for a parser that backtracks, is the only position worth naming: the last thing tried is usually shallower than the best thing tried. On a match it is instead where the match began.

Every recognizer takes a ref Failure and raises Position at the one place a machine gives up on where it is. Nothing is paid on the path that matches, a rule call carries its callee's failure out with it, and a lookahead is the one machine that does not take the state — how far it looked before answering "no" is not how far the parse got. A positive look that saw nothing refuses the reading where the look began, which is how far the parse got, saying nothing about what it expected there. A turn of a possessive repetition, or an alternative of a group that commits, kept in locals gives the position back at the door it leaves by; what refused inside it is recorded there, where it is further than anything before, so Digit+ & ('.' & ['0'..'9']+)? on 1.x refuses at the x wanting a digit rather than at the point wanting the end. A scanner that gave input back to itself hands back how far it read when it matches too, and that place is recorded in the scanned rule's name, as its refusal is.

Failure now also carries Expected — §0/§11's first tier, built live beside Position rather than re-derived afterward: every literal or element test that fails records, before it jumps, an already-built display array naming itself; a new furthest position replaces what is recorded there, a tie with the current one adds to it. A message reads it once the whole attempt has failed — "Expected ')'." for one, a comma-and-"or"-joined list for several, "Expected more input." when the furthest point was the end of the input and nothing else was tried there. Reached through RenderEngine's shared Fail: and RenderFlat's own, identically, so a lowered rule carries it too. A binding-power guard, a when, an external recognizer, a negative lookahead that matched, and the rest of what is not a literal-or-element test clear it rather than leave a stale value behind, the same care lookahead < 0 already takes for Position.

CompilePredictedChoice — a choice one character decides — contributes a display too: the union of every alternative's first-set ranges, rendered as one element set, since Predictive already proved each of those first sets known and finite before it agreed to predict at all. Calculator.Explain("2*") names "Expected ['-' | '(' | '0'..'9']." rather than falling back to "Expected more input." Where the alternatives begin with the seam — the operators of a spaced grammar, each read after trivia — their first sets hold the spaces too, and a set listing the whitespace classes before the operators is not what was wanted: such a choice says one item per alternative instead, what begins it past the seam, Expected '+', '-' or ')'.. Every item of a set is a literal, a class or a rule's name, whatever it is asked of — a choice whose alternatives are whole sequences names what begins each, never the alternative's source.

One narrowing remains, documented at its own site: a prefix-conflicted run of literals — "p" | "q" | "pr" — can under-report what it covers, since two entry-less runs chained by fail overwrite rather than merge when both fail at the one position neither could move past. It never mis-attributes or moves the position; it simply has less to say than the full mechanism eventually could.

A case-insensitive literal ("text"i) needs nothing special here — it fails through the same Node.Literal codegen as any other and names itself with its own i: "http"i names Expected "http"i. But it reports its first set as "anything," the same conservative answer an unreadable Unicode category or a complement gives, so it opts out of CompilePredictedChoice and CompileLiterals's optimizations the same way those two narrowings do — a first-cut cost, not a correctness one.

The position itself is now the character that did not fit, not where the failing operand began: "abcd" against abXY names 2, not 0. Each of Node.Literal's per-character comparisons and CompileLiterals's shared-prefix read advances p by its own offset immediately before the jump to Fail: — safe because nothing between that jump and the next resume ever reads p for anything but recording it; every resume restores p from the arena entry being popped rather than trusting whatever it was left at. CompileLiterals's own per-alternative suffix tests are the one place this is not true yet: each alternative's remainder is one combined boolean rather than a per-character branch, which is the whole of that optimization's saving, so a failure there still names where the shared prefix ended rather than the exact character — narrower than the rest, in the same accepted-first-cut way as the two narrowings above it.

And one thing bundled with Expected when it was still a plan is still not built on its own: the outcome that tells a malformed record from no record (§8.1) — a third thing beside Position, not delivered by this.

A reading from a position can refuse, or cut short, the rule's first reading. A rule is compiled once for its whole forms and the forms that begin at a position or read a window, and by default against the end of the input, which only the whole forms demand. Some decisions taken on the strength of that end hold for the whole forms only, so in a few shapes — an optional or a repetition before a negative lookahead, a quoted string with doubled quotes — a reading from a position refuses, or stops short of, what the rule's first reading is (§4). The whole forms are right. The experimental build property DotGramPositionalFollow (§6.8) compiles the positional forms against what follows instead, and they read the first reading, at the cost §6.8 gives.

Back-references

syntax.md §3.5.1 describes a binding, $q: X, and the operands that read it: $q, and a count by its length, X{#q}. It works in both readers, the generated one and the engine, for parse and for find, over a string, a span, a memory or an array.

What it does not do is refused at build time with a diagnostic that says where:

  • A binding is read by a reference in the same alternative of the same rule. A reference across a rule call, into or out of a constructing group, or in the step of a fold is refused (GRAM4063, GRAM4064), and so is a name that nothing bound (GRAM3021).
  • A reference that may be reached on a route that skipped its binding is refused with the fix (GRAM4032).
  • A binding inside a lookahead is refused (GRAM4060); a reference inside one is fine.
  • Not yet supported (GRAM4034): a binding in a repetition that recovers, or in what such a repetition skips to; and in what trivia is made of once a grammar is cut into a lexer and a syntactic half. An atomic terminal that binds text in such a grammar is begun by the lexer and read whole by its own rule from the token's start, and where that rule refuses the position is lexed again without it (§7.1); beside a token or trivia that can read on past its beginning, or not atomic, the part is read over characters with a GRAM5004 that names the fix; one that begins with nothing an automaton reads is refused by name. A publication over a TextReader or a stream reads bindings as the string form does.
  • Over kinds neither a binding nor a reference is accepted (GRAM4035); a guard compares two captures there.

A count whose bounds cannot be met is not a build error, because the lengths are known only when the count is reached: {n,#q}, {#q,m} and {#q,#r} fail at run time when the lower bound exceeds the upper.

Captures, and what they build

A rule with captures gets a type of its own — public sealed class, nested in the host class, one get-only property per capture name — and every published method hands that back instead of a string. A rule without captures is unchanged: its value is the text it matched, and its recognizer has the signature it always had.

A capture holds (start, end) into the input, or the value of the rule it names when that rule builds one. The whole value is constructed once, at the accepting state, from one expression. Deferred, nothing is built during the match, so an attempt that is abandoned costs nothing to undo — and any C# a grammar supplies will run on the parse that actually happened rather than once per attempt. On the immediate carrier a construction runs where its alternative is read, so a parse that fails may already have run some (Carriers, below).

Backtracking forgets what it captured. Slots are numbered in the order the notation writes them, which makes "everything written since this point" a suffix of them; each state a match can resume at clears that suffix, as literals worked out while generating. There is no journal and no marks, and the path that does not backtrack pays nothing.

A repeated capture collects. items: Row* is a Row[], appended to where each value is built and truncated back when an attempt is abandoned. The length at the moment of a push rides on the backtracking frame, which is what makes it exact even for a repetition inside a repetition: giving back an outer iteration truncates to what the inner ones had collected before it began. No iterations is an empty array, never null.

A repeated capture of text is a different thing and stays one: §10 binds a capture tighter than a quantifier, so digits: ['0'..'9']+ is one capture repeated, and §7.3 gives it the text joined. Each turn records an entry of its own and the value is those joined — taken as the extent of the whole run where the turns are adjacent, which is measured rather than assumed, so (t: A+ & '-')+ answers "1234" and not "12-34".

A run that took no turn is "", whatever its bounds. c: 'a'{0,2} that took none read "" in a rule of one alternative and null in a rule of several, where another alternative leaves c unwritten: the capture is recorded once per turn, no turn left no record, and no record was read as the capture that never happened. Only * was safe, because its capture is recorded once around the loop, and a loop of no turns is still a record. Every bound but {0,1} is recorded that way now. A run whose turns cannot be one record — (c: 'a' & ',')*, where the comma is in the extent and not in the text — is given an empty record in front of it, where the rule may also leave the name unwritten. ?, {0,1} spelled out, stays the option it is: null where it did not match. Over bytes a text capture is a span and was empty either way, so the string and byte forms of one grammar disagreed until now.

One thing a capture can still be that is recognized and not built, GRAM4006 rather than a silent drop: a capture inside a lookahead, which is a machine of its own that answers yes or no.

And GRAM4007: one name captured twice with different types.

A rule that names its own type

R : @T = … => @Expression works. The type is written into the generated file exactly as the grammar wrote it, the grammar's @using directives are carried in beside it, and whether the name resolves is C#'s question to answer on the grammar's line — which is why none of this needed symbol resolution.

The => becomes a method, and the captures are its parameters:

static int New_DotGram_Number(string parserText, string digits) =>
    int.Parse(digits, CultureInfo.InvariantCulture);

A method rather than an expression written where the value is assigned, and that is what makes the capture names usable at all: inside a recognizer they would have to dodge every local it has, and a capture called p or state would collide with the machine itself. parserText is supplied — the matched extent, §7.3 — and a capture that takes that name, or any of the other thirteen, is refused (GRAM4012).

§7.3's first way of filling a type in works: a rule that declares : @T and writes no => is built by calling T's constructor, with its captures as the arguments.

Row : @Row = name: ['a'..'z']+ & ',' & amount: ['0'..'9']+

matched against Row(string name, string amount) and called with the two captures, in the constructor's order. Names are compared without regard to case, which is the mechanical transform §7.3 describes — the capture symbol fits the parameter symbol and, where a record wrote one, the property Symbol.

The constructors of a type are the third thing the Roslyn shell answers, alongside whether a type exists and whether one is assignable to another (.claude/rules/grammar-half.md). It is asked as part of the cached question set, so a keystroke that changes nothing about the host still costs nothing.

Chosen, not guessed at: the longest constructor every parameter of which is covered by a capture. Two of the same length both covered is an ambiguity nothing here can resolve, so none is chosen and the rule is reported unbuilt — calling the wrong constructor silently is the failure worth avoiding. The types are not checked on this side; whether a capture goes in that parameter is C#'s question, and §7.6 now asks it on the grammar's own line.

Writing the construction out by hand goes on meaning exactly that. The match is what happens when the grammar left the question unanswered, so => @(new Row(amount, name)) builds it that way round, arguments swapped and all — a test pins that, because a match by name could never produce it.

Half an answer is refused. A => on one alternative and not on the next leaves a rule whose value is built two ways, and the constructor is matched against the rule rather than against an alternative, so there is no half to complete. The message says which half: says how to build its value on 1 of its 2 alternatives and not on the rest. It could have been completed instead — filling in the alternatives that stayed quiet — and that was not done on purpose: a missing => is as likely to be an omission as an intention, and the silent version of that guess builds the wrong value.

A type written beside the grammar is found by its short name, the same way a method beside it is. @Row used to mean a top-level Row only, so a type nested in the host — which is where a type written for one grammar belongs — could not be named without spelling out a chain the author writes nowhere else. The host is looked in first, which is both what C# does and what the generated code needs: it sits inside the host class, so a short name there binds to the nested type whatever the resolver decided, and deciding otherwise would check the constructors of one type and call another.

§7.3's second way works too, and is reached when the first cannot answer: the value is made and its properties written from the captures, in one object initializer because that is the only place init and required can be written. Every required property has to be covered — a type saying required is saying it will not compile otherwise — and a property that is neither covered nor required is left alone, keeping whatever default the type gave it. At least one has to be written, or this would be making an empty value rather than building one.

The order is §7.3's own: a constructor first, and only what it could not answer is asked of the properties. A tie between constructors is left as a tie rather than falling through to them — the grammar did name a way to build this type, and it is the ambiguity that has to be reported, not a second way found behind it.

Whether the type has a constructor of no parameters to write into is not checked here. That is C#'s question about the initializer this emits, and §7.6 now asks it on the grammar's own line.

A guard asks the values

when @(…) runs during the match, which is what makes it recognition: saying no is a non-match and a sibling alternative is tried, exactly as §8.1 has it. It becomes a method of its own for the same reason a => does, and takes the same parserText.

What it may look at is what was captured before it. A capture further along has not been written, so it is not a parameter, and naming it is an ordinary C# error about a name that is not there. A name is passed as nullable at the guard exactly where a route can reach the guard without having written it — an option on the path, as in ('(' & a: X)? & when @(a …). Where every route to the guard writes it, the guard is handed the value itself, whatever the rule's other alternatives do or do not write: the question is asked of the alternative's prefix, not of the rule.

A typed capture is different from text: its => normally runs only after recognition, but a guard that names the value needs it now. That construction runs once at the guard and is cached on the current derivation. Acceptance reuses it rather than calling the factory again; backtracking discards it with the arena suffix. Sequence captures are materialized together into one array in grammar order, including recovered elements. The cache and its invalidation are emitted only for grammars that actually use a typed value in when.

Every alternative may build its own way

Which => fired is remembered while matching and undone with everything else an abandoned attempt did — a => covers a whole alternative, so the only way back past one is through the choice that offered it, which is where it is forgotten.

A factory sees only what its own alternative can have captured. A sibling's captures are not its parameters, and its own are optional only where that alternative may skip them — so digits: […]+ => @(int.Parse(digits)) does not warn about a null that the alternative it belongs to cannot produce.

Three things are refused rather than quietly ignored, all GRAM4008:

  • a => on a rule that declares no type. There would be nothing to build.
  • a declared type where some alternative has no => and §7.3 cannot fill the rule in: a => on some alternatives and not the rest, or captures no constructor or settable properties of the type can be matched to (A rule that names its own type, above). : @string is the one type left to the shape of the rule.
  • a => anywhere but on an alternative of the rule — inside a group, say. It builds the rule's value, and a group has none.

: T naming another rule is §4.1 case 3 and resolves: the rule takes the named rule's value. GRAM4011 is what is left over — a name in type position that is neither a C# type nor a rule in view. Before either, the declaration was dropped in silence and the rule got a type generated from its own captures instead, so A : B compiled, ran, and handed back an A with nothing to do with B.

Syntactic position now fixes the two recognizer contracts. [@Name] is an element predicate and emits Name(c); bare @Name is an input-consuming recognizer and emits Name(text, ref p). Both are now asked of the host (ISymbolResolver.ResolveExternalMethod), looked for where the generated call will look: the host class, the classes around it, its bases, and the classes of the grammars it includes. A name with no method, or only methods of another shape or out of reach, is GRAM4025 on the grammar's line (since 2026-09-13 for recognizers, 2026-09-14 for predicates). Only a certain no is said: a method of the right shape anywhere in the compilation's source is taken to be the one meant, and a grammar compiled without a host is not asked. Overload selection among fitting methods is still the C# compiler's.

One deviation from §7.3, deliberate

The generated type used to be the other one. §7.3 asked for a record and a sealed class was emitted, because a positional record needs IsExternalInit and that lives in a namespace this generator must not emit into. That is no longer a deviation: the specification says class now, and says why. A specification may describe what is not built yet — that is what this file is for — but not something the project has ruled out on purpose.

What is left:

  • Match<T>.Value is T rather than T?, so a failed match holds default and IsSuccess is what says so. An unconstrained T? needs a language version this generator may not assume, and T has to be unconstrained now that a rule may declare itself : @int.

Where the author's C# actually runs

Not inside the machine. Every =>, every when and every recovery factory becomes a method of its own, and the names it can use — the captures, and the supplied parserText, parserLine, parserColumn, parserOrdinal, parserMessage — are that method's parameters:

static FeedLine Recover_DotGram_Feed(
    string parserText, int parserOrdinal, int parserLine, string parserMessage) =>
    new RejectedLine(parserOrdinal, parserLine, parserText, parserMessage);

static decimal New_DotGram_Expr(string parserText, decimal operand) =>
    (-operand);

That is what makes the names usable at all. Written where the value is assigned they would have to dodge every local the recognizer has — p, state, r, saved, sp, bt, value, failure — and a capture called p would collide with the machine itself. As parameters they are in a scope of their own, named exactly as the grammar named them, and the machine's internals cannot leak in either direction.

It also means a capture may not be called parserText: the parameter is already taken. That is the whole reason the supplied names carry a prefix — with it, nothing an author would naturally write collides — and GRAM4012 is the backstop for a capture that takes one of the fourteen anyway. Before it was refused, the generated code simply did not compile — "no overload takes 2 arguments", in a file the author never wrote, about a grammar it did not mention. §8.2 of syntax.md says why the names are separate arguments rather than one context object.

C# value calls are passed through

Names used by when and => are not looked up or classified by the generator. The call is emitted as written, and #line maps the consumer compiler's diagnostics back to the grammar. Overloads, generic inference, accessibility and result types consequently have exactly their C# meaning. A misspelled @Tini(digits) remains a missing C# name; it is not turned into a generated declaration.

find reads from a reader

find R now has a second overload taking a TextReader, and it is the first thing the retention analysis actually decides rather than merely computes: a rule gets one when a single occurrence of it fits in a window, which is LineExtent anything but Beyond. Start = any* & 'z' gets none — it can give back any of the file, so the window would be the file.

The window is a buffer that is reused: what is before where the parse is now can never be returned to (§4, and §6.3 rests on it), so it is dropped by moving what is left to the front of the same array. A feed of a million occurrences reads through one allocation. It grows only for an occurrence longer than 4096 characters, which the analysis has already established is bounded by the grammar.

It is not a line reader, and that is the part worth knowing. The analysis measures in lines because that is what bounds a feed, but nothing in the window knows what a line is: two occurrences may share one, one may span three, and a grammar with no line terminators in it streams exactly as well.

A result that ran into the end of the window is not an answer yet. This is the whole of what makes a windowed parse correct rather than nearly correct. ['0'..'9']+ stopped at a buffer boundary looks exactly like ['0'..'9']+ stopped by a letter, and a failure that reached the end could have matched with more input. So anything touching the end is provisional while the reader has more: read, and ask again from the same place. Without it, digits straddling the boundary come back as two occurrences — or, since the parse then resumes mid-number, as none at all, which is what the test saw.

It is also what keeps eof honest. The end of a full buffer is indistinguishable from the end of the input to a recognizer, and the only thing that can tell them apart is whether the reader is finished.

A grammar that does not get one is told so, as GRAM5001, at the directive that asked — 'FindStart' gets no overload taking a reader: 'any*' may take more than one line, …, naming the innermost part that does not fit rather than the whole body it sits in, and pointing at §6.3. Information rather than a warning: the grammar is correct and there is nothing to fix. Without it the author meets a call that does not bind and a message about converting TextReader to string, which names neither the rule responsible nor anything they could do about it.

Only where the grammar is the reason. A parse now gets a reader overload when its staged repetitions provide safe continuation or recovery boundaries, as described below. GRAM5001 is reserved for a grammar whose retention prevents that overload; a missing compiler driver is no longer reported as if the grammar caused it.

parse reads from a reader

parse R gets a second overload taking a TextReader and handing back IEnumerable<T> — the elements of the sequence, one at a time, out of input that is never all there at once. Header, then every Row, then Trailer: the envelope arrives in the stream with the records, on its own place, which is what §4.1 case 2 buys.

The stages are driven in order but recognized by the same machine as a string parse. The machine may backtrack across ordinary rule calls; a stream may not go back past what it has handed over. Each stage therefore has an explicit continuation or recovery boundary.

Three conditions, and the second is the interesting one:

  • the result is a sequence (: @T[]), because that is the only shape that comes in parts;
  • every repetition either ends where the grammar says, or is marked recover;
  • every part fits a window, a repetition measured by one of its elements.

The second is the requirement itself rather than a stand-in for it: no element handed over may ever have been wanted back. A repetition whose first set does not meet what follows it stops where the grammar says and nothing has to commit it — that is the ordinary feed, and it streams with no mark at all. Where the two do meet, recover settles it: the complete continuation gets first refusal at an element boundary, after which an element actually read or explicitly rejected cannot be offered back.

It used to demand the mark outright, which was a conservative test standing in for this one. recover is now back to meaning only what it says — survive a bad record — rather than doubling as permission to stream.

A grammar that declares a sequence and does not get the overload is told why (GRAM5001). One that declares no sequence is told nothing: most grammars are not feeds, and a note on every build of every one of them is noise.

A broken record is stepped over in a stream too, both ways §8.2 offers: with a => the rejection takes its place in the sequence, and without one it is dropped and told to the OnRecovered hook. Over a string the repetition backtracks out of the bad element and the machine steps over it; in a stream the driver does the stepping itself, scanning for the synchronization expression through the window and reading more of it when the search runs out of what is held.

The names §8.2 supplies come from the window rather than from a span, and that is not tidiness: a line number counted inside the buffer restarts every time the buffer moves, so a bad record deep in a large feed would be reported near the top of the file. The window counts the terminators it drops and where the last one was, which is what makes parserLine and parserColumn mean the same thing in both modes. There is a test at two thousand records — well past the first window — that says so.

A repetition that cannot tell its own end

GRAM5002. Row* & Trailer where a trailer also reads as a record parses perfectly well — the repetition takes the trailer, the rule fails, the repetition gives it back, and the parse succeeds by the second reading. Nothing is wrong with the answer, and nothing told the author their rule had two readings and backtracking picked one. First sets say when it can happen: what the repeated element can begin with, against what follows the repetition.

An overlap is not a defect on its own, which is why this is not raised everywhere. 'a'+ & 'a' is the same overlap and is perfectly good .Gram: §11 makes backtracking total and a rule is entitled to lean on it. It becomes a defect exactly where the parse cannot go back — a rule declaring : @T[] is asking to be handed over an element at a time, and an element handed over cannot be taken back. So the check runs on those rules and no others.

That measurement is also what the streaming test runs on now. It used to demand a recover outright, because committed element delivery is a property that can be checked; this is the property that actually matters, and having it measured let the requirement become "no overlap, or marked".

The sets are approximate and in the safe direction: a complement, a Unicode category or a C# predicate answers "anything", two of those overlap, and the result is a note rather than a refusal. Being told about an overlap that is not real costs a sentence; missing one costs the thing this exists to prevent.

A rule may say out loud that its result is the text

§4.1 case 4: with no => and no captures, "the result is the matched extent: string gives the text, SourceSpan gives the bounds". Saying so was refused — and refused with a message about matching captures to a constructor, of which there were none.

: @string now means what the same rule without a type has always meant, and is recorded as no declared type at all: a declared one is what tells the emitter to expect a value the machine never builds, which is how this first showed up as generated code that would not compile.

: @SourceSpan is the other half and now builds those bounds through the same parserSpan supplied value used by explicit factories. It may be captured inside another rule. It can also be the value of a publication. It could not while the generated SourceSpan lived in a namespace, where it had to be internal so that two assemblies emitting it would not collide — and internal is what a public method may not return (§6.1). It is emitted into the host class now, where its name is the host's, so it can be both public and safe from collision.

A whole parse leaves the trivia it reads around the rule out of a text value (§6), in every reading: the entry writes down where the rule began and ended, between the trivia on either side, and the value is cut from between the two. Where the rule builds a value from its extent — @SourceSpan, or parserText and parserSpan in its own => or when — the engine, which reads the rule in place of a call, puts its frame to the two marks: its beginning at the first, as the rule is read, and its end at the second before anything is built. One difference between the readings is left. Over characters the trivia woven inside the rule before operands at its end that read nothing is read by the rule, and stays in the value: Word & Word? in a spaced namespace, read whole from ab , is ab over characters and ab over tokens, where the value ends with the last token. Telling those seams apart would cost every seam of the rule a write while it is read.

A lookahead produces what it saw

§3.4 says ?=X "produces X's value (which can be captured) without moving the input", and §3.6 writes the example out:

SmallNumber : @int = n: ?=Number & when @IsSmall(n) & value: Number => value

Neither half worked. n: ?=Number did not parse at all — a capture read only a primary expression, and ?= is a prefix, so the two nested one way round and not the other. And once it did parse, the capture came back empty: the extent was measured from p to p, and p is exactly where a lookahead leaves it.

It now takes the extent from what the lookahead returned, which is how far it got before giving the position back. A negative lookahead still produces nothing, which is not an oversight — it succeeded because what it looked for was not there, so there is nothing to have seen.

What it took was still the text, where §3.4 says the value: n: ?=Number with Number : @int was handed the digits as a string, and the example above, typed, did not compile (CS0029). A lookahead at a rule that builds a value now commits as an atomic group that keeps its records does — its ways back are put out and the call it read stays in the tape — and the capture names that call, as a capture of the call itself would. A guard reads it the same way, which is what the example asks. A lookahead at a pattern, or at a rule whose value is its text, is the text as before. Only the deferred carrier carries it: the direct reader and the immediate carrier hand a rule that captures a lookahead to the deferred carrier, as they did.

Found by reading §3 with a probe rather than by writing a feature: five claims tested, one of them false in two ways.

A rule may take another rule

§4.2, for the arguments that are pieces of grammar:

List(item, sep) = item & (sep & item)*

Start = List(Word, Comma) & ' ' & List(Word, Semi)

By substitution, not dispatch. List(Word, Comma) becomes a rule of its own — List_Word_Comma — whose body is List's with the parameters replaced by what was passed. A parameter is therefore a compile-time thing entirely, and nothing downstream ever meets one: the machine, the capture layout and the retention analysis all see an ordinary rule. That is also what lets a parameter be a recognizer at all, since passing a rule as a value at run time would need a delegate the emitted code deliberately does not have.

Two calls with the same arguments share one specialization, keyed by what those arguments lower to, so a grammar naming List(Word, Comma) twice gets one recognizer. An argument need not be a rule — anything that recognizes will do, including a literal or a character class.

It used to compile and match nothing at all: a parameter lowered to an element set with nothing in it, which is a rule that runs and refuses every input. The parser and the binder had understood parameters all along; it was the normalizer that dropped them.

An argument may also be a number, which is the other half of §4.2:

Digits(n) = ['0'..'9']{n}

Start = Digits(4) & '-' & Digits(2)

A count may name a parameter, and the number the call passed is substituted into the quantifier. The two kinds of argument are told apart where the call is lowered rather than by the parameter's declaration: a number is neither a recognizer nor lowerable into one. An argument that names the caller's own parameter passes the number through, so Pair(n) = Digits(n) & '-' & Digits(n) works as it reads.

The template itself is not in the graph. A parameterized rule is not a rule until it is called — its body names things only a call gives values to — so what is emitted is the specializations. Lowering the template would report a count with nothing passed for it, and emit a recognizer nobody could call.

Refused: a count naming a parameter that was given a piece of grammar rather than a number, which would otherwise repeat zero times and match nothing (GRAM4013). And : item, the result type naming a parameter — §4.1 case 3 said of a parameter, refused where the rule is declared and not again about the specialization.

A call that would specialize for ever is refused too, which §4.2 asks for and which matters more than it sounds. Grow(item) = 'x' & Grow(Pair(item)) wraps its own argument at every call, so there is no repeat to find and no end to the specializing — and the way that ended was a stack overflow, which is not an exception and takes the process with it. An author would have watched their IDE lose the compiler rather than read anything about their grammar. Bounded at 24 nested specializations: generous for a grammar built out of Lex(List(Padded(…))), and passed almost at once by growth.

A result type may name a parameter, in the sequence form. Many(item) : item[] called as Many(Word) is an array of what Word produces — there are no type parameters in the language and none are needed, because a specialization has one concrete argument and so a concrete answer. The pairing is written down where the specialization is made, because that is where the argument is known, and resolved once every rule's own type has been worked out. To a fixpoint, since an argument may itself be a specialization of the same kind; an argument that builds nothing answers string, which is what an extent is.

The scalar : item works too, and is the same thing as §4.1 case 3 — A : B says A's value is B's — so one rewrite covers both. The operand that produces the value becomes a capture and the alternative hands it back, which is the sequence rewrite one size down.

Exactly one operand may produce it. Two is a rule with two answers and nothing to say which, so it is left alone and reported: that is a grammar to rewrite, not a choice for this compiler to make quietly.

A declared parameter type. §4.2 says a C# type makes the parameter a value and anything else makes it a recognizer, and the argument is read as the declaration says. A value is a number, a literal, or a value the calling rule was handed itself — so Digits(n: int) called as Digits(4) works, and the number reaches the quantifier, and Padded(item, pad: char) handed ' ' passes a char. A literal is checked against the declared type through the host (IsAssignable): 'x' is a char and "x" a string, and one that does not fit is refused (GRAM4013).

That ' ' once became a recognizer: the call judged the argument by what it turned out to be rather than by what was declared, so the parameter meant one thing where it was declared and another where it was used. The declaration decides now. What is still refused is a value the parse produces (the row above) — a specialization is made before anything runs, and a captured value exists only while it does.

A C# method may read the input itself

§7.1's second row works:

static bool Blob(ReadOnlySpan<char> input, ref int pos)

Bare @Blob stands where an operand goes, reads whatever it likes, and moves the parser's own position to say how much it took. Saying no is an ordinary non-match: the stack has somewhere to resume and the grammar carries on. Its value is the text it covered, the same as any rule that captures nothing — which is why this form needs nothing new from the host, and why it came first.

The third row now works too — the same call, with an out T value parameter added:

static bool ParseTimestamp(ReadOnlySpan<char> input, ref int pos, out DateTime value)

Notation does not change; @ParseTimestamp is still bare. The host is asked whether the name also has this shape — RoslynSymbolResolver.TryResolveExternalValue; since 2026-09-13 ResolveExternalMethod inspects signatures too, to say whether the call can be made at all (GRAM4025) — and finding one gives the call a rule-shaped identity: a RuleSymbol synthesized with no declaration, its body the same Node.External marked to say it has a value, its type in the ordinary Types map right alongside every rule that wrote : @T itself. Everything downstream — BuildsValue, capture layout, materialization — sees an ordinary typed rule and needed no case of its own; the only place that did is materialization itself, which recovers the value not by trusting the call recognition already made (that one runs speculatively, same as always, and only for the bool and the position) but by re-invoking the method against the position the arena recorded, once a derivation is known to be accepted. That is sound on exactly the contract §7.1 already asks of a recognizer — safe for repeated, speculative invocation — applied once more, later, rather than a new obligation.

A rule whose whole body is one bare value-returning call takes that value directly (Timestamp : @DateTime = @ParseTimestamp) — §4.1 case 3's pass-through, reached by a narrow rule of its own rather than the general mechanism, because the general one settles fit by asking the host an ordinary, separately-cached IsAssignable question, and the type on this side of that question is discovered by the very call being asked about — not knowable from grammar syntax the way every other assignability question's two types are. Asked and settled in the one call that discovers T, using the live symbol rather than a round-tripped display string; a mismatch is not a diagnostic of its own; it simply means the pass-through does not apply, and the rule is exactly as unbuilt as any other capture-less, =>-less typed rule (GRAM4008). Two such overloads with different T is GRAM4015, the one genuinely new diagnostic — there is no existing case of "which of two contradictory shapes did the author mean" to fall back on.

It is trusted absolutely. The ref is the method saying it moves a position; it is handed the parser's own, and nothing copies it away, checks it afterwards, or reasons about what came back. That is written into §7.1 as a contract rather than left implied: a seam that second-guessed the code on the other side of it would cost every parse that uses one and still not make a wrong recognizer right. Reaching into the parse means taking the parse's invariants on with it.

The one consequence: a publication that reaches one gets no streaming overloads. The method is handed a span and told nothing about where it came from, so it cannot tell the end of a window from the end of the input — and, unlike a literal, has no way to say which it hit, which is exactly the distinction Starved exists to carry. It would read a record cut in half as a record that ended.

A C# predicate stands where an element does

§7.1's first row works: bool M(char c) asks the same question about one input item that a range does, so [@IsVowel] is an element set with one C# predicate and merges with characters and categories in the same brackets:

Start = [@IsVowel | '0'..'9']+ & [@IsStop]

The name is written into the generated code as the grammar wrote it, unqualified. The grammar's own @using directives are in that file, which is what they are there for.

Bare @Name is the other contract: a recognizer taking the span and a position. The generator chooses between the two only from brackets versus operand position. Which contract is meant is never asked of the host; whether a method fits it is, and a missing or incompatible one is GRAM4025 on the grammar's line rather than a C# error in the generated file. Among methods that fit, the emitted Name(c) or Name(text, ref p) lets C# select the overload.

Where a C# error lands

On the grammar's line. A => or a when is the author's own C#, and the C# compiler will have things of its own to say about it — that a method does not exist, that the arguments do not fit. Those are said over a #line directive naming where the code was written, so they arrive there rather than inside a machine-written file the author did not open, cannot edit, and is told is auto-generated. §7.6 calls this a condition of the seam working at all, and it is: a seam whose errors land on the wrong side of it is not a seam.

static int New_DotGram_Sum(string parserText, int value) =>
#line 28 "…\CalculatorExample.cs"
                                                                       (value);
#line default

The padding is deliberate. The directive fixes the line; the column comes from where the text sits on it, so the line is written out with no indent of its own and padded to the column the grammar had. An error under one argument of @Add(l, r) then lands under that argument. The @ is skipped when the position is taken, because it is the grammar saying that C# follows and is not part of the C#.

Two maps, because the answer depends on how the grammar reached the compiler. A .gram file maps onto itself — GrammarLineMap, which is pure and lives on the grammar side. A grammar inside a [Gram("…")] attribute maps into the C# file holding it, and that cannot be computed: what the compiler was handed is the decoded value of a string literal, and what the author reads is its spelling, with escapes, quoting and a raw literal's indentation in between. So it is searched for — take the grammar's line, find it in the spelling, and where it occurs exactly once the offset is known exactly. Found twice or not at all, there is no answer and no directive: pointing at the wrong line is worse than pointing nowhere, because the author reads a place with nothing wrong with it and concludes the message is nonsense.

The plain form of the directive, not the span form C# 10 added — the consumer's language version is not ours to assume.

Two things this is not. It is not what places DotGram's own GRAM diagnostics: those carry a position in the grammar and are placed by Generation/Report.cs, which solves the same inline problem by the same search and has done for a while. And it does not extend to the rest of the generated file, which stays attributed to itself — #line default closes every region, so this compiler's own bugs are reported against this compiler's own output.

A method that does not exist

The generator emits calls from when and => even when their C# names do not exist. The consumer compiler then reports the missing name at the mapped grammar location. No partial helper declaration is generated and no intended signature is guessed. One name is told on the grammar instead: a rule's parameter that stands for a piece of grammar, read by the rule's own C#, where nothing in the host answers to the name (GRAM4058); it holds no value C# could read.

A rule can be a sequence of what it is made of

§4.1 case 2 works: Feed : @FeedItem[] = Header & Row* & Trailer & eof hands back the envelope and the records in one array, in the order they were read, with no => anywhere in Feed. Every operand whose value is assignable to FeedItem joins; Row* contributes all of its elements; eof and anything else that builds no value contributes nothing. A rule that declares a sequence and has no operand that fits is refused (GRAM4008) rather than generating a method that returns an always-empty array.

Rewritten into what already worked. Each operand that fits becomes an ordinary capture and the alternative gets a => whose text is a marker, so the captures are numbered, given up on backtracking and rebuilt by exactly the code that does it for a capture the author wrote. The only new thing is what the factory's body says — a body rather than an expression, because a repetition contributes an unknown number of elements and an optional operand contributes none.

The capture goes inside a repetition, not around it, which is where one the author wrote ends up: rows: Row* parses as (rows: Row)* (§10). The other way round the slot holds the text of the whole run.

A repetition's operands arrive as one sequence, in the order they were read. Each operand's capture collects an array of its own, so (Circle | Square)+ once handed the construction every circle and then every square, and (A & B)* every A and then every B: csc read as circle, circle, square. The grammar is still rewritten exactly as before, one capture per operand; what changed is only how the values are put together. The captures of such a repetition are one member of the rule's result, whose slots are gathered in the order their records were written — the walk over the tape reads them in that order already, and a reader by methods logs each record with the slot it came from, which says whose table holds it when the operands' types differ. The immediate carrier keeps one stack per type and so cannot order across them; a rule gathering several types is carried deferred instead.

Assignability is a question for the host, so ISymbolResolver gained IsAssignable — the third thing the grammar half asked about C#, alongside "does this type exist" and "what shape is this method". It has since gained constructors, settable properties, an external recognizer's value and whether an external method can be called in its role. It is asked through the same question-and-answer list as the others, so nothing downstream of it holds a Compilation, and the pairings are collected as a superset from the grammar's syntax the way §7.1's names are. Roslyn's own conversion classification answers it, minus numeric widening and user-defined operators: what joins a sequence is what already is the element type.

This is also the shape a streamed parse needs, since a sequence is the only result that can be handed over one element at a time.

It fixed something else on the way. BuildsValue asked only whether a rule had captures, so Header : @Item = 'H' & eol => @(new Head()) — a rule that plainly has a value and no captures — counted as text, and a capture of it held the characters instead of the Item.

A recovery that builds needs a sequence to build into

rows: Row* where Row captures nothing is one string — the run joined, §7.3 — not a sequence of values, so a => on the recovery has nowhere to put the rejection. It used to emit a factory call against a list that does not exist, which the consumer's compiler reported as an undefined name in a file they never wrote. Now GRAM4010, saying which of the two fixes applies: give the repeated rule a capture, or drop the => and report out of band (§8.3).

Found by writing a test about something else — that an exception out of a => leaves the parse, which §8.2 decided and nothing had checked. It does.

And from a sequence of lines

§6.3 lists IEnumerable<string> beside TextReader, and the difference between them is one character: a reader carries its terminators, and a sequence of lines has had them taken off. So they are put back and everything downstream is the reader case unchanged — one generated method per publication, forwarding.

Which terminator is a decision rather than a detail. , because a grammar's eol matches it, because it is what the lines most often came from, and because putting back what was actually taken off is not knowable: the sequence does not say, and File.ReadLines would not tell it.

A test gives the same feed both ways and compares what comes back, because that is the property worth holding: what a parse answers may not depend on which door the input came in by.

What the window costs

Measured, because streaming that is slower and heavier than reading the file is a feature nobody wants. The same feed, the same grammar, the same parts built, given three ways — benchmarks/DotGram.Benchmarks/StreamingBenchmarks.cs, ten thousand records:

Input Time Allocated Gen2
string 719 us 2653 KB 249
TextReader 433 us 1415 KB 0
IEnumerable<string> 518 us 1884 KB 0

Streaming is faster, which was not the claim being made and is worth understanding: the string case has to hold the input and every part at once, and the array it grows is large enough to be collected as one. The Gen2 column is the whole point — the streamed cases hold one part at a time and never reach the large object heap at all, while the string case pays a second-generation collection for every four operations.

At a hundred records the three are within a fifth of each other, which is the other half of the answer: the window costs nothing worth noticing on input that would have fitted anyway.

A wide feed, which is the shape that pays for itself. Fifty pipe-separated fields a record, twenty-five of them read out into an object — long, int, decimal, DateOnly, DateTime, an enum of the grammar's own and a good deal of text, every one converted by C# the grammar names. The captured fields are scattered rather than the first twenty-five, because a skipped field still has to be recognized and every capture between them is a slot the machine keeps. One million records, about 190 MB:

Input Time Allocated Gen2
string 3164 ms 3279 MB 7000
TextReader 1351 ms 1641 MB 0
File.ReadLines 1472 ms 2710 MB 0

Ten million records — 1.9 GB of feed — read through the same 4 KB window in 13.6 seconds, still with no second-generation collection. The string overload was not asked: 1.9 billion characters is 3.8 GB in one object, which stops being a choice well before that.

The defect the benchmark found, and what it was. Records of differing lengths lost the window: one record per buffer was read as broken and stepped over, silently, until the trailer turned up where a record was expected.

Running out of input looked exactly like not matching. A literal checks p + n > text.Length and gives up without moving p — so a record straddling the end of the window reported its failure at the position the missing character would have gone in, which is before the end of what is held. The driver asks "did this run into the end of the window?" to decide whether to read more, and the honest answer was no.

Failure now carries Starved, set exactly where a bounds check gives up, and both drivers read it beside the position. Only where something streams: over a string the end of the input is the end of the input, and a rule wanting one more character was simply wrong.

Every fixed-width test passed throughout, including a megabyte of records through a 4 KB window — the boundary sat at the same offset inside every record, and that offset happened to be a safe one. There is now a test whose quantity field is one, two or three digits, which walks the boundary through every offset there is.

One more thing fixed on the way there: the recovery scan extended the window from start rather than from from, which threw away the front of the element about to be handed over and put from before the window — a negative index into a buffer.

An offset is a long, a length is an int

§6.3 draws the line and the generated API now sits on the right side of it: Match<T>.Position is a long, because it is an offset into the whole input and an input may be a file no int can index, while Match<T>.Length beside it stays an int, because it is an extent into a buffer and a buffer never is. parserPosition and the OnRecovered hook were already long; the published match was the one place still saying int, and streaming is what makes the difference something other than pedantry.

Widening rather than narrowing, so nothing written against it breaks: an int variable reading match.Position is the one thing that stops compiling, and long is what it should have said.

Nothing is shared between assemblies

.Gram emits everything a parser needs into the consumer's own compilation, and every type it puts in a namespace is internal. That is what makes the claim in the README true rather than nearly true: an internal type cannot be seen across an assembly boundary, so two assemblies that both emit the same type never collide, never bind to each other's, and have nothing to version.

internal alone was not quite enough. An assembly granting InternalsVisibleTo to one that also uses .Gram handed it a second DotGram.GramAttribute, and every use warned (CS0436). Since 2026-09-13 the attributes and enums written into every assembly — [Gram], [GramParserVariant], [GramInclude], [GramSource], GramCarrier and the tooling ones — are [Embedded], with the definition asked of Roslyn (AddEmbeddedAttributeDefinition in GramGenerator), and a type marked embedded is not seen from another compilation at all.

There was briefly a shared mode — [assembly: GramRuntime] published four support types as public and other assemblies bound to them, having found them by looking up a type by name. It was removed rather than fixed, for two reasons.

It reintroduced exactly the skew that emitting into the consumer exists to prevent: an assembly built by one version of the generator would bind to types emitted by another, with no package, version or metadata anywhere to say so. And it was protecting nothing — of the four types, Outcome, Diagnostic and RecognitionResult<T> were referenced by no generated code at all. SourceSpan remains, and has since moved out of the namespace into each host class, where being public collides with nothing because the name is the host's — so a publication can hand one back after all. Three types were deleted then. Outcome has since come back, emitted beside Match<T> in each host as Success, NoMatch and Starved, which is the row the table marks built; Diagnostic and RecognitionResult<T> are still not emitted.

GRAM0001 went with it — it reported two assemblies both publishing — and is the one number that has been used twice: it reports the generator itself failing now. That was free while nothing had been released, and it stops being free at 0.1.0. From there a retired number is not reused, because a suppression written against the old meaning would silently acquire a new one — which is what AnalyzerReleases.Shipped.md is for.

Numbers go by the stage that raises them: GRAM0002–GRAM0012 and GRAM0017 the Roslyn shell (the analyzer's release files), GRAM1xxx the lexer, GRAM2xxx the parser, GRAM3xxx the binder, GRAM4xxx the normalizer, GRAM5xxx the analyses that decide what a grammar gets rather than whether it is one; GRAM6xxx the tooling a grammar is annotated for ([GramClassify]), which the build reports as the editor does. Retired, and listed at the end of diagnostics.md: GRAM3013, GRAM3015, GRAM3017, GRAM3018, GRAM4004, GRAM5006, GRAM5008, GRAM5010 and GRAM5015.

This file talks about the diagnostics a section explains; diagnostics.md is the list. Several there have no section here beyond a mention: GRAM4016 (two alternatives read the same recursive operand twice, a warning), GRAM4017 (two rules each with a with reaching the other), GRAM4018 (a rule nothing reaches, a warning), GRAM4019 (word with no wordboundary), GRAM4020 (a when … is … somewhere other than beside an alternative's operands) and GRAM5003 (a generated method past the size the JIT optimizes, a warning). GRAM5004, GRAM5005, GRAM5007, GRAM5009, GRAM5011, GRAM5012 and GRAM5016 are under A grammar cut in two and Carriers above.

GRAM0001 was retired with the publisher check and has since been taken up again, by the Roslyn shell, for the one thing outside those ranges: the generator itself failing. That is a reuse, and the rule against reusing a retired number stands — it was broken deliberately, because a number nobody had ever seen in the wild was worth less than GRAM0001 reading as "something went wrong before the grammar was reached".

How a message arrives, rather than what it says

Three of these, of which two are now fixed. They are here and not against a particular number because none of them is about a particular number.

  • A position in an inline grammar now lands inside the attribute's string, where it can be placed at all. The offset is into the grammar and what the author looks at is the spelling of it, so the two have to be lined up — and a C# string knows how to turn its spelling into a value, not the other way round. Reversing that properly means re-implementing escapes, verbatim doubling and raw-string indent stripping: three sets of rules, each with corners, all to place a squiggle.

    So it is done by looking rather than by decoding. Take the line of the grammar the diagnostic sits on, find it in the spelling, offset within it. Found once, the place is exact. Found twice or not at all — a repeated line, or one whose escapes were written differently from what they decode to — there is no answer, and the message lands on the attribute as it always did. Never wrong, sometimes silent.

  • An unrecognized character no longer induces a crowd. A stray ~ used to be reported seven times: by the lexer, then by the parser about the same character, twice more about where it ended up, and then by the binder and the normalizer describing the tree the parser had guessed at — including No rule, parameter or capture named '', which is about nothing at all. Now two, and the first one says what happened.

    Two rules do it. At most one error per position, because the second thing said about a place is the first stage's failure told again by the next one; warnings and information are left alone, since two of those in one place can both be true. And nothing from a later stage about a declaration the parser could not read whole — what it would be describing is a guess. That silence is scoped to the declaration, from where it begins to where the next one does, so a rule below it is still checked, which is what implementation.md §0 asks for and there is a test for.

    Recovery validates the complete name: Type = prefix before treating it as a new rule, so a capture such as date: Digit{4} in the damaged expression cannot start another diagnostic cascade. What remains after the lexer error is one parser message at the synchronization point.

  • An ambiguous grammar is only called one where it asks to be streamed. GRAM5002 compares first sets, and only for a rule declaring : @T[] — everywhere else leaning on backtracking is legitimate and saying otherwise would be wrong. A grammar that is ambiguous and never streamed is still told nothing, and whether that is worth an opt-in warning is open.

A generic C# type as a rule's type

Pair : @KeyValuePair<string, int> = key: … & '=' & value: … works, and so does its sequence, : @KeyValuePair<string, int>[] (since 2026-09-14, found by writing RFC 9651). A C# type in type position takes arguments, each a C# type and possibly generic itself. The name is written whole into the generated file, and whether it exists is asked of the host as its definition — KeyValuePair`2 — and each of its arguments, by the binder and ahead of it by the question list alike. From there it is any other declared type: its constructors and properties are matched as §7.3 says. Pinned by the parser, binder, semantic and driver tests.

A rule says what its own refusal says

Expression : @Expression on fail "Expected an expression." = … (§4, §7.5, since 2026-09-11). Where that rule is the refusal, the message is the text as written rather than the list of everything that could have stood there. A rule that vanishes in lowering — one that only forwards — leaves its message to the rule that took its place. Nothing reads the text.

Three shapes still differ between the forms in what the message says, the outcome and the position agreeing: a root read after leading trivia names what it expected on the engine where the methods say its sentence; a root a flat method compiles names it where the reader and the stream say the sentence; and the reader's call of a rule read whole inside braces names it where the engine says the sentence.

Who may call a publication, and from where

internal parse … and private find … declare every method the directive makes with that accessibility: the whole form, the positional and windowed forms, and the reader overloads. Saying nothing is public. The words are modifiers only in front of parse or find, so a rule may still be called internal. A private publication in a [GramParserVariant] reading is private to that nested class.

A position and a window. Beside TryParseR(string input) a positional parse gets TryParseR(string input, int at) — read from at, not required to reach the end — and TryParseR(string input, int at, int length), which sees nothing from at + length on (both 2026-09-13), with their bool forms. A parse that does not say positional gets none of them, whatever reads it. Positions stay offsets into the whole input. Over tokens the first form begins at the first token at or after at; the second cuts only the window into tokens. A publication compiled as a plain method keeps that method for the whole input and is read from a position by a second machine beside it, since it was proved sound only against the end of the input. positional on a find or with yield is GRAM2012, a word before the verb out of order or written after a directive on its line GRAM2013, and in a grammar that names eos GRAM4055.

Readings, and machines that join

The publications of one rule share one machine. A with that substitutes a rule only conditions ask about makes a reading of the grammar, and since 2026-09-10 the parsers of one rule are one machine told apart by the reading's number: Node.Reading tests a bit of it where a condition decided an alternative is there in some readings and not others. Sixty-four readings fit in the word, and more is GRAM4023; a condition that leaves different C# behind in different readings is GRAM4024, since the C# would need telling which reading it runs in.

A publication another one reaches is read by that one's machine (2026-09-13, CSharpEmitter.Joined). A machine holds every rule its root reaches, so the smaller publication needs only an entry into the larger. They are joined only where both are written the same way — flat stays flat, methods join methods, the engine joins the engine — and never where the smaller one streams.

One grammar, several readings and several sources

[GramParserVariant] carries what [Gram] does except which grammar. Both derive from the abstract GramReadingAttribute, which declares the options they share: TargetMethodPartSize, Lexical, Carrier, ConstructionsMayThrow, BufferedText, BufferedBytes, UseSpanCaptures, MaxBufferedInputLength, InitialBufferSize, MaxExtraStacks, LocationType, ExportGrammar and Trace. [Gram] adds the source, DefaultAlias and an optional Name; [GramParserVariant] adds UsePerCallLocations, and takes the name of its class as its one, required argument. Every [GramParserVariant("…")] on a class is a compilation of its own in the nested class it names — Sql.Immediate.TryParseR — taking from [Gram] whatever it does not say. Two wanting one scope is GRAM0006; a name that is empty or not an identifier is GRAM0007.

[GramInclude(typeof(X), Alias = "…")] splices X's grammar into this one under a namespace named Alias, or X's DefaultAlias, or X's name, and brings X's static members into the generated code's scope. It may be written many times, and what it names is walked in turn, together with the base classes. Two under one name is GRAM0008; an DefaultAlias that is not an identifier is GRAM0005. LexemeLibraryExample in examples/ includes a grammar this way. DotGram.Sql's grammars include none: its T-SQL grammar restates the rules it shares with SQL-92.

[GramSource] is the grammar's text, written by the generator onto a class it compiled where ExportGrammar holds — by default, where the class is visible outside its assembly. A base or an include in a referenced assembly has no .gram file in reach, so its text is read from there. A class of a referenced assembly that carries its grammar in [GramSource] is always read from there, the grammar it was compiled from: a .gram file of the same name in the including project is left alone, and GRAM0017 (information) says so where the two differ. This is what the table's referenced-assembly row rests on.

LocationType names an interface declaring void Locate(int at, int length) — with UsePerCallLocations, void Locate(int at, int length, int gapStart) — or a class declaring or inheriting it; every value of that type is handed the range it was read from. An interface is called through the interface, so an explicit implementation serves and a struct is told on the value the rule returns; a class is called on the class. A type that is neither, or that lacks the form its reading needs, is GRAM0011.

A grammar cut in two

[Gram(..., Lexical = true)], or the same on [GramParserVariant], cuts a grammar into a lexer over characters and a syntactic half over token kinds (GramCompiler.Cut, LexicalSplit, TerminalInventory, LexicalAutomaton, LexerEmitter; built from 2026-09-01). The published methods do not change: they take a string and answer as before.

It is a request. Where the grammar cannot be cut it is compiled over characters, as it would have been without the request, and GRAM5004 says which reason applies: no trivia at all, so nothing tells a token from a character; terminals that cannot all be read by one automaton; a find, which hunts through characters for a place to begin, so a grammar publishing one is never cut; trivia not written in braces, whose seam is skipped by the scanner braces ask for; a published rule that is no token of its own over tokens (part of the seam, or a helper a terminal calls); or a published terminal that builds a value, which over tokens only its callers read. A warning, because the two readings are not always the same parser.

What is different over kinds is said too. GRAM5005: a rule of the syntactic half that the methods cannot read — a find, a captured lookahead, a guard handed what a reader cannot give it, a rule called with arguments — runs on the shared engine, the slower rendering. It reads what the methods read: since 2026-10-04 the engine, and the flat method lowered from it, read each call over kinds as if braced, and each choice and repetition of a rule not marked ? too, so a rule's answer stands and what matched inside it is revisited only in a rule marked ?, as §4 says. What holds a repetition marked recover is left open: the repetition tries the complete continuation after it before each turn (§8.2), past the end of its rule. What it synchronizes on is read in kinds as its body is (since 2026-10-05), and a separator only the synchronization names is a token of its own, by the same rule as a body's: longest match, so recover ";;" makes ;; one token that ';' & ';' cannot read, as ";;" in a body would (§4.5). Carried across as written, the engine tested the kinds for a character, never found it, and resumed every recovery at the end of the input. A recovery and a stream were on that list until the buffered rendering learned to read both: over a buffer the methods carry a recover and step a yield one element at a time, and what runs then is the reader's committed reading, not the engine's. GRAM5009: an optional or a repetition that can take, in one token, what follows it, which over kinds nothing gives back.

A terminal the lexer begins and a rule or the host ends (since 2026-09-13). A terminal that is not a regular language — a nested comment, a blob the host measures — is written as a regular beginning followed by one operand that is not: Comment = '/*' & Nested, Blob = '<' & @ReadBlob. The automaton reads the beginning with every other token, and where it stands the rest is measured by the rule over characters or by the host from the position after it. A beginning that can be empty, or is also a token of its own, is refused with GRAM5004. A terminal that is nothing but @M has no beginning, so the host is asked at the start of every token before the automaton; that works and is GRAM5011, a warning. Std.Nested(open, close), as the terminal or its last operand, is begun by its open, and its rest is read by its counter rather than by a machine over characters.

A terminal that names the context. The lexer cuts the tokens before the syntactic half reads anything, so a guard or a when … is … of a terminal sees the context as the publication was handed it, and the lexer hands on the context, the reading and a per-call located argument to every terminal that reads them. Such a guard has to answer alike throughout the parse. Where a terminal's value is built by reading its token again, its guards run again against the context as the parse has written it by then: GRAM5019 warns of a guard naming context there, and a token the second reading refuses throws InvalidOperationException naming the terminal. A grammar whose terminals depend on what the syntax has read is one for Lexical = false.

A window that holds no token is Starved over kinds. A window, or a position, whose text is empty or trivia alone gives the syntactic half no token to read, and it answers Starved there, which is what docs/syntax.md §6.3 specifies; over characters an empty repetition reads it.

Carriers

How a reader carries what it read until the constructions run: [Gram(..., Carrier = GramCarrier.…)], CarrierKind on the grammar side, Machine.Carrier.cs.

  • Auto, the default: compiled exactly as Immediate, byte for byte, and deferred for a machine that carrier refuses, in silence. Where Deferred would hold back constructions the immediate carrier runs — a rule the machine builds read for a derivation that may not stand, or read again after it has answered — the grammar is told: GRAM5016, a warning, where constructions share context with a when, a switch selector or a recognizer (what is accepted and what is built can differ), or a loop rebuilds what it read on every way back (quadratic memory on refused input); GRAM5012, information, for the rest. What counts is not a reading that is given up but one that has already built something: a rule read where the machine constructs nothing — under a lookahead, whose body the machine need not build — leaves nothing to hold back. Until 2026-10 Auto chose the deferred carrier wherever a gate held something back, and naming Immediate over such a grammar was a warning of its own, now retired (diagnostics.md).
  • Deferred (Tape before 0.3.0): records built into values by a walk once the parse is accepted. The carrier a find still takes, and the one that keeps "nothing is built while matching" whole. It was the only carrier that streamed or recovered until the buffered rendering: a machine reading over a buffer chooses its carrier like any other, so a stream and a recover can be carried immediately, building at the end of each rule and releasing what is behind it.
  • Immediate: a construction runs the moment its alternative has been read. A factory is called once per derivation tried rather than accepted, and a parse that fails may already have run the constructions of what it read. No walk at the end, which is about two fifths of a parse.

A carrier is what a reader — the rendering by methods — holds. Where the immediate carrier named refuses a machine, or nothing in the grammar is read by methods, the deferred carrier is used and GRAM5007 says why, as a warning; left to the generator, the fallback is silent.

What re-runs, and when

Two tests hold this, and they only mean anything as a pair: editing a .cs file that no grammar and no host has anything to do with must leave the output step Cached, and editing the grammar must not. The first alone is satisfied by a generator that does nothing at all.

It began as one test that failed. Every parser was being regenerated on every keystroke in every open project, because of one line:

context.RegisterSourceOutput(hosts.Combine(files).Combine(context.CompilationProvider), …);

An incremental generator caches what each step produced and re-runs the next one only when that changed. Host is carefully reduced to strings for exactly this reason, with a comment saying that a symbol compares equal to nothing across compilations — and then a whole Compilation was combined into the same input, which compares equal to nothing either.

The caching is Roslyn's, not ours. A generator keeping its own table of grammar text to generated code would pin compilations, outlive projects and target frameworks, and leak. The pipeline does this properly; what was needed was to stop defeating it.

The compile now happens in a Select rather than in the output step. The transform still re-runs on every keystroke — resolving @Name needs the compilation and there is no way round that — but what it produces is a hint name, a string of C# and a list of reports, all compared by value. An edit that changes none of them leaves the output step Cached, and the consumer's IDE is not handed a new syntax tree to parse and bind, which for a fifteen-hundred-line state machine is the greater part of the cost.

Two things had to become values first, and both are the usual way this fix is written and found not to work:

  • a Diagnostic holds a Location, which holds the syntax tree it came from, so carrying one would make the output unequal whenever any tree was reparsed. Report carries the pieces and builds the Diagnostic at delivery.
  • ImmutableArray<T>.Equals compares the underlying array by reference, so a step handing one out is unequal to itself every run. Hence EquatableArray<T>.

Then the Compilation was narrowed to what it is for, because the transform it fed was not cheap: one compile of the URL grammar was 1.5 ms as written on 2026-08-14, so twenty grammars in a solution is thirty milliseconds of a keystroke and a hundred is a sixth of a second. That figure is for a grammar the size of a URL and has not been re-measured since; the SQL grammars of DotGram.Sql now take the generator tens of seconds, which is why the stages below matter more than they did.

The compilation answers the questions ISymbolResolver asks — whether a C# type exists, whether one is assignable to another, a type's constructors and settable properties, and the shape of a method a grammar names — for the handful of @Name and : @T a grammar mentions. So there are three stages:

grammar + host  ──►  the questions its C# names raise      cached on the grammar
                              │
Compilation ──────────────────┤  the answers, as values    re-runs, and is a few lookups
                              ▼
grammar + host + answers  ──►  the parser                  cached on all three

Editing a C# file re-runs the middle stage and stops there, because the answers it produces are the same ones. Both ends are checked: Asked and Compiled must come back Cached after an unrelated edit, and Compiled must not after a grammar edit — and the check insists the stage ran at all, because Assert.All over nothing passes.

The questions are collected from the grammar's syntax, and are a superset. Not by watching the binder ask, because the binder stops as soon as an answer satisfies it — TypeInView tries the bare name and then each import in turn — so a recording pass would record a different set from the one the real pass needs. Every C# name crossed with every @using is more questions than are needed and always includes the ones that are.

If it is ever not, the answered resolver throws rather than saying no: a question nobody foresaw cannot be answered once the compilation is out of reach, and "no" would refuse a grammar for naming a type that exists. A test drives the four ways a grammar reaches C# and requires the generator not to fall over.

RegisterImplementationSourceOutput — output produced only for real builds, invisible to IntelliSense — is the mechanism for keeping heavy work off the editor's path, and it does not apply here: a generated parser is the public API a consumer writes against, so it has to exist in the editor. It suits a generator whose output nothing references by name, which is why the aspect generator next door uses it for its interceptors and RegisterSourceOutput for its diagnostics.

Streaming, so far

§6.3 emits the streaming overloads only where the grammar provably works with a reused buffer, so the analysis comes before anything else. It has two halves and one is built.

What each rule can take, in lines — Retention.ExtentOf. Three answers, and the distinction that matters is not whether a terminator is consumed but whether anything follows it:

fits a line's buffer
None no path consumes a terminator — a field ✓
AtEnd one may be consumed, and nothing follows — a record ✓
Beyond one may be consumed and the parse goes on ✗

A fixpoint over the graph, like nullability, and for the same reason: a rule's answer depends on the rules it calls and recursion makes that not a tree. It rests on a second fixpoint — which rules can consume anything at all — because that is what tells a terminator at the end of a rule from one in the middle. Guessing that a call consumes made eol & eof two lines, which it plainly is not.

The case it exists for is the field written while thinking about separators:

Text = [^ '|']+                 // Beyond — `+` repeats, so it swallows the file
Text = [^ '|' | '\r' | '\n']+   // None
Row  = "R" & Text & eol         // AtEnd with the second, Beyond with the first

A Unicode category is not looked into and is assumed to admit a terminator. That is wrong in the safe direction: a rule wrongly said to take one loses an overload it could have had, and one wrongly said not to would lose data.

Where the window may move — Retention.PlanFor. A published rule breaks into stages, one per operand of its body, and each is either a piece that fits the window or a committed repetition of pieces that do. A committed run is measured by one element rather than by the run, because the run's length is what streaming is for.

Two things must hold, and each is a different failure:

Feed = Header & Row* recover eol & Trailer & eof   // streams
Feed = Header & Row*             & Trailer & eof   // 'Row*' may take more than one line
Pair = Header & Trailer & eof                      // every stage fits, none commits

The second is not a measuring failure dressed up: with the mark off, the run stops being a stage boundary and is measured as what it is, every row at once — so it names itself. The third is the one measuring alone would miss, where each stage fits the window and there is still no point at which the first may be let go.

Written as a decomposition rather than as "find the recovering repetition" because that generalizes. Two committed runs in one rule are an ordinary feed — Header & Trades* recover eol & Separator & Adjustments* recover eol & Trailer — and a stage may itself be a rule with stages of its own. Neither streams yet: over a string a rule may mark as many repetitions recover as it likes, each with a plan of its own, but a streamed rule marking more than one is refused its reader overload (Retention, reported as GRAM5001), because the driver steps over a bad element one repetition at a time. That is an implementation limit this shape makes visible, and it will bite exactly when multi-stage feeds become worth writing.

Both halves are built and emitting: find and parse take a TextReader where the analysis allows one, the driver reads stage by stage through the reused window, recovery steps over broken elements in the stream the way it does in memory, and a publication refused an overload is told why in a GRAM5001 information diagnostic. A spaced collection streams too — the driver skips the seam §4.5 weaves before each element it hands over, growing the window while the trivia may continue past it — and four thousand seamed records through a window that holds none of them for long is a pinned test. parse reads from a reader above has the mechanics; the analysis above is what the overloads rest on.

What a reader hands back is held to what the string reads, on every shape the analysis lets through (StreamedParseTests): only the marked repetition asks the rest of the rule first, an ordinary one beside it is read greedily, least and most are held, and input left after the last part is refused. A part that collects a value without being a call, and a rule with its own =>, get no reader.

Two shapes that read the same either way are refused a reader all the same, because the check cannot tell them from shapes that do not: space trivia reached through the seam after a part's optional prefix, beside the trivia in front of the part; and a choice of alternatives that call fixed-width rules, whose overlapping first sets are taken for one being a prefix of the other.

What has been measured

Eight of the architecture's claims now have numbers rather than reasoning behind them.

Against Regex. benchmarks/ runs the URL grammar against the same language written as a regular expression, and refuses to time anything until both agree on every part of every input. Re-measured 2026-08-27, after the analysis work that closed the performance programme: generated parsing is faster than RegexOptions.Compiled on all five benchmarked inputs — 104.4 ns against 315.0 for the short URL, 110.1 against 304.0 for the IP-host form, 54.1 against 121.1 on the refusal, 170.9 against 479.9 for the 84-character path, and 277.9 against 306.0 on the one that exercises every named part. Against interpreted Regex, 2.4× to 8.7×.

That last one has been both sides of parity within a day: 1.12× before the predicted-dispatch change, 0.99× after — that change removes work on every input and lost this one to profile-guided block layout anyway — 1.01× once a literal became one span comparison, and 1.10× in the run above. A few per cent on this input is layout as often as it is work, and means nothing without the DOTNET_TieredPGO=0 check beside it. docs/internal/next.md has both.

Measured with --against rather than DefaultJob, and the difference matters for a ratio. BenchmarkDotNet runs each case in a process of its own, one after another, so .Gram is timed at one minute and Regex at another; --against runs all six round-robin in one process, so what the machine does to one measurement it does to the five beside it. Three DefaultJob runs in a row had to be discarded here — the benchmark's own two rows that must agree came out 21% and 28% apart — while --against came through the same conditions with spreads under 6%, and the two independent runs behind the table above agreed to within 0.1 on every ratio.

Those five ask each side for one part, which is the pattern's question and not this one's. A group records where a capture was and cuts its string when somebody reads it; a publication hands back a record with all seven parts already inside it. Asked instead for every part — the honest form of this project's question, and the second pair the benchmark now times — the same five come out 4.21×, 4.16×, 2.48×, 1.62× and 3.77× faster than the compiled pattern. Reading all seven costs this nothing measurable, because they were built before the call returned; it costs the pattern 32% to 52% and 32 to 208 bytes more. Neither pair is the honest one on its own, the first flattering the pattern and the second flattering this, and benchmarks/README.md carries both tables for that reason.

Read the ratios rather than the nanoseconds when comparing against an earlier run, and only for the inputs stable enough to compare at all: the shortest ones move by 9% to 14% between runs of one unchanged binary, and the BCL's own numbers have moved by as much as a third between runs, on code no change of ours touched. Three repetitions is not enough on this machine, and docs/internal/next.md records what believing three of them cost.

Allocation is not at parity and has not been since the parser began to be kept between parses: the short URL costs 264 bytes against the pattern's 1032, and what is left is the result and nothing else — the value, the value nested in it, and one string for each part kept. Measured exactly rather than sampled (--alloc), 2026-08-25, after the deferred-Expected change: 400 → 264 B for the short URL, 480 → 352 for the one with every part, 424 → 392 for host-and-path, 440 → 344 for the refusal, and 2016 → 784 for twenty struct-valued numbers. An earlier version of this paragraph said a rejected URL allocated nothing at all; it never did — it allocated the furthest-failure set, which is exactly what that change stopped rebuilding on every step back.

An earlier version of this paragraph claimed the compiled pattern was beaten across the board, then that it was uniformly 1.2×–2.6× slower. Both were true once: the first, by the generator that compiled each rule to its own method, before it was removed because one automaton is what made backtracking across a rule boundary possible, and it costs what a method call did not; the second, at whatever point between then and 2026-08-24 the numbers above were last refreshed — this project's own accumulated optimizations (possessive repetitions, predictive choices, the parser kept between parses, typed value tables) closed most of the gap without anyone re-running the benchmark to notice. benchmarks/README.md has the fuller table and what not to read into it; CallCost.cs isolates the one piece still costing something on every call regardless of allocation — going through the arena rather than being compiled in place costs about 25% (568 ns against 711 ns, pooled either way) — and never had its own numbers written up before now.

Throughput on a large feed, under What the window costs above: a million wide records read in 1351 ms through a 4 KB window against 3164 ms and 3.2 GB for the same feed as one string, and ten million — 1.9 GB — in 13.6 seconds with no Gen2 collection at all. That is the streaming claim measured rather than argued.

And it does not depend on the size of the file, which is the half of that claim a single run cannot make. --feed reads one feed at two sizes, made a line at a time so that twenty gigabytes need not exist on a disk: 40,000,002 records over 1.41 GiB in 12.9 seconds, and 600,000,002 over 21.17 GiB in 198.1. Fifteen times the input left the working set 4.8 MiB smaller — 83.0 MiB against 78.2 — because what a streamed parse holds is the window and the record in hand. The managed high-water mark is sampled once per million records, so the longer run finds a higher point in the collection cycle (48.3 MiB against 37.8) without the heap having grown; the working set is the column that says so, being the one nothing samples. benchmarks/README.md, What a streamed parse holds.

Pathological backtracking remains possible: a repetition whose body can consume the same input in several ways may take exponential work when failure occurs at the end. Extracting that body into a rule no longer changes the search space. Use an explicit atomic group only where the language really permits commitment. Its commonest form in a real grammar, trivia without braces beside a class that reads the same characters, is told (GRAM4051, syntax §4.5). Over tokens the other common form — an ordered choice whose alternatives read a nested instance of their own recursion before either can be refused, a bracket read as a value and then as a condition — is told too (GRAM4054, syntax §4.7), and on the immediate carrier the reader remembers the recursion's successes beside its failures, so that the nest costs its depth rather than two to it. The historical timings and generated-size table were measured for the removed per-rule generator and must be remeasured against the current automaton before making performance claims.

Adjacent repetitions that can take the same characters — ws* & x? & ws*, or R = 'o'* & 'o'? written k times — are tried in every way the input can be shared between them before a refusal after them is final: about n^k ways, on both machines, and that is the search the grammar asks for. What the direct reader adds to it is fixed. It replays a failed rule from its start rather than resuming a way, and the replay used to read again everything in front of the way it moved: a run of one character scanned to its end and cut back, every turn of a repetition called again, a host recognizer inside it with it. A way cost O(n), and the reader grew n^3.7 where the engine grew n^2.9 (k = 3). Now a replay reads where a giving-back run ended, and steps over the turns of a repetition whose body only recognizes (no value, capture, guard, look or mark), off the tape, so the reader grows as the engine does, a constant three to four times above it (ReaderGiveBackGrowthTests). What still costs more than the engine: a replayed choice calls its alternative again, and a construct in front of the moved way that is neither of the two (a literal, a rule called before it, a turn that builds a value) is read again, so a long head before the repetitions multiplies the search by its length. The n^k itself is the language's: where nothing after the first repetition can want its characters back, { ws* } says so, writes nothing on the tape and reads the same input in linear time.

A hundred lines of C# per line of grammar, and the ratio holds because the machines are what dominate: one state per position a rule can be in, each with its comment saying which notation it came from. The support library at the end is a fixed cost and a small one — 19 lines where nothing streams, 281 where it does, as written on 2026-08-16 and not re-counted since; the lexer, the carriers and the window overloads have been added to what may be emitted after that — so a second grammar in the same project pays the machines again and the support again, since both are emitted per host class rather than shared (§6.1).

Nothing here is optimized for size and it should not be: the file is read by a compiler, and every line of it exists so that no allocation, no virtual call and no closure exists at run time. What the number is worth knowing for is compile time in a project with many grammars — given above as 1.5 ms for the URL grammar, as of 2026-08-14, which says nothing about a grammar the size of SQL's.

Nesting depth: bounded by the arena rather than by the machine's stack, which is what compiling every rule into one automaton bought. CSharpEmitterTests nests a rule inside itself a hundred thousand times and parses it. The figure this line used to carry — about 2700 levels — was the process stack under the generator that gave each rule a method, and has not applied since that generator was removed.

One grammar compiled: 1.5 ms for the URL grammar of examples/, in Release, as of 2026-08-14 and not re-measured since. That is what an editor used to pay per keystroke per grammar, and is why the pipeline was narrowed rather than left as it was. It is not a figure for a large grammar: the generator's time over DotGram.Sql is now tens of seconds (.claude/rules/profiling.md says how it is measured).

Flat lowering: a machine every publication of which needs none of the arena's three uses compiles without Recognize_DotGram, Parser or ParserArena at all — see Backtracking, and where it stops above. Measured on a grammar structurally identical to a repeated-record feed (benchmarks/DotGram.Benchmarks/Flat.cs): 119 ns and zero allocation against 691 ns and 952 B through the shared engine. The gate is per machine and per reachable subgraph, so a recovery or a climb elsewhere in the grammar no longer costs an unrelated publication its flat path, and a value no longer disqualifies one: captures lower to position locals and the construction runs after the whole-input check, deferred exactly as the engine defers it.

The document shape, across the 2026-08 series (benchmarks/DotGram.Benchmarks/Documents.cs: four hundred key-value records, trivia at every seam, span values, a collection in reading order): 287.5 µs and 3.14 MB per parse before the series, 19.3 µs and 46 KB after — fifteenfold in time, sixty-eightfold in allocation, and the 46 KB that remain are the result itself. The seam costs seven percent over the dense input, comments ten. What moved it, in order: machine-scoped lowering gates, a repeated capture recorded once instead of per character, valued publications lowered flat, captured calls compiled as sites, the trivia scanner asking one character for the whole choice and searching for its comment delimiter instead of testing it twice per character, and the give-back doors, checkpoints and locals the CFG work removed. On the notation grammar itself — a tower of recursive valued rules, which is the shape none of the flat work can reach — the hand-written-to-generated ratio stands between 1.3 and 1.7 depending on the corpus file, from about 3 before the series. The last step was two analysis fixes in one day (2026-08-27): a positive lookahead's demand became part of a sequence's first set, which un-poisoned every operand reachable from the inline C# expression and let the tower's optionals settle, and every repetition that may take nothing is now entered through one character, so the general machinery is built only where its body could actually begin. What remains is the completion ceremony — two thirds of the remaining trace, measured to its floor and pinned by two recorded experiments (docs/internal/next.md: eager construction, and the RuleCapture fusion) as the price of honest backtracking — and one enumerated two-token shape, the optional name: probe reading a word the reference after it reads again.

Eager construction — a rule proved Committed && Deterministic at every call site running its => the moment it returns, rather than waiting for the parse to be accepted — was built, measured, and then found unsound and removed. Committed proves only that no alternative derivation can still replace this one through backtracking; it says nothing about whether the suffix that follows will go on to succeed, so a rule could be, and in practice was, constructed on a parse that later failed entirely — a direct violation of §3's "nothing is built while matching." See docs/internal/next.md, "Reverted: eager construction violated deferred-construction semantics" for the full account, including a second, compounding bug in how the region analysis it depended on read atomic-group commitment.

Everything the architecture claims now has a number behind it.

What the tests cover

SemanticTests is a corpus of small grammars run against real input, and grammars that must be refused. SnapshotTests compiles whole grammars and compares each generated file with the one checked in, so a change to code generation is a diff. GeneratorDriverTests drives the generator in memory; the test project also has the generator attached as an analyzer, so it runs over the tests' own sources. RegexDifferentialTests runs matched pairs of a .gram grammar and a regular expression over every string of a small alphabet and requires them to agree — the check that would have found the backtracking defect above in seconds.

UrlTests runs the URL grammar of §7.3 and reads the captures back by reflection; GeneratedApiTests asks the compiler the same questions about the same grammar, so a member that stopped being generated fails the build rather than an assertion.

ExampleTests runs everything under examples/, and its most useful tests are the ones that compare two examples rather than either against a written-down answer: the same expression through a grammar of levels and a grammar of strengths, and the same expression through five rules and one, compared as whole trees by record equality. A number in a test is a number somebody decided; two implementations disagreeing is a defect neither of them can hide.

DiagnosticsReferenceTests holds the code and diagnostics.md to each other: every GRAM identifier in src/DotGram is documented, and every documented one is either in the code or listed as retired. That is a check on the reference, not on coverage. Many diagnostics are raised and asserted by the semantic, driver and emitter tests, but no test checks that each of them is, and "every diagnostic has a test that raises it" — which this paragraph used to say, of twenty-nine — is not claimed for today's hundred and more.

ConcurrentParsingTests holds the concurrency claim to a real race rather than to reasoning about it: a parser of every shipped package, read at once by a large batch of brand-new threads and a smaller batch already several rounds into reading, is required to answer every row exactly as the one single-threaded reading computed before any of them started. Its re-entrant row is a small grammar built for the one shape no shipped grammar happens to need — an action that calls the generated class's own TryParse while the outer parse is still open — read the same way, by many threads at once. What makes this true rather than assumed: every mutable field the pool keeps (CSharpEmitter, around the Rented_/Recycle_ pair for each machine) is [ThreadStatic], and a call reached while a thread is already inside one takes a deeper spare instead of the one already checked out. Memory held per thread is not unbounded, but it is not simply the largest parse that thread ever did either: a buffer grown past the ordinary size is only weakly held once the next few calls stop asking for it (_largeTokensIdle, _spareTokensIdle), so a thread's one large parse is eventually let go rather than kept forever. A handful of statics are shared rather than per-thread — the Expected arrays a refusal's message is built from, lazily built the first time one is asked for behind an Interlocked.CompareExchange — and are safe for the same reason a [ThreadStatic] field is not needed there: the value built is the same regardless of which thread's attempt wins, so a race costs a discarded duplicate array and nothing else. None of this reaches the grammar author's own C#: a =>, when, recovery hook or external recognizer that keeps static state of its own is exactly as unsafe under concurrency as any other static field written from more than one thread, which is what §7.7 already says about a when writing one.