.Gram — the language and its bond with C#

The engine plan lives in implementation.md. Nothing decided there is a decision about the language.

This is a specification, not a report. It says what .Gram is, in the present tense, whether or not the compiler does it yet. status.md says which parts are real.

.Gram is a typed recognition notation for .NET. A grammar describes how a stream of TIn input items becomes a typed TOut result; a source generator turns it into ordinary C#.

This document covers the notation and its seam with C#, nothing else. Every choice here answers to one criterion: each piece of notation means exactly one thing, and that thing is what the notation already means in C# or in .NET regular expressions.


Contents

1. The file and the host class

A grammar lives in a *.gram file beside a partial class:

[Gram]                                  // looks for FeedGrammar.gram
public partial class FeedGrammar;

[Gram("formats/feed.gram")]             // or an explicit path
public partial class FeedGrammar;

[Gram("""                               // or the text right here
    Digits = ['0'..'9']+
    """)]
public partial class Numbers;

The host may be static or not. Everything the generator writes into it is static, so a static partial class is the usual shape; without static the class can also be instantiated and hold instance members of its own beside the generated ones.

A path is matched against the project's additional files ignoring case, on every operating system, so that one project finds the same file on Windows and on Linux. Two files that differ only in case, or in the folder they are in, both match a bare name: that is GRAM0004, and the cure is the path in [Gram("…")], which is never chosen silently.

The grammar file:

@using System;
@using MyApp.Model;
using Lexical;

Header = "H" & '|' & date: Date & '|' & source: Text & eol

@using X.Y; imports a C# namespace, using X.Y; a grammar namespace (§2). The syntax is C#'s own directive, semicolon and all; there is no module system of our own for C# — project references already are one.


2. Two vocabularies: @ and its absence

One rule, no exceptions and no clever resolution:

Written Looked up
Name among grammar rules
@Name among C# symbols (type, method, property)
string, int, bool, char, decimal, … always a C# type — these are keywords and cannot name a rule

@ never qualifies or overrides — it switches vocabulary. There is no fallback in either direction (a bare name that sometimes finds a C# type and sometimes generates one): that is the single source of ambiguity worth removing outright. Only a C# name is generic: @Make<int> is a C# method, and Rule<int>, type arguments after a name of the grammar, is refused (GRAM2016).

Row = ...                // type Row will be generated
Row : @Row = ...         // use the existing C# type Row
Id  : string = ...       // the result is a string

More precisely, @ is a transition into C#, and what it applies to may be a directive as well as a name:

@using System.Text;      // import a C# namespace
using Lexical.Numbers;   // import a grammar namespace

@Encoding.UTF8           // a static C# property
Lexical.Token            // a rule from a grammar namespace

Otherwise using System; and using Lexical; would look identical while resolving in different vocabularies — exactly the implicit ambiguity @ exists to remove.

Of all keywords @ applies only to using, and that is not an exception: namespace, parse, when and the rest are constructs of .Gram with no C# counterpart, so there is nothing to transition into. using is the one directive that exists in both languages. The model is Razor's, where @using, @model and @inherits mean precisely "C# follows".

A name, a call, or a parenthesized C# expression may follow @:

@DateOnly                a C# type
@int.Parse(text)         a C# method call
@(y * 10000 + m * 100)   a C# expression

Those parentheses are not .Gram notation but C#'s own: they are balanced and so delimit the insertion themselves. The generator never parses C# — it only finds the matching ), minding literals, and hands the text to the compiler.

The block form (Razor's @{ ... }) is not supported, and not arbitrarily: the positions that accept C# accept a value, and a block of statements is code. Code belongs in the partial class next door, where there is a debugger and refactoring. The reverse transition (@:, <text>) and the @@ escape are unnecessary: a grammar is never nested inside C#, and a literal @ occurs only inside quotes.


3. Recognition expressions

3.1 Elementary

Each tests exactly one input item.

'x'                     character literal
'x'i                    character literal, case-insensitive
"text"                  string literal (a sequence of characters)
"text"i                 string literal, case-insensitive
['a'..'z']              element set: a range
[Letter | @IsDigit]     element set: a union
[\p{Lu} | \p{Nd}]       element set: Unicode categories
[^ '|' | '\n']          element set: complement (any item except)
any                     any single item

\p{...} is the .NET regular-expression spelling, with the same category names (Lu, Ll, Nd, Zs, Pc, …). Character input only.

What a category holds is Unicode 16.0's general categories (UnicodeData.txt, the version case folding below reads), on every runtime. The generator carries that table rather than asking the runtime it is hosted on, and the parser it writes carries the bits of each set of categories it tests rather than asking the runtime it runs on: .NET Framework's tables are Unicode 8.0 and each .NET release has its own, so a parser that asked would accept different characters on different runtimes, and could be built differently by Visual Studio and by the .NET SDK. A later Unicode version is taken by a new release of the generator, as a behaviour change. A category is tested on a UTF-16 code unit, as every element is: a character outside the Basic Multilingual Plane is two units, each Cs, so \p{L} does not match a letter there. Names are not categories: a rule's or a capture's name becomes a C# identifier and follows C#'s identifier rules as the compiler building it reads them, so a name with a letter beyond ASCII may be taken by one runtime and refused by another, as it is in C# itself.

A trailing i — no space before it — is spelled as in Lark, but it folds less: a character at a time, each character of the literal matches itself and its simple upper and lower case — the simple mappings of Unicode 16.0 (UnicodeData.txt), with no culture sensitivity — and a partner on the other side of ASCII is not taken. So an ASCII letter matches exactly its two ASCII cases and a character with no case (a digit, punctuation) compares exactly as it would without i:

literal matches does not match
's'i s, S ſ (U+017F, whose upper case is S)
'k'i k, K K (U+212A Kelvin sign, whose lower case is k)
'i'i i, I ı (U+0131), İ (U+0130)
"привет"i привет, ПРИВЕТ, ПрИвЕт
'μ'i μ, Μ µ (U+00B5 micro sign, whose upper case is Μ)
'σ'i σ, Σ ς
'ς'i ς, Σ σ
'ß'i ß ẞ (ß has no simple upper case)
'ẞ'i ẞ, ß

The relation is the literal's and is not symmetric: 'ς'i reads Σ, and 'Σ'i does not read ς. It is not Unicode case folding (Lark's, through Python's re, reads ſ as s and the Kelvin sign as k), and the keywords of the formats this is written for — RFC 5234's ABNF and SQL — are ASCII-only in exactly this way. The generator carries its own table of those mappings rather than asking the runtime it is hosted on (whose answer depends on its ICU, on invariant globalization mode, and on .NET Framework's NLS in an editor), so the parser it writes does not depend on the build machine. The generated parser tests the characters named here rather than folding at run time, on every runtime: a letter of an ASCII literal is tested by setting bit 0x20 of the input character and comparing it with the lower-case letter. It attaches to the literal alone — "text"i & X folds only the literal's own case, not whatever X is.

Square brackets in an expression are always an element set, testing one input item. Inside them | is set union rather than ordered choice, and only ranges, characters and references to other elementary rules are allowed. The brackets are required: without them Letter | @IsDigit would be indistinguishable from structural alternation, which means something else. A range has a character at each end, both written as characters are, without i, and stands only between brackets: ['a'..], ['a'..'z'i] and 'a'..'z' are refused (GRAM2014, GRAM2015). A case-insensitive set is written with both cases, ['a'..'z' | 'A'..'Z'].

3.1.1 Built-in rules

Eight ordinary rules, not keywords, that every grammar has without declaring them:

any             one input item, whatever it is — fails only where there is none left
none            zero input items — always succeeds, consumes nothing
eol             one line ending: "\r\n" | "\n" | "\r", CRLF checked first
eof             the end of input — succeeds exactly where `any` would fail, consuming nothing
eos             the end of a segment — see below
trivia          none by default (§4.5)
wordboundary    none by default (§4.6)
word            one whole word, whatever it says (§4.6)

A rule of the same name shadows the built-in one exactly like any other lexical shadowing (§5) — no directive, no mode, nothing declared specially to make it possible. Whitespace handling and keyword boundaries rest on exactly that: trivia and wordboundary are ordinary rules whose only distinction is what the compiler automatically does around them once they are not empty (their own sections, §4.5 and §4.6, cover the insertion and the appended check).

any and none are complements of each other and, along with eol and eof, each stand on their own: eol is an ordinary choice of literals and eof is built the same way ?!any would be, but neither is a call to any under the name any — each carries its own copy of "one input item, whatever it is." Shadowing any therefore changes what any itself matches and nothing else; eof still means the true end of input even in a grammar that redefines any to mean something narrower.

eos, the end of a segment. A grammar that names eos reads a sequence of segments — the arguments of a command line, the lines of a feed — rather than one text. At a boundary between two segments there is no character: any, every literal and every class fail there as they fail at the end of the input, so any*, (?!X & any)*, Std.Quoted and the rest of the until idioms stop at the end of their segment by themselves. eos matches at a boundary and passes it, to the start of the next segment; every segment ends with one, the last included, and eof comes after the last eos. So ["a", "b"] reads as a eos b eos eof, ["a", ""] as a eos eos eof, [""] as eos eof, and [] as eof alone. eol still means a line ending inside a segment, and \n in a segment is a character like another.

Args   : @string[] = items: Arg* => @(items)
Arg    : @string   = ("--output" | "-o") & eos & v: Value & eos => @("out=" + v)
                   | v: Value & eos => @(v)
Value  = any*
parse Args

Such a grammar publishes forms over sequences only (§6.3). A position counts one for every character and one for every boundary, so a position before an eos and after it differ; where a line and a column are asked for (§8.2), and where Parse… throws, a line is a segment and a column the offset in it, both from 1. A refusal at a boundary says end of segment. What is not built yet is refused rather than guessed at (GRAM4048): text captured, bound or published across an eos — capture the parts on either side, or a value built from them, which may be kept: (rows: Row & eos)* holds rows — and parserText of what may hold one, in a =>, in a when and in a recover whose synchronization is not eos; parserInput, which would be the segments as one text, is not supplied. Text around a repetition marked recover is taken to hold an eos, whatever it synchronizes on: what it steps over goes on past the end of a segment, and a when inside it reads what was stepped over between its turns — one whose most is one, X? or X{1}, has no turn before its only one — and so does one in its synchronization, which is read where the element broke. A when in a rule that builds no value is read as if it stood where the rule is called: such a rule may be compiled there, and its parserText is then the calling rule's. The parserText of a left-recursive step (§4.3) is the rule's text from its seed on, steps before it included. A count by a length, X{#q}, is read as any repetition is, and a repetition whose most is nought, X{0} or a parameter's {n} in an instance where it is nought, reads nothing, and one marked recover never recovers. A recover without a => hands OnRecovered (§8.3) the text it stepped over, and is refused unless it synchronizes on eos, which stops at the end of the element's own segment: so a feed written Row* recover eos tells the hook the rest of the bad row's segment and nothing after it, and one that synchronizes on anything else builds the rejection with a => that does not read parserText. An eos grammar split into tokens (GRAM4049) or asked for buffered or byte forms (GRAM4050) is refused as well. U+0000 is how a boundary is read in this version, so no segment may hold it, and a segment that holds it is refused before it is read. A literal or a class item that is U+0000 and nothing else could never match, and is an error (GRAM4047); a range or a category that merely holds it — ['\0'..'\u001F'], \p{Cc} — reads the rest of what it holds. A predicate a class calls (§7.1) is never asked about the end of a segment, and a recognizer of the host (§7.1) is handed the current segment and nothing else: its input begins and ends where the segment does, and the position it is handed and moves counts from the segment's start, a value-producing one's included.

3.2 Composition

a & b                   sequence
a | b                   ordered choice
( a & b )               grouping
{ a & b }               atomic group (commit when the group succeeds)

A connector between operands is always required. .Gram has no juxtaposition: two expressions cannot sit side by side without & or |. That is precisely why rules need no separator (§4.4).

| is ordered choice. What happens once an alternative has matched depends on what is being read: over characters a failure further on comes back and tries the next alternative; over kinds — the syntactic half of a split grammar — it does not, and the first alternative that matches is the one (§4).

trivia is inserted between the operands of a sequence — an empty rule by default, so by default nothing is inserted (§4.5).

3.3 Quantifiers — postfix, as in regular expressions

X?                      zero or one
X*                      zero or more
X+                      one or more
X{3}                    exactly three
X{2,4}                  two to four
X{2,}                   two or more
X{#q}  X{#q,}  X{n,#q}  by the length of a bound text, §3.5.1

Every quantifier is postfix, and together they form one consistent family. Braces immediately following an operand with a numeric or parameterized body are a count; braces in primary position are an atomic group. An operand takes one quantifier, and every repetition is greedy: there are no lazy or possessive forms, so X*? and X+* are refused (GRAM2017). A repetition is repeated in a group, (X*)?, and kept from giving back what it read with braces, { X* }.

The body of X*, X+ or X{n,m} must consume at least one input item per iteration — a build-time check, not runtime behaviour. (A?)* and (?!A)* are rejected by the compiler.

A bound may also be the length of a text bound earlier in the rule, #q (§3.5.1): X{#q}, X{#q,}, X{n,#q}. That count is read when it is reached, in input items, like the others.

Repetitions that can be cut two ways. Over characters a repetition and a choice give back what they read when something after them fails, and an input is refused only once every reading of it has been tried. A repetition that can read the same text in two ways makes that exponential: (X+)* can end a turn after any X of a run, ('a' | 'a' & 'a')+ reads aa as one turn or two, and (Cfws? & Word & Cfws?)+ can give the space between two words to either. An input accepted by the first reading costs nothing more; one that repeats such a text n times and is then refused is read two to the n times, and so is one accepted only by an alternative after the one that reads the run, (('a' | 'a' & 'a')+ & 'b') | 'a'+ & 'c' on aaa…c — a URI template's literal run took three seconds at twenty-four characters, an address list over a minute at twenty-eight. The compiler tells the shape (GRAM4052, a warning), at the rule, with the repetition and the shortest text it reads two ways. There are two cures. Braces, around the repetition or around what it repeats, keep what a turn read — but they can change the language, since a reading the rest of the input needed is no longer offered: {('a' | 'a' & 'a')+} & 'a' refuses aa. Writing the repetition so that every text has one reading keeps the language: 'a'+ for ('a' | 'a' & 'a')+, 'x'* for ('x'+)* (which reads nothing too), X+ for (X+)+, Cfws? & (Word & Cfws?)+. Braces where nothing after the repetition can need a turn read again; the rewriting where it may. The warning is exact for what it can see and blind past a call to a recursive or braced rule, which it reads as one opaque step, so no warning is not a proof; and a look of more than one character or a when that removes one of the readings is not seen to, so a warning there may be wrong — the docs row has the details. Raise it to an error, alone of the warnings, with <WarningsAsErrors>GRAM4052</WarningsAsErrors> or dotnet_diagnostic.GRAM4052.severity = error (diagnostics.md).

3.4 Lookahead

?=X                     positive: X matches here, nothing is consumed
?!X                     negative: X does not match here, nothing is consumed

The spelling comes from .NET regular expressions. ?=X is a recognizer in its own right and produces X's value (which can be captured) without moving the input. ?!X produces nothing. Neither is sugar over the other.

Captured, n: ?=Number holds what n: Number would: the value of a rule that builds one, of that rule's type. Where X is a pattern, or a rule whose value is the text it matched, the capture holds the text the lookahead saw, and a captured ?!X holds "".

Postfix ? and prefix ?=/?! do not clash: the postfix follows an operand, the prefix opens one, and between operands there is always & or |.

SmallNumber : @int = n: ?=Number & when @IsSmall(n) & value: Number => value
Identifier  = ?!Keyword & Letter & LetterOrDigit*

3.5 Capture

name: X

The colon reads "this name — that". What stands on the right is decided by position, and there are exactly two positions:

Where On the right Example
in an expression — a capture a recognizer symbol: Text, value: (A & B), y: Digits(4)
in a rule header or a parameter a type Row : @Row = …, n: int

Usually the difference is invisible, because a rule's name is by default the name of its type (§4): in symbol: Text the right side is the rule Text, and the captured value's type is Text too. They part company where a rule declares a type of its own: after Date : @DateOnly = …, the capture d: Date names the rule Date while the value has type @DateOnly.

A capture cannot take a type: a group and a call are allowed on its right (value: (A & B), y: Digits(4)), and those are recognizers, not types.

A capture may be called anything the grammar can spell, C#'s own words included. A capture becomes a parameter of the method a => compiles into, and one named using, base or checked is written there as C# writes such a name — @using — so that is how the => names it too:

Import : @string = using: Identifier => @(@using)

The escape belongs to C# and stops at its edge: the grammar says using: on the left, because a rule name and a capture name are the grammar's own and nothing there is reserved. Written without the @ inside the =>, it is a C# syntax error against that line of the grammar, which is what it is.

A capture's name is read only where a value goes: after =>, in a guard and as a switch's selector (a mark after with state names no capture, §7.8, and a recover factory is handed only the names of §8.2). Where a recognizer goes — an operand, a side of when … is …, a call's argument outside a value — the same spelling is the rule's, so a capture may be named after the rule it reads: hour: hour & ':' & minute: minute => @(hour + minute) reads the rules hour and minute and hands their text to the => under the same names. A capture's name where a recognizer goes, with no rule of that name, names nothing (GRAM3002); to match the text it captured again, bind it as well and write $q (§3.5.1).

$q: X is not a capture. It binds the text X matched so that $q can match it again (§3.5.1); it adds no member to the rule's type and no name to a => or a when. A name can be both: q: ($q: X) captures the text and binds it, and the two names live apart.

3.5.1 Binding and back-reference

$q: X                   bind: q is the text X matched
$q                      the same text again
X{#q}  X{#q,}  X{n,#q}  repeat X by the length of q

Some constructs close with the very text that opened them: a Lua long bracket [==[ … ]==], a C# raw string, a PostgreSQL $tag$ … $tag$, a heredoc, a Markdown fence. A grammar cannot list the openings, because there are as many as there are texts. It binds the opening to a name and matches that text again.

$q: X binds. It records the text X matched under the name q. It stands where a capture stands, so $q: '"'{3,} is ($q: '"'){3,} — and, as for a repeated text capture, the binding is the whole run, joined. A binding is not a capture: it adds no member to the rule's type, => and when do not see it, and a rule that was text stays text. To have the text in C# as well, capture it too: q: ($q: X).

$q matches exactly that text again: the same items, compared one for one, with no regard to case whatever the binding read ($k: "end"i that read End matches End and nothing else). It is an ordinary operand and composes as one: ?!$q, $q*, r: $q, ($q & X). $q* is refused where q can be empty, as (A?)* is.

X{#q} repeats X by the length of q, counted in input items as {n} and any are — characters, since a binding is read only over characters (one over kinds is refused, below). The forms are {#q}, {#q,}, {n,#q}, {#q,m} and {#q,#r}; the bound is read when the count is reached, and there is no arithmetic ({#q-1} is not a count). A count whose lower bound is greater than its upper bound cannot be met, and simply fails when it is read — {n,#q} with n greater than the length of q, {#q,m} with the length of q greater than m, and {#q,#r} with q longer than r; the lengths are known only then, so it is not an error at build time. #q stands only inside count braces.

A quantifier binds tighter than ?!, so ?!'}'{#d} is (?!'}'){#d}: a lookahead that is then repeated. To look ahead for the whole count, write ?!('}'{#d}).

Backtracking is as in a regular expression. A reference is checked against the text bound on the path being tried; when a greedy binding gives an item back, the references after it are tried again with the shorter text. A binding the author means as a whole is written as an atomic group, { $q: X }.

Scope. A reference sees a binding to its left in the same alternative of the same rule, through groups, atomic groups and repetitions, and also from inside a lookahead (?!$q reads an outer binding). It does not see a binding in a sibling of |, in a rule it calls, in the rule that calls it, inside a constructing group ( … => … ), or in the step of a fold; the name of a binding is not a rule or a capture, and $q never names anything but a binding.

Every route. A reference is an error unless every way of reaching it has bound q before. Two alternatives that both bind q are fine, and share it:

Quoted = ('\'' & $t: Word & '\'' | $t: Word) & " " & $t
Word   = ['a'..'z']+

The same name bound twice on one route is an error, and so is a reference inside its own binding. What a binding reads when it matched zero times follows the same line as a text capture's (§7.3):

Written After zero turns
$q: (X?), $q: X*, $q: (X{m,n}) "", the text of no items
($q: X)*, ($q: X){m,n} "" — the same thing; a repetition of a binding is a binding of the repetition
($q: X)?, ($q: X){0,1} there is no text: the skipping route never bound q

A reference after ($q: X)? is therefore a build error, and the fix is the one in the table: $q: (X?). A repeated binding whose turns are separated, as in ($q: X & ',')*, may be read only within its own turn; read after the repetition it is an error, and the fix is to bind the whole run, $q: (X & ',')*.

What is not supported. A binding is refused inside a lookahead: a lookahead gives back what it read, so there would be nothing to bind. A binding or a reference over kinds is refused too; there a guard does the job: close: Name & when @(close == open). Case-insensitive references, references across rules and arithmetic in counts are out of scope (§11). Not yet supported, and refused with a message saying so: anything that holds a recovery point (§8.2) — a recovery point inside a binding, or a recover on a repetition that holds one — and a binding in what trivia is made of once a grammar is cut in two (§4), which a scanner skips between tokens.

In a grammar cut into a lexer and a syntactic half (§4), a terminal that binds text is one token when its body is atomic ({ … }) and no other token, nor trivia, can match a longer text that begins like it. The lexer starts it on its regular beginning — the opening bracket and its = run, the quotes, << and the tag and the end of its line, as much as an automaton reads — and measures it with its own rule, read from the token's start: its length is that reading, not a longest match. Where that reading fails, the position is lexed again as if the terminal were not there, the same answer a regular token would give. Otherwise that part is read over characters, and GRAM5004 says which token stood in the way and what to write: { } around the body, a competitor kept from continuing the beginning, or both forms in one terminal as alternatives (§7.1). A terminal that begins with nothing an automaton reads — a lookahead, say — is refused by name.

Where such a terminal is a choice of forms of which some bind no text — a raw string beside a plain one — a token none of the binding forms could have been is not read again: the lexer tells, from what each binding form necessarily begins with, that none of them stands at the token's start, and the automaton's reading of the plain form stands. That holds only where the form's first reading is its longest, so the two readings are one; a form that can stop short of its longest reading — a choice inside the braces whose earlier alternative matches a prefix of a later one, a run that gives back to what follows it, a guard — is read again by the rule, as a plain terminal of that shape is. Such a token's value is read the same way: where the terminal has one plain form, a capture of a rule that builds a value, under a => over its captures alone, the value is that rule's reading of the token, handed to the => in its capture's place with nothing in the others'.

A publication over a TextReader or a stream (§6.3) reads bindings as the string form does, bytes included. A reference compares the items where they stand in the buffer, so the buffer keeps a binding's text until the rule that bound it is done with it: a binding holds the input from where it began, as a text capture does. A feed that lets the buffer go at every record (§8.2) still does with bindings in it: a binding there begins after a record does and is read before the next. Over bytes, a length #q counts bytes.

Trivia, where it is woven in, is part of a binding's text — as in a text capture — and is woven around a reference as around a literal. Rules that use bindings are, in practice, rules with trivia = none (§4.5).

Examples. Each recognizes the token; what is made of it (unindenting, unescaping) is the rule's => or C#'s.

A Lua long bracket, for strings and for comments:

LongString = '[' & $eq: '='* & '[' & { (?!(']' & $eq & ']') & any)* } & ']' & $eq & ']'
trivia     = { (Std.Spacing | "--" & LongString | Std.LineComment("--"))* }

A C# raw string, three quotes or more:

RawString = { $q: '"'{3,} } & { (?!$q & any)* } & $q & ?!'"'

The atomic group says every opening quote belongs to the opening, so that """"a""" is not read as a three-quote string that begins with a quote. The last ?!'"' refuses a closing run longer than the opening. Rust is the same shape, with # for the quotes:

RustRaw = 'r' & $h: '#'* & '"' & { (?!('"' & $h) & any)* } & '"' & $h

PostgreSQL dollar quoting, $$ … $$ and $tag$ … $tag$; tags are case-sensitive and cannot start with a digit:

DollarQuoted = '$' & $tag: (Tag?) & '$' & { (?!('$' & $tag & '$') & any)* } & '$' & $tag & '$'
Tag          = [\p{L} | '_'] & [\p{L} | \p{Nd} | '_']*

$tag: (Tag?) that matched nothing binds "", so $$ … $$ is the same rule.

A heredoc whose body starts on the next line, with <<- stripping leading tabs of the closing line:

Heredoc = "<<"  & $tag: Word & eol & { (?!($tag & EndLine) & Line)* } & $tag & ?=EndLine
        | "<<-" & $tag: Word & eol & { (?!('\t'* & $tag & EndLine) & Line)* } & '\t'* & $tag & ?=EndLine
Word    = ['A'..'Z' | 'a'..'z' | '_']+
Line    = [^ '\r' | '\n']+ & EndLine | eol
EndLine = eol | eof

The closing tag is followed by ?=EndLine, a lookahead, so the line break after it is not part of the match: Heredoc ends right after the tag, and parse Heredoc of a text that ends in that line break refuses it. Say & EndLine instead where the break belongs to the token.

A Markdown fence: the closing fence is the same character and at least as long, so "at least as long" is $f followed by more of the same, and needs no comparison:

Fenced  = ' '{0,3} & $f: '`'{3,} & [^ '`' | '\r' | '\n']* & eol
          & { (?!(' '{0,3} & $f & '`'* & ' '* & EndLine) & Line)* }
          & (' '{0,3} & $f & '`'* & ' '* & EndLine | eof)
Line    = [^ '\r' | '\n']+ & EndLine | eol
EndLine = eol | eof

A fence that is never closed runs to the end of the input, so a Line may end there too, without a line break.

A count by the length of a binding says "at least as long" for a run. In reStructuredText the underline of a title is at least as long as the title:

Heading = $t: Title & eol & '='{#t,} & eol
Title   = [^ '\r' | '\n']+

The cost of the "until" idiom depends on its shape. Where the closing is a delimiter that begins with a delimiter character of its own, as in the Lua, PostgreSQL and heredoc examples, a position that does not begin a closing fails at its first item and the scan is linear in the text. For (?!$q & any)*, as in the raw string, every position that holds a quote compares the binding with the text there, so the worst case is the length of the text multiplied by the length of the binding: a crafted input can make it as slow as the opening it was given is long.

Either way the closing is not tried where it cannot begin. Where what the look refuses can begin with only a few characters, the generated parser searches for the next of them rather than reading a character at a time, so the text between two of them costs one vectorized search; the answer, and what a refusal says, are those of the loop as written.

3.6 Guard

when @Predicate(args)
when @Predicate(args) on fail "Expected …"

An operand that consumes no input and produces no value: if the predicate returns false, the whole sequence did not match. on fail "…" after it says what a refusal says where the guard said no and nothing else is named (§7.5).

The keyword is not ceremony. Syntactic position fixes every C# contract: @ParseGuid as an operand is an external recognizer, [@IsLetter] is an element predicate, and when @IsSupported(symbol) is a test on captured values. No C# signature is inspected to decide which one the author meant.

The word follows C#'s own guards: case P when condition and catch (Exception e) when condition make a branch applicable only under an additional condition. Here it says the same thing about the current recognition path. The guard is evaluated while that path is being tried, so it may run more than once and on a path later abandoned by backtracking. A guard inside a lookahead may not yet read a capture made before the lookahead (GRAM4006): the lookahead is a reading of its own and is not handed it. A guard reads nothing, so it needs no lookahead around it — ?=(when @(g)) is when @(g), and ?!(when @(g)) is when @(!(g)).

If the guard names a capture whose value is built by =>, that value has to exist before the guard can be called. The parser builds it at that point and caches it on the current derivation. Acceptance reuses exactly the same value; the construction is not called a second time. If backtracking abandons the derivation, its cached value is abandoned with it. Thus choosing to inspect a computed value also chooses to run that computation during recognition, with the same speculative-effect requirements as the guard itself. A captured sequence is handled as one array in grammar order, including values supplied by recover.

The guard's position is the author's choice and carries meaning. A guard has no outcome of its own — it is an ordinary operand, and its failure means whatever the failure of any operand in that place means:

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

nothing has been consumed before the guard (lookahead does not move the input), so SmallNumber simply does not begin here and a sibling alternative may be tried;

Row = "D" & '|' & symbol: Text & when @IsSupportedSymbol(symbol) & ...

"D" has been consumed — the line is plainly a data row, and failure should produce a diagnostic about the unsupported symbol rather than a silent fall-through to another alternative.

The first reading is what the language does: ordered choice backtracks fully, and the only thing that commits is an atomic group (§3.2), which this guard is not inside — so a failing guard is a non-match and a sibling is tried.

The second is what one would want in the Row case, and the notation has no way to say it — see §11. Note that it is a question about diagnostics, not about parsing: whichever way it is answered, the guard's position stays the author's choice and still decides how much work is thrown away and where the message points.

A guard about the grammar rather than about the input. The same word asks a second kind of question, and the two are told apart by what follows the first operand:

Test = l: Name & "*=" & r: Name & when Version is "2000"

is asks whether two recognizers have a string in common. Both sides are recognizers — a name, a literal, a bracketed choice — and neither is C#, because the question is about their languages and a C# expression has none. A side takes no quantifier: a repetition is named as a rule first, Digits = ['0'..'9']+, and asked about by that name (GRAM2024). A rule's name after when with no is asks nothing, and is refused (GRAM2009); a bare capture there is the C# value it holds, as in any guard. Unlike every other guard it has an answer before anything is read, and it is given that answer when the parser is generated: where it holds, nothing of it is emitted; where it does not, the alternative it stands in is not in that parser at all. Nothing tests it while a parser runs. What gives it more than one answer is §5.1: with substitutes a rule at every one of its uses, so one grammar publishes parsers that answer it differently.

It combines the way C#'s patterns do — is not, and, or and brackets, with and binding tighter than or:

… & when (Version is "2008" or Version is "2022") and Product is not "Azure"

There is no combinator inside a pattern: Version is ("2008" | "2022") already says what Version is "2008" or "2022" would, and the language keeps one way to say a thing.

A C# guard may stand among the conditions, and what is generated is what is left of the whole once the conditions are answered:

Written Generated
a false condition and @(g) no alternative, and g compiled into nothing
a true condition and @(g) when @(g)
a true condition or @(g) nothing — no answer of g could change the reading
@(a) and @(b) when @((a) && (b))

A literal written case-insensitively is every way of spelling it, so "v1"i meets both "v1" and "V1". Three things a condition does not do. It stands only among the operands of an alternative, since removing an alternative is what it is for (GRAM4020). It is answered only where each side accepts a listable set of strings — a literal, a choice of them, a rule that is one — which is what a domain and a range are; elsewhere it says so and keeps the alternative (GRAM4021), because deciding either way would silently change what the parser reads. Each side is read as a whole input, so the word boundary on either edge of a keyword (§4.6) holds and is no obstacle; words with trivia between them are not a listable set, since the trivia has no bound. And a rule every alternative of which it rules out is not an error (GRAM4022, information): a construct removed from a dialect has to be removable, and what is left is a rule that cannot match, so a caller fails where the construct is written. is, not, and and or are keywords only after when, as when itself is.

Computed choice: switch

Field = tag: Digits & '=' & switch @(Kind(tag)) {
    case 0: Text
    case 1: Binary
    default: none
}

The C# expression is evaluated once each time recognition reaches the switch. Its result selects one case directly, without trying other cases. Labels are decimal integer literals (including negative values) or string literals; one switch cannot mix the two. The expression must return an integral type or string. C# checks that labels fit the selector's type. String matching is case-sensitive and ordinal. A null string selects default, if present.

Each body is a grammar expression and may capture values, construct a result, or contain ordinary alternatives. Consecutive labels may share one body. Duplicate labels and multiple defaults are errors (GRAM2021), and so are labels of both kinds (GRAM2022), a switch with no label and a label with no body (GRAM2023). A semicolon after a body is optional. If no label matches, default is selected; without it recognition fails. Failure inside the selected body fails the switch and never tries another case, including default. An enclosing ordinary alternative can still backtrack.

The selector sees preceding captures, context, parserText and parserSpan under the same rules as a guard. It runs during recognition: outer backtracking may reach it again, and side effects are not rolled back. Branch result inference and explicit : @Type contracts keep their ordinary meaning.

3.7 Construction

=> value

Construction gives the alternative its value. It never touches the input. When it runs depends on the carrier (§6.8), and the default is to run it where it is read.

By default, a construction runs as its alternative is read. A grammar that names no carrier is carried as Immediate wherever that carrier can carry it: each construction runs the moment its alternative has been read, and its value is in hand for whatever reads it next. That is once per derivation tried, not once per derivation accepted: a construction runs also for an alternative the parse then gives up, and for the prefix of a refused input. In a grammar with no context and no recovery that is a constant number of times, at most two attempts for each enclosing loop that gives back: the second reading a refusal makes for its message builds nothing but what a guard names, and so does every attempt after a repetition or a choice has given a turn back a second time, until an attempt stands and is built — except in a rule whose own guard asks for its value so far. With a context or a recovery, and in such a rule, nothing is left unbuilt: the second reading builds again, and every way back taken builds what stood before it again, as often as the input gives ways back — for a long refused list, memory quadratic in its length, which GRAM5016 warns of. How many times a construction runs for a reading given up, and whether a value built for it is used again or built anew, is not promised either way: the generator may share an operand two alternatives begin with, or read a rule once where it can prove the reading is the same, and then builds it once where the grammar as written would have built it twice. A construction that only builds does not mind. One that counts, logs or throws does: an exception it throws there escapes the publication (§7.5) — unless the grammar says ConstructionsMayThrow = true, which holds what a construction throws and throws it only where the deferred carrier would have. In a grammar with a context, constructions run interleaved with the hooks that share it (§7.7). The generator says where this can matter: GRAM5016, a warning, where constructions share context with a guard, a selector or a recognizer, or where a refused input can rebuild a list on every turn given back; GRAM5012, information, where a construction can run for text the parser then reads another way or a second time.

Deferred, a construction runs once the parse has accepted. Where a construction must not run for input that is refused or for a reading given up — it counts, logs, or throws — say so:

[Gram("…", Carrier = GramCarrier.Deferred)]

and every construction is deferred until recognition has selected the accepted derivation, unless a later when on that same path explicitly asks for the computed value. In that case the construction runs for the guard and its result is cached. An alternative later abandoned by backtracking does not invoke an unrequested construction.

Where a construction only throws, it can stay immediate. A construction that throws for some of what it may be handed — int.Parse, a division, a lookup that does not find — and has no other effect, can keep the immediate carrier and its speed:

[Gram("…", Carrier = GramCarrier.Immediate, ConstructionsMayThrow = true)]

Then what a construction throws is held, and thrown where the deferred carrier would have thrown it, so the answer is the deferred carrier's, exceptions included (§7.5). The hold costs every construction of the grammar a little whether anything throws or not, which is why it is asked for rather than given.

What a construction can count on

The paragraphs above in one table. A column is the carrier a machine is read with, which is not always the one asked for: left to the generator, a grammar is carried immediately wherever that carrier can carry it, and deferred where it cannot — among the reasons, most repetitions marked recover and the TextReader overload of a plain parse (below the table). Where Carrier = Immediate was named and a machine moved, GRAM5007 says which and why; carriers.md lists every grammar of this repository. "Currently" marks what this version does and does not promise: a later version may change it without notice.

Immediate Deferred
Accepted input Every construction of the accepted derivation runs at least once. Where the same text is read again (a choice trying its next alternative over the same operand, a repetition giving a turn back) it may run again, or a value already built over that text may be used; no number of runs is promised. Every construction of the accepted derivation runs after recognition, once, except where the TextReader overload reads an element again (below the table). A value a when or switch asks for is built when asked, during recognition, and not built again.
A reading given up — a rejected alternative, a turn given back Its constructions have run; their values are dropped, or may be used where the same text is read again. In a grammar with no context and no recovery, at most two attempts for each enclosing loop that gives back, not counting a restart (below the table). Nothing runs, but a value a guard asked for on that reading.
A refused input What was read before the refusal has been built; the second reading that says what was expected builds nothing but what a guard names (with a context or a recovery it builds again). Nothing runs, but values guards asked for.
Under recover The part of a bad element read before it failed has been built; then the recovery's => runs once for the bad element. A bad element builds nothing of its own; the recovery's => runs once for it.
Order A construction runs after every construction whose value it is handed: an element before its rule's =>. Among siblings, currently in input order. The same rule for values handed. Among siblings, currently: in input order, but a value a guard asked for is built first (a: A & b: B & c: C & when @(c > 0) builds C, A, B), and a machine read by the shared automaton rather than by methods can build guarded siblings right to left; a recovering list read whole may build its bad elements before its good ones. The values come back in input order in every case.
A lazy result — yield, a streamed parse of a sequence, find Each element is built before it is handed over, and none after it until the caller asks for the next. A caller that leaves its foreach early builds nothing more. The same.
The TextReader overload of a plain parse (not stream) Carried deferred. An element read up to the end of what the window holds is read again once more input is in, and its constructions run again: currently the last element of every input, and any element ending where a read ends (§6.3). The stream forms build each element once.
An exception Escapes the publication wherever the construction ran — on a reading given up too, and from a Try method as well — unless ConstructionsMayThrow = true, which holds it and throws it only where the deferred carrier would. Escapes only from a construction of the accepted derivation, or from a value a guard asked for. Nothing is caught on either carrier (§8.2); from a lazy result it is thrown by MoveNext, after the elements already handed over.

On the immediate carrier, neither the number of runs nor instance identity is promised (the deferred carrier still builds the reading kept, once). A value in the result may be the instance a construction built in an earlier attempt over the same text, and a construction may run again for text it has already been run over. Where the table or the text above gives a bound or says that a reading builds again (context, a recovery, a rule whose own guard asks for its value so far), that text stands as written. A parse may read part or all of its input again, and the constructions of what it reads again may run again; the table counts attempts within one such reading.

So a construction that only builds may be written for either carrier. One that counts, logs, writes somewhere or throws should name Deferred (or ConstructionsMayThrow for one that only throws), and even then not count on a number of runs where the reader overload reads an element again, nor on the order of siblings. On the immediate carrier it may run more than once and its value may be one built in an earlier attempt. The order a construction is handed values in — an element's values before its rule's — is the one order promised.

Nothing is promised about the order of => among siblings, and one repeat is known. The TextReader overload re-runs => for the last record of the input, and for any record that ends where a read of the reader ends: the result at the boundary is not an answer while the reader may have more, so it is read again once more input is in. This holds on every carrier and under recover too. A construction that counts, logs or writes must not stand where the reader overload can reach it; the stream forms build each element once (§6.3).

It binds to one alternative, not to the rule body — by §3.8 it sits below & and above |. So every branch of a | builds its own result, and no parentheses are needed for that:

Expr = value: Number           => value
     | '(' & inner: Expr & ')' => inner

A name, a call or a parenthesized C# expression may stand on the right (§2). Captures are visible there as ordinary local variables, along with the names the parser supplies itself — parserText, parserSpan, parserInput and the rest of §8.2's table. They are names of the rule like a capture is, so either form reaches them: => @Hold(parserSpan) and => @(Hold(parserSpan)) say the same thing.

Number : int    = ['0'..'9']+ => @int.Parse(parserText)
Point  : @Point = x: Number & ',' & y: Number => @(new Point(x, y))
Add             = l: Expr & '+' & r: Expr     => Add(l, r)

The last line carries an important distinction: Add without @ constructs a type owned by the grammar, whereas @Add would call a host method. Same rule as §2, nothing new. The type is the one the grammar generates for the rule Add — a rule that captures and says nothing else of its value (§4.1 case 3) — and it is built from the values handed, in the order the rule writes its captures. A rule that declares its own type or captures nothing has none to build, and a call with the wrong number of values, or a capture that cannot be the member it fills, is refused on the grammar (GRAM4056).

A nested group may also construct a value:

Fields : @Field[] =
    (value: Field & end: (Separator | eof)
        => @(value.Ended(end.Length)))*
    recover Separator
        => @(new Field.Skipped(parserText, parserSpan.Start, parserMessage))

The group takes its expected result type from the enclosing rule: T for @T, or the element type T for @T[]. No new type annotation is needed here. A group requiring a different result type can be written as a named, explicitly typed rule. Existing inference for rules without a construction is unchanged.

A constructing group owns its captures, just like a named rule. Capture its result outside the group to use that value; its inner capture names do not escape, and its factory cannot refer to captures outside it. parserText and parserSpan describe the group's own match. Plain groups without => keep their existing capture scope. The compiler lowers constructing groups to internal rules, using the same deferred construction, backtracking and location handling. Repeating a group in a typed collection collects its values; a complete (... => ...)* or (... => ...)+ also supports yield under the restrictions below (§6.3).

=> is not always required. When it is absent and captures are present, they are matched to the result type by name — case 3 in §4.1, which covers most rules. => is for where automatic matching does not suffice, or where being explicit is worth it; when present it wins over the other cases.

A construction's value never needs rollback: one built on a reading the parse gives up is dropped with that reading, and nothing the parser keeps is changed by it. How many times its code runs is the carrier's, as the table above says: deferred, for each accepted result it builds (a repeated rule builds one per element) and, over a TextReader, again for the last or a boundary record; carried immediately, also for readings given up.

3.8 Operator precedence

Highest to lowest:

1.  capture, binding,     name: X  $q: X  ?=X  ?!X
    lookahead
2.  postfix quantifiers   X?  X*  X+  X{n,m}
3.  adjacency             a ~ b
4.  sequence              a & b
5.  construction          => expr
6.  alternation           a | b

Capture and lookahead are prefixes of one level and nest either way round: n: ?=X and ?=n: X are both written. A quantifier applies to everything before it on its operand, so name: X* is (name: X)* and ?!X* is (?!X)*. A binding is a prefix of the same level as a capture, so $q: X* is ($q: X)*; a reference $q is an operand, not an operator, and so has no row.

=> binds to a single alternative rather than to the whole rule body, which is what lets each branch of a | construct its own result.

recover (§8.2), with (...) (§5.1) and with state (§7.8) are not in the table: all are optional suffixes on row 2 rather than levels of their own, and with — when both are written on the same operand — always comes after recover, applying to everything to its left, quantifier included. X* recover S with (A = B) recovers X* first and rebinds the result of that as a whole.

Inside a when, a condition (§3.6) has three levels of its own, highest first: A is B and A is not B, then and, then or — C#'s order.


4. Rules

Name = pattern                          // the result type is named Name
Name : Type = pattern                   // the result type is given explicitly
Name(params) : Type = pattern           // a parameterized rule
Name : Type on fail "…" = pattern       // and what a refusal of it says (§7.5)

A declaration always begins with the rule's name — the form without a type is not an exception but its degenerate case, where rule name and type name coincide. The colon here stands in type position (§3.5): a result type is on its right, not a recognizer.

Row  = "D" & '|' & symbol: Text & '|' & quantity: Decimal & eol
Feed : FeedItem[] = Header & Row* & Trailer & eof
Id   : string = Letter & LetterOrDigit*
Date : @DateOnly = y: Digit{4} & '-' & m: Digit{2} & '-' & d: Digit{2}

T[] in type position means "a sequence of T" — the same array notation as C#. In expression position [ opens an element set; the positions do not overlap, just as an array type and an indexer do not overlap in C#.

on fail says what a refusal of the rule says (§7.5), between the type and the body:

Expression : @Expression on fail "Expected an expression." = e: Assignment => @(e)
Word on fail "Expected a name." = [\p{L} | '_'] & [\p{L} | \p{Nd} | '_']*

Without it a refusal names what could have stood where the parse stopped, which is exact and, where what could have stood there is everything an expression may begin with, a list nobody reads. The rule that knows what it is says so instead.

Every reading says it — the direct-method reader, a method compiled flat, and the shared backtracking engine, over a string, a reader and a stream alike. What is parsed is the same either way.

The text is handed back as it stands. Nothing here reads it, so it is a sentence where a sentence is wanted and a code where the caller has its own words in its own languages.

An event and a value, rather than the text alone: what else a rule may want to say about itself is then written the same way, and on is a word everywhere else — between a rule's type and its = nothing else may stand.

Over characters, a rule call is transparent to backtracking. If a later expression fails, the parser may resume a choice or repetition inside a called rule just as it may resume one written inline.

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

matches xy: after Name first answers "xy" and 'y' finds nothing left, the parser retries Name as "x". The same expressions written inline have the same meaning:

Start = ("xy" | "x") & 'y'

Use { ... } where success must commit. For example, { "xy" | "x" } & 'y' fails on xy: once the atomic group succeeds as "xy", later failure cannot reopen choices made inside that group. Rule extraction by itself never introduces such a commit.

Over kinds, a rule's answer stands. In a grammar split into a lexer and a syntactic half (Lexical = true on the host attribute), the syntactic half reads tokens, and there a choice is decided by the token in front of it and never revisited: once a rule has matched, nothing that fails after it sends the parse back into it, and | takes the first alternative that matches. This is what a parser written by hand does at every choice — sees the token, enters, never looks back — and it is the default because it is what nearly every rule over tokens wants. { } there says what is already so.

A rule that needs to give back says so on its name:

NamedType? : @Type
    = ?!Keyword & head: Word & ('.' & part: NamePart)*
    & when @(context.Resolves(ExpressionParser.Dotted(head, part)))
    => ...

Inside a rule marked ?, a choice or a repetition may be revisited when something later in the same rule fails — here the greedy dotted name gives a part back at a time until the guard is satisfied. Its answer still stands at its boundary: a caller that fails after it is not sent back into it. What a caller needs given back it has to read itself: "new" & type: Type & "[]" cannot have Type hand back the [] it read, and is written "new" & type: Type & when @(type.IsArray) instead, which is how one writes it by hand. Over characters ? is accepted and changes nothing, since every rule there gives back already.

This is the language, not the engine. A rule is a function from a position to a match, and the rest of the language rests on that. What a match records is which alternative it came through — one number per call — and that is what lets construction happen after recognition rather than during it (§7.3), what lets a fold collect its steps (§4.3), and what lets a repetition be committed by recover (§8.2). A rule that answered more than once would be a function from a position to a sequence of matches, and every one of those would have to be built again around it.

None of which costs the freedom to refactor. Lifting part of an expression into a rule of its own does not change what it matches, and inlining a rule back does not either: that is what a transparent call means, and it is the property the whole of this section is about. Over characters a rule earns its own commit only by being written inside { }; over kinds it has one, and gives it up only by being marked ?.

4.1 A rule's result

  1. There is => expr — the expression gives the result.
  2. The result type is T[] — a sequence. Every operand that declares a type assignable to T joins it in order; X*, X+ and X{n,m} contribute all of their elements. Everything else contributes nothing: an operand of some other type, and equally a rule that declares no type at all — which is how whitespace, separators and other plumbing are written. A rule with no contributing operand is a build error.
  3. There are captures — they are matched to the result type by name (§7.3). A rule that declares no type gets one generated, named after it, with a member for each capture; a rule may name it as its own, Swapped : Pair, and gives back a value of that type: one its => builds (=> Pair(right, left)), the value of the one operand that produces it, or one its captures fill by name.
  4. None of the above — the result is the matched extent: string gives the text, @SourceSpan gives the bounds. Any other type requires an explicit =>. The extent is the rule's own: the trivia a parse reads before and after a published rule is not in it (§6).
Feed : FeedItem[] = Header & Row* & Trailer & eof

Header, Row and Trailer declare types assignable to FeedItem and enter the result in order; eof declares none and contributes nothing. A sequence of a type the grammar generates, Pairs : Pair[], is joined by the calls of that rule and of rules typed by it. A separator written as Space = [' ']+ is silent for the same reason, and needs no keyword to say so.

What a construction hands back has to be the declared type. Where the grammar can tell that it cannot be — a capture handed back whole, => x or => @(x), that holds text where an array is declared or a generated type where another is, between types that declare no conversion of their own — it says so on the construction (GRAM4056) rather than leaving the C# compiler to say it in the generated file. What a C# expression makes of a capture is the C# compiler's to judge, on the grammar's line (§7.6).

A name, a call and a parenthesized C# expression are allowed in => and when (§2), with captures visible as ordinary local variables:

Number : int    = ['0'..'9']+ => @int.Parse(parserText)
Point  : @Point = '(' & x: Number & ',' & y: Number & ')' => @(new Point(x, y))
Row             = ... & when @(qty > 0 && symbol.Length == 4)

A bare ( … ) is not a C# expression there, but a group of what a rule reads, and after =>, or as an argument of a call in a when (when @F((l))), it is refused (GRAM4065): write the expression as @( … ). (when ( … ) itself is a condition on grammar and wants is.)

Besides captures, the names the parser supplies are always in scope inside => and when: parserText (the matched text, when TIn is a character) and parserSpan (the current rule's SourceSpan) in both, and §8.2's table says which of the rest a => or a recover is handed; a when is handed no more than those two. A name written where it is not handed is refused (GRAM4053) rather than left to the C# compiler. They all begin with parser, which is what that prefix is for — a capture or a rule's parameter may not take one of those names, nor one of the few the parser gives its own parameters (§8.2; GRAM4012), and every other name in the grammar is the author's to choose.

A capture that is optional ON THE PATH reaches a when nullable, and one that every route to the guard writes reaches it as the value itself. The two are told apart by the alternative the guard is in, not by the rule: ('(' & a: X)? & when @(a …) can be reached by the route that skipped the group, so a is X? there and the condition has to say what it means about absence — a is { … } or a?.P == … — as does the construction, which owes the rule a value of its declared type: => @(a ?? ""). a: X & when @(a …) cannot be reached without a, so it is X, however many other alternatives the rule has and whatever they write.

A when runs before its rule is finished, so the two that say what the rule matched say what it has matched so far: from where the rule began to where the parse stands. That is the same extent either way — parserText is the string of it and parserSpan is the two numbers — and it is what lets a guard record where something was read, which is the only thing a => cannot do later. Construction runs children before parents, so anything written inside a construct is built before the construct is.

There is no limit on the size of an expression, but there is a recommendation: once it stops reading at a glance it is better off as a named method in the partial class next door, where it has a debugger and refactoring. The generator neither declares nor resolves that method (§7.4).

4.2 Parameters

A parameter is written like a capture — name or name: Type — because it does the same thing: binds a name to something that came from outside.

Lex(item)               : item   = trivia & item
List(item, sep)         : item[] = item & (sep & item)*
Padded(item, pad: char) : item   = pad* & value: item & pad* => value
Digits(n: int)          : int    = ['0'..'9']{n} => @int.Parse(parserText)
Declaration What it is What is passed at the call site
item a recognizer; result type comes from the call site a rule, a literal or a recognition expression
item: Row a recognizer constrained to produce Row the same, but obliged to produce Row
n: int, t: @Tag a value a literal, or a value this rule was handed itself

An argument is one alternative, or a value: a choice is written in brackets, List((A | B), ',').

Which kind a parameter is follows from §2, with nothing new needed: rules live in the grammar namespace, types in C#'s. That settles an ambiguity otherwise unresolvable: item: Row is a recognizer producing Row, while item: @Row is a ready value of type Row.

There are no type parameters in the language. A parameter's name is allowed in type position instead: : item means "of whatever type item produces", : item[] a sequence of those. That covers every known case, and there is nothing to generalize over at run time anyway: a rule is specialized for each call site, where the argument type is already concrete.

Numbers = List(Number, ',')      // : string — §4.1 case 4, the extent it matched
Name    = Lex(Identifier)        // : string, and for the same reason

A rule whose body is a call does not take the type the call produces. With no =>, no captures and no declared type it is case 4 like any other rule: its own extent. Capture what the call built and hand it on where its value is what is wanted:

Numbers : @int[] = v: List(Number, ',') => @(v)

A value parameter is allowed anywhere a value is expected: in a quantifier count ({n}), in the arguments of @Method, inside @(...). It stands for the literal the call passed, put where the name was written — so Padded(item, pad: char) called as Padded(Word, '!') reads a '!' and hands '!' to the C# it wrote. Two calls passing different literals are two specializations, the same as two calls passing different recognizers.

A number is a value whatever the parameter's declaration says, because a count is where one goes: Digits(n) = ['0'..'9']{n} needs no type on n, and only a value that reaches C# needs one. What a value cannot be is something the parse produces: a specialization is made before anything runs, and a captured value exists only while it does. Pass a literal, or capture the thing and hand it to the =>.

A recognizer parameter never becomes a delegate — specialization means calling it costs exactly what calling the rule directly costs. For the same reason a parameterized rule's name alone is no rule: Std.Nested without its arguments is refused where it is written (GRAM4013), as a call with the wrong number of them is. A recursive parameterized call that would spawn an unbounded number of specializations is rejected when the grammar is built.

4.3 Precedence and associativity

There are two ways, and which to use is a real choice rather than a fallback.

Levels as rules is the default. It needs no engine, no notation and no annotation — a grammar written this way compiles to the same recursive descent as everything else, and for the handful of levels most notations have it is the faster of the two as well: an operator costs one iteration of an ordinary repetition. Use it unless something below says you cannot.

Binding powers (§4.3.1) buy the two things levels cannot: an expression language with many levels written as one rule, and the shapes ordered choice cannot settle. They cost a precedence-climbing engine at run time, which is why they are not the default.

Levels as rules

One rule per level, each calling the next:

Expr   = Term & (['+' | '-'] & Term)*
Term   = Factor & (['*' | '/'] & Factor)*
Factor = Number | '(' & Expr & ')'

Associativity is which side the recursion is on, and there is no notation for it because there does not need to be: a grammar that recurses on the left is left-associative and one that recurses on the right is right-associative, which is what those shapes have meant since BNF.

Sum   = left: Sum   & op: ['+' | '-'] & right: Product  => @Apply(left, op, right)
      | value: Product                                  => value

Power = left: Unary & ('^' & right: Power)?             => @Raise(left, right)

1-2-3 groups as (1-2)-3 and 2^3^2 as 2^(3^2), because that is how they are written.

The two are not written the same way, and the difference is the point. Sum recurses on the left, and §4.3 rewrites a left-recursive rule into a loop over its tails — so the operand at the head is read once however many alternatives there are. Power recurses on the right, where there is no such rewrite, and the obvious form

Power = left: Unary & '^' & right: Power                => @Raise(left, right)
      | value: Unary                                    => value                // no

reads Unary twice: once for an alternative that wants a ^ after it and once for the one that does not. That is a factor of two, and where the shared operand leads back to the rule holding it — as Unary leads back to Power through the parentheses at the bottom of every expression grammar — it compounds: the second reading reads everything inside them twice again. And a flat cost with no nesting is still a cost paid once per alternative: eleven alternatives reading one operand is eleven readings where one would do. GRAM4016 reports the shape wherever the compiler could not share the operand itself.

The two are not the same grammar, which is why it is reported rather than rewritten. Two alternatives prefer every reading of the first over any reading of the second, so a shared operand that can give back will give back to let the rest of the first alternative fit:

Path = dir: Segments & '/' & file: Name | dir: Segments      // a/b/c is a/b and c

is how the last part of a path is split off, and no optional tail says it — written with one the Segments would take a/b/c and leave no file. So where the operand can give back, which form to write is a decision about meaning, and only the author has it.

Associativity therefore belongs to an alternative, not to a rule — that is where the recursion is. A rule ends up with one because a level of precedence is a rule, and mixing two in one rule is legal and a bad idea, the same way it is in any grammar.

In a left-recursive alternative, the leading capture is the accumulator. left: Sum is not a fresh parse of Sum; it is the value built so far — the first time from the alternatives that are not left-recursive, and afterwards from the previous application of this one. Which is to say => is a fold, and both => in the rule above are used: the base builds the first value, the recursive alternative applies once per operator.

A fold follows §7.2 like any other rule. Carried immediately, the default, each step's => is applied as the step is read, on the value so far. Deferred, it waits until the accepted derivation is known: what the match records is which alternative it came through and, for a chain, which step followed which, and a step's => not needed earlier is applied once the whole match has succeeded, in that order.

A guard on a left-recursive step may name the accumulator, the same way any guard names a capture (§3.6): l: F & ',' & y: D & when @(l.Length < 4) => @(l + y) reads l, the value so far, from inside the guard. Doing so is asking for that value early, and §7.2's rule for a value a guard asks for applies here exactly as it does to an ordinary capture: the construction that builds the accumulator runs during recognition rather than after acceptance, is cached, and is reused if the step is kept. Ordered choice may still retry the step or give it up entirely, and a construction that already ran is not undone by that. So a step's => may run more than once, or for a step that ends up no part of the result. A pure construction cannot tell the difference; one with a side effect — a counter, a cache, a write — can, and that is the cost of naming the accumulator from a guard: write such a construction as safe to run speculatively, the same as a guard or an external recognizer already has to be (§7.2), unless it is pure. Nothing here is refused — the generator does not tell a value built early, for a guard, from one built at acceptance — so the choice and its cost are the grammar author's alone.

Several steps of one fold may give the accumulator different names; each sees the value so far under its own. A step written without the leading capture has no accumulator at all, and a guard there naming what another step calls its own reads that spelling however it is already bound outside the fold — a host member, a parameter — not the value so far: there is no implicit accumulator to fall back to, and nothing is refused for it. Where a step does have its own name, a guard that instead spells a different step's name — one that is neither its own name nor a capture this step made before the guard — is refused (GRAM4031): give every step that shares the head the same name, or capture this step's leading call under the name the guard reads.

A rule with no => on any alternative is not folded. It may still recurse on the left: E = E & '+' & N | c: N & '=' & N is a record of what its base captured, and the steps only extend what it matched. Its steps capture nothing — neither the leading call, which would name a value so far that nothing builds, nor anything after it, which a record has one place for and the steps would write once each — and a step that does is refused (GRAM4039). Give every alternative a => to fold, or capture only in the alternatives that are not recursive.

Each application of a fold is a derivation of its own, so parserText and parserSpan (§3.7) see this step's extent — from where the fold began to where this step ends — the same whether they were built at acceptance or early, for a guard.

Three things are rejected when the grammar is built:

  • indirect left recursion — A reaching itself through B without consuming — unless every rule between is only a name for what it forwards. That case is made direct and then rewritten like any other: a rule whose every alternative hands another rule's value straight back (Primary : @Expr = p: Call => @(p) | n: Number => @(n), or a valueless Term = List | Word) means nothing those rules do not already mean, so a leading call to it is the choice of what it forwards and the alternative distributes over that choice. The layered shape every expression grammar is written in therefore works as it reads, left-associatively:

    Primary : @Expr = p: Call => @(p) | n: Number => @(n)
    Call    : @Expr = target: Primary & '(' & args: Args & ')' => @Invoke(target, args)
    

    An intermediary that does anything of its own is still refused. Its operands and its own => would join the tail of the fold, so a step would have to apply two constructions in order against an accumulator that is itself the result of one — arbitrarily many shapes, which is what this rejection is about.

    Every postfix step goes in one rule, and that is not a style choice. Written as several rules that each begin with the forwarder — Member, Index, Apply — making each one's recursion direct leaves them recursive through each other, which no rewrite removes and which is refused for the reason above. One rule whose tail is a choice of steps is the same language and folds:

    Selector = s: Applied => @(s) | s: Root => @(s)
    Applied  = target: Selector & step: Step => @(new Step(target, step))
    Step     = t: ('.' & Name | Subscript | Arguments) => @(t)
    
  • a rule whose every alternative is left-recursive. There is nothing to start from.

  • an alternative recursive on both sides, E = E & '+' & E. Ordered choice cannot settle it: the leading E would be the accumulator and the trailing one would take everything to the right, so what is written left-associative would parse right-associative. A guard or a lookahead after the trailing E reads nothing and changes none of that: E = E & '+' & E & when @(…) is refused the same. Write the operands at the next level down, or say what you mean with §4.3.1.

4.3.1 Binding powers, when levels are not enough

An alternative may state its own strength instead:

Expr : @int = left: Expr & '+' & right: Expr   << 1  => @(left + right)
            | left: Expr & '-' & right: Expr   << 1  => @(left - right)
            | left: Expr & '*' & right: Expr   << 2  => @(left * right)
            | left: Expr & '^' & right: Expr   >> 3  => @Pow(left, right)
            | '-' & operand: Expr              >> 4  => @(-operand)
            | '(' & inner: Expr & ')'                => @(inner)
            | digits: ['0'..'9']+                    => @int.Parse(digits)

One expression language, one rule, and -1-2 is -3 because unary minus is stronger than binary minus — which is said here rather than arranged by how the rules are stacked.

<< and >> mean one thing: at what strength the operand to the right is parsed. << n parses it one level tighter, which makes the operator left-associative; >> n parses it at n, which makes it right-associative. A prefix operator is the same statement with no left operand, which is why it needs no third marker.

Written Is
left: E & op & right: E << n infix, left-associative, level n
left: E & op & right: E >> n infix, right-associative, level n
op & operand: E >> n prefix, level n
left: E & op << n postfix, level n
no marker an atom — a literal, a group, a call

Higher binds tighter. The numbers are the author's, from 0 to 9999, and need not be contiguous: gaps are where a level is inserted later without renumbering the rest.

A step is taken only where the operand before it could not have taken it. The rule is read as an atom or a prefix followed by any number of infix and postfix steps, and a step is entered only at a strength its level allows. After an operand read at strength k — the right side of an infix, the operand of a prefix — the next step's level must also be below k: an operator of level k or more is one that operand would have taken itself, and taking it in the enclosing loop would read the same text grouped the other way. So the grouping is the strengths' own, whatever a when in a step accepts:

E : @string = left: E & '+' & right: E                             << 1  => @(left + "+" + right)
            | left: E & '*' & when @(left.Length > 1) & right: E   << 2  => @(left + "*" + right)
            | digits: ['0'..'9']+                                        => @(digits)

reads 12*3, and refuses 1+2*3: * is stronger than +, so the text can only be 1+(2*3), and the guard refuses 2*3. It is not read as (1+2)*3. A when in a rule that calls this one and reads the value is handed only the grouping the strengths say, the same way. The operand read last is what counts, at whatever strength it was read: one read at 0 — a prefix written without a strength, '!' & E, or a middle operand an optional else did not follow — leaves no step to take. After a postfix step, or anything else read last, a step may be anything the strength being read allows; so may it after an alternative that ends with its operand on one reading and with something else on another ('~' & E & '!'?). A strength binds the operand an alternative ends with, a when or a lookahead after it included, since neither reads anything; an operand the alternative may or may not end with — inside an optional, a choice or a repetition — is read at 0, and the compiler says so (GRAM4042).

A rule uses one convention or the other. Levels as rules and binding powers in one rule would be two answers to the same question, and the compiler refuses it rather than choosing.

4.4 Rule separator

There is none and none is needed: a connector between operands is mandatory, so an expression can never be "continued" by the next rule. An identifier followed by =, : or (, in a position where the current expression is already complete, is always a new rule. It cannot be a capture: a capture must follow & or |, and there the expression does not count as complete.

4.5 Trivia — insignificant whitespace and comments

The rule trivia is always inserted between the operands of a sequence. It is empty by default, so by default nothing is inserted:

// built in (§3.1.1)
none                  = any{0}                 // zero repetitions: succeeds, consumes nothing
trivia                = none

// the grammar's own, over the standard library (§5.2)
Whitespace            = Std.Whitespace*
WhitespaceAndComments = (Std.Spacing | Std.LineComment("//") | Std.BlockComment("/*", "*/"))*

A grammar to which whitespace is insignificant redefines one rule:

trivia = { WhitespaceAndComments }

The braces make what trivia reads stay read, and are worth writing wherever nothing needs trivia to give a character back; why is below. No directive, no mode: it is an ordinary rule, and none is expressed in the language itself as any{0} rather than by a new primitive.

At every seam between the operands of a sequence. The turns of a repetition are such a seam wherever the thing repeated is itself a sequence — A & (S & A)* is how one writes A S A S A, and the join that wraps around is no different from the ones inside. An author who wrote S & A has already said that a space may stand between S and A; refusing one between A and the next S would be the same seam answered two ways.

Not before a when. A seam separates two readings of text, and a guard reads none: there is no token on its far side for trivia to stand in front of. So a guard evaluates where the operand before it ended — which is also what its parserSpan says — and an alternative that ends in a guard ends where its last reading operand did, exactly as its guard-free twin does.

trivia = { Whitespace }

Pair    = Word & Word            // matches "ab cd"
List    = Word & (',' & Word)*   // matches "a , b , c" — the repeated part is a sequence
Several = Word*                  // matches "abcd", and stops at the space in "ab cd"
Entries = Entry*                 // Entry builds a value, so this is a list: "a; b;"

A repetition of a valued rule is a list, and lists are spaced. Entry* in a rule declared : @T[] is the collection §4.1 case 2 gathers, and a grammar that separates its operands with trivia separates its collections the same way: entries: Entry* reads a; b; as readily as a;b;. Valuedness is what draws the line, and it is the author's own declaration doing the drawing: a rule that builds a value is a thing being collected, and things stand apart.

A repetition of anything valueless gets nothing, and that is what keeps lexemes whole. A repetition is how a lexeme is written — Digits = ['0'..'9']+, Name = Letter+ — and spacing those turns would make 1 2 one number and a b one name in every grammar that ignores whitespace. A valueless operand is a fragment of text rather than a thing, so its turns have no seam between them.

An optional is left alone for a reason of its own: it has no second turn, so it has no seam. So is a repetition of a choice, which is what keeps trivia's own usual shape — (Whitespace | LineComment | BlockComment)* — from being asked to space itself.

What is left over is a spaced run of a single valueless thing, which nothing can infer: Word* and Digit* have the same shape and only the author knows which is a list. So the author says which, and trivia is an ordinary rule that may be named:

Attributes = Attribute & (trivia & Attribute)*     // a list of one thing, spaced
Digits     = ['0'..'9']+                           // a lexeme, not

A run with a separator needs none of that, because the thing it repeats is a sequence:

List(item, sep) : item[] = item & (sep & item)*    // "1, 2 , 3"

Trivia that can swallow more than one character at a time — comments — is worth making atomic:

trivia = { (Whitespace | LineComment | BlockComment)* }

The braces say that what a comment swallowed stays swallowed. Without them §11's ordered choice means a failing parse may re-read a comment's interior as syntax, one give-back at a time — legal, useless, and expensive. With them the engine can also prove that a spaced list never needs to hand a completed element back, which is the difference between a syntax error reported in milliseconds and one reported in minutes. Whitespace-only trivia needs them too: before an optional part a lexeme may end with, the spaces can be read by the seam inside the lexeme or by the one after it, two readings of every such lexeme unless the trivia or the lexeme is braced.

And wherever what stands beside a seam reads what trivia reads, braces are what keeps a refusal from taking minutes. trivia = ' '* beside Field = [^ ',' | '\n']+ — the first way a CSV file is written — gives every run of spaces next to a field as many readings as it is long: each space is the field's last character or the trivia's first. Trivia without braces offers every one of them back. An input that is accepted takes the first reading; one that is refused is refused only once every combination at every seam has been tried, which is exponential in the number of seams — a few rows of a malformed file take seconds, six take over a minute. trivia = { ' '* } reads each run once. The compiler tells the shape (GRAM4051, a warning): trivia without braces whose characters a class, any or a negated class at the edge of an operand beside one of its seams also reads. Braces on the trivia, or on the rule it forwards to, silence it; joining the two with ~ (below) leaves no seam to tell. The end of a braced operand keeps what it read and is not told, and a negative look in front of an element takes what it refuses out of it: (?![' ' | ','] ~ any)+ reads no space.

Braced trivia is read by a scanner, which reads what it calls in place and so cannot follow a rule that reaches itself. A comment that holds others is the one such rule trivia needs, and is written Std.Nested("/*", "*/") (§5.2), which a scanner reads with a counter.

And a rule that spells out a lexeme is worth making atomic for the same reason:

DecRun = { Digit & ('_'* & Digit)* }
Name   = { ['a'..'z' | '_'] & ['a'..'z' | '0'..'9' | '_']* }

A rule like this is meant to read to the end of what it recognizes and never hand a character back — that is what its author means by it, and what anyone writing the parser by hand would do. Written without braces the grammar does not say so, and nothing downstream can prove it: what may follow a name includes a letter, because trivia may match nothing, so a reading one character shorter cannot be ruled out. The proofs that rest on it then go too — a repetition whose end is not settled writes a way back at every turn, and two alternatives that begin with the same lexeme cannot be read as one.

It is a choice and not a rule of style. Braces commit the first reading, so a rule that is supposed to give characters back must not have them:

TypeName = Word & ('.' & Word)*      // no braces: a dotted name is a type only as far
                                     // as it resolves, and the rest is member access

The grammars that ship hold both, and the difference between them is not in their shape — it is in what the author meant. That is why the compiler diagnoses only the narrow shape above: it can see that the reading is unsettled, and cannot see whether that was the intention.

Switching per block is the shadowing from §5, not a separate mechanism:

trivia = { WhitespaceAndComments }

namespace Lexical
{
    trivia = none                              // whitespace is significant here

    Identifier = ['a'..'z' | '_'] & ['a'..'z' | '0'..'9' | '_']*
    Number     = ['0'..'9']+
}

namespace Syntax
{
    using Lexical;

    If = "if" & '(' & cond: Expr & ')' & then: Statement
}

Scoping is lexical: a rule uses the trivia visible where it is declared, not where it is called. A rule means the same thing wherever it is used.

Which trivia is visible is looked up in two steps. First the namespace's own chain — the namespace, then each one around it, out to the top of the file — and the nearest trivia declared there wins. Only where none of them declares one does an import count: a trivia declared by a namespace the chain imports, the nearest scope's usings first. Where neither finds one, trivia is the built-in none. The chain coming first is what makes the example above read whitespace in Syntax: using Lexical; brings in Identifier and Number, and the trivia = none beside them is shadowed by the trivia declared around Syntax. And it is the same wherever the using is written — at the top of the file or at the top of a namespace block, as §5 allows — so a grammar that declares no trivia of its own and imports a namespace that does reads with the imported one at either placement. Two imports at one scope that each declare a trivia are ambiguous and refused (GRAM3022): the order of the usings never decides between two imports (§5). Declaring the one meant settles it, trivia = Spaces.trivia.

trivia must be nullable — it has to accept empty input, or the build fails. That condition is what makes unconditional insertion safe: a second application consumes nothing, so nothing is ever doubled and no rule of the form "insert after a literal but not after a structural call" is needed. The single exception is one insertion at the start of a published rule, for leading whitespace.

When trivia is empty the insertions are dropped entirely during normalization: nothing of them survives to run time.

A silent failure is possible here — a lexical rule that ended up by oversight in a namespace with non-empty trivia will quietly accept i f as if, and 1 . 5 as a number. The compiler cannot tell a lexeme from anything else by its shape, but it tells the one shape that is almost never meant (GRAM4043, a warning). A rule declared where trivia is not empty is told when:

  • every operand it reads tests one input item: a character class, any, a literal of one character, eol, a call to a rule that builds no value and is itself one such item (Std.Digit, Letter), a back-reference, or a group, ?, *, +, {} or capture of those;
  • at least one of them is a class or any, so that '<' & '>' is left alone;
  • a seam is woven between two of them, in a sequence or between the turns of a repetition of a sequence; and
  • the rule does not name trivia itself.

Std.Digit+ & ('.' & Std.Digit+)?, Letter & (Letter | Digit)* and '\\' & any are told; "if", ['0'..'9']+, Word & ('.' & Word)*, a rule under trivia = none or joined with ~, and a specialization such as List(['a'..'z'], ',') are not. Braces do not silence it, because they commit a reading and keep every seam; write ~ between the parts (Std.Digit+ ~ ('.' ~ Std.Digit+)?), declare the rule where trivia = none, or, if the space is meant, write trivia there. The rules trivia is itself made of are not judged.

What it does not catch. A run is not one item: Std.Digits & ('.' & Std.Digits)?, which reads 1 .5, and Word & ('.' & Word)* have the same shape, and the second may be the dotted name TypeName below, written on purpose. Neither is told, so a number or a string built from runs and quotes is written with ~ by hand:

Point = { Std.Digits ~ ('.' ~ Std.Digits)? }     // 1.5, and not 1 .5
Text  = '"' ~ body: Body ~ '"'                    // " a" keeps its space

The converse costs a warning: a single-digit toy, Digit & ('+' & Digit)*, written to be spaced, is told too; naming trivia in it (Digit & (trivia & '+' & trivia & Digit)*) says that the space is meant.

~ — where trivia may not go

a ~ b is a & b with no seam between them: what b matches must begin exactly where a ended. It binds tighter than &, so a & b ~ c is a & (b ~ c).

It exists for the operators that share their characters with something else. A shift is two > with nothing between them, and a nested type argument list closes with two that each belong to a different level:

Shift = left: Shift & '>' ~ '>' & right: Additive
Type  = Name & ('<' & Type & (',' & Type)* & '>')?

x >> 2 shifts, List<List<int>> closes twice, and a > > b is refused — which is what C# and Java answer, and what C++ answered only from C++11.

Writing the shift as ">>" instead cannot work, and the reason is worth stating because it is the whole argument for the operator. A literal is a terminal, a terminal is a token, and a token cannot be half spent: with >> in the inventory the scanner takes both characters and the inner argument list, which wants one >, is handed a shift. There is no order of alternatives that recovers from that, because the choice was made before the parser was asked. With '>' ~ '>' there is no >> for the scanner to make.

One meaning in both halves of a split grammar (§4). Over characters ~ is simply the seam withheld: with nothing woven between them the operands are adjacent because there is nowhere for anything to stand. Over kinds the trivia was skipped before the tokens were made, so two operands are two tokens whether or not anything stood between them — and the question is asked of the tokens themselves, each of which records where it began and how long it is. The same grammar reads the same language either way, which is the point.

Inside a lexical namespace it says nothing, and is allowed for that reason rather than refused: trivia = none there means there was never a seam to withhold.

4.6 Keyword boundaries

wordboundary is a built-in rule (§3.1.1), none by default, naming the characters that continue a word:

wordboundary = ['a'..'z' | 'A'..'Z' | '0'..'9' | '_']

Once it is not empty, every string literal whose characters all fall in that class is guarded on both sides: it may not be followed by a boundary character, and it may not be preceded by one. The first keeps "if" from matching the start of iffy; the second keeps it from matching the end of stiff — the reading backtracking would otherwise find, where an identifier hands characters back and a keyword matches mid-word. A word literal is a lexeme, and a lexeme is whole. Whether a literal qualifies is decided when the grammar is built: "if" gets the checks, "(" does not.

Read over tokens, the lexer asks the first question of the character after a keyword's token: where it continues a word, the token is not the keyword, whether or not another pattern covers the longer word. gogo is never two "go"s, nor gox "go" and 'x'; where a class matches the same token, the token is still that class. The second question is not asked there: a keyword glued to the number before it, 1MB, is two tokens.

Same shape as trivia (§4.5), and for the same reason: a rule, ordinary shadowing, and the insertion dropped entirely while the rule is empty. A regex or a feed grammar pays nothing; a language grammar pays one line. The boundary may name its class through another rule — wordboundary = WordOrDigit — and Unicode categories count as classes.

A lexical namespace shields it. A namespace whose own trivia is empty (§4.5) does not inherit a wordboundary declared outside: its literals are the parts of one lexeme, not lexemes standing next to each other, and the 'u' of an escape sequence must not be told it cannot precede a hex digit. A namespace that declares its own boundary beside its empty trivia keeps it — that is the scannerless keyword grammar, SqlReadOnly in the examples being one.

The boundary checks go before the trivia insertion. The other order would ask whether a letter follows the whitespace rather than whether it follows the keyword.

word

The other half of the same fact. wordboundary says what a word is made of; word is one whole word made of it, whatever that word says:

OptionName = word           // FILLFACTOR, DATA_COMPRESSION, ONLINE, PAD_INDEX, …

A boundary is a class of characters, so one that can match nothing (['a'..'z']?) would make word a run that never ends; word over it is refused at the boundary's declaration (GRAM4001).

It is a run of boundary characters that does not stop short of one — maximal by construction, so word cannot read half of FILLFACTOR however the parse backtracks — and it gives back the characters it read, like any rule that names none of its parts. Each namespace's word is that namespace's own: a boundary is declared per namespace (above), and a word is a run of whatever the boundary in scope says continues one.

It is for the places where a language admits a word and does not care which: an option's name inside brackets, a permission spelled out of words the language reserves, a name belonging to some other catalogue passing through this one. Written out, those become a list of every word the specification happened to have — a list that is wrong the day the specification grows one, and that says a catalogue where the grammar meant a word. Where only some words will do, the shape is a lookahead and not a list:

PermissionWord = ?!PermissionEnd & word
PermissionEnd  = "ON"i | "TO"i | "FROM"i | "WITH"i | "CASCADE"i

word in a grammar with no wordboundary is GRAM4019: it would be a run of nothing.

Over kinds it is a kind test. Where the grammar is cut in two (§4) the boundary is gone with the rest of the lexer, and being a word is a property the token kind already has — so word becomes one range test over every kind that is a word: a keyword, and a class every character of which continues a word. It reads exactly one token there, which is what it read over characters too.

4.7 Alternatives that decide after a nested construct

Ordered choice decides by trying: A | B reads A, and where A fails anywhere, B is read from the same place, with nothing kept of what A read. That is linear as long as the token that refutes A comes early. Where two alternatives share a prefix that holds a nested instance of the recursion the choice stands in — a bracket whose content is read by the tower the choice belongs to — and the token that tells them apart comes after that instance, the instance is read once per alternative, and inside it the same choice does the same at the next level: two to the depth. The 1992 BNF's predicate is the shape, written as it stands:

BooleanPrimary = Predicate                                  // a row and its tail: (CASE WHEN c THEN 1 END = 1) read as a value, refused at =
               | '(' & SearchCondition & ')'                // then read again as a condition, at every level

Every grammar that reads a bracket as one thing and then as another has it — a row against a bracketed value, CAST( against a call by that name, a subquery read and then declined — and a hand-written parser avoids it one way: it reads the shared text once and decides by what follows. The compiler finds the shape and says so (GRAM4054, information), at the rule, with the alternatives and the shortest text after which both go on reading the same construct. Nothing has to be done about it: over tokens, on the immediate carrier, the reader then remembers where the first rule of that recursion both alternatives enter at one token succeeds, and what it built — two integers a rule and a token and a bit in the memo word, beside the memo of failures §6.5 describes, under the same contract (§7.2) — so that a second entry at the same token is answered without reading, and every level is read once. What it costs is a store at each success of that rule of four tokens or more while the reader is inside the earlier alternative of the choice — it counts them, so a success is stored while an earlier alternative is being read, whether or not it wins, and not otherwise — and 8 bytes a token for it; where some flagged alternative is read in place rather than called, or stands in a clone of its rule the reader could not match to the choice the analysis named, every success is stored, and the carriers report says so. Over characters, carried deferred, in a trace build, where a construction may throw, inside a lookahead and for a rule that reaches its context nothing is remembered, and the message says so: there the shape costs its depth's power until the grammar is rewritten.

The rewrite needs no memo and is what the message shows. Factor the prefix the alternatives share, A & (X | Y), where it is one operand (GRAM4016, §4.3, which the compiler does itself where it can prove the operand has one reading). Where the alternatives call different rules over overlapping text, read the union once and classify after: one bracket rule that reads what a bracket holds through the top of the tower, and a switch (§3.6) on what it read or on the token after it — a switch enters one case and records nothing for the others, so a refusal names what it named. Or read the value first and then at most one tail, the way an operator loop reads its operand before the operator. Which to prefer is measured, not assumed: on SQL-92 the rewrite that reads a bracket once cost more on accepted texts than the memo does, and the grammar stays as written.

The analysis is bounded, not a proof: it follows the two alternatives over at most fourteen tokens, a rule at most twice on one stack, and gives up a pair past three thousand states; a shared prefix longer than that before the nested construct is not seen. A when on the way is read as nothing, so a pair a guard separates is told with a note that it may be.


5. Namespaces

@using System;

Common = ...

namespace Lexical
{
    Token = ...
}

namespace Syntax
{
    using Lexical;              // import a grammar namespace

    Unit = Token*               // instead of Lexical.Token
}

The top of a file is an implicit global namespace. The { } after namespace Name is a block of declarations, not an expression; in expression position braces mean a repetition count or an atomic group and nothing else (§3.2, §3.3). An inner namespace sees the outer one; the qualified name Namespace.Rule is available from outside. Declaring a rule whose name already resolves outside is refused rather than taken as shadowing — replacing a rule is what a rebinding is for, and the rule is stated where the two are told apart below.

using X; without @ brings the names of namespace X into the current namespace unqualified. Import directives stand at the top of the file or at the top of a namespace block — where C# expects them; one after a declaration is refused (GRAM2019). If two imports supply the same name, the error is raised at the use site rather than at the import, and is settled by qualification, as in C#.

Every namespace becomes a nested static class in the generated code.

5.1 Rebinding

A namespace may carry a header, namespace Name with (A = B, ...) { ... }. This does something different from an ordinary declaration in the block: it rebinds A to B for the whole call graph reached from what the namespace declares — not only for calls written lexically inside it. with is required; a header written without it is refused (GRAM2006) rather than silently accepted as something else.

B = 'c'
A = B
F = A

namespace Ns with (B = D)
{
    E = A
}

D = 'd'

F, outside the namespace, still resolves A to the ordinary B. E, inside, resolves the same A through D — even though A is declared outside the namespace and never mentions D. A itself is untouched: nothing about F's behavior depends on the namespace existing.

What the namespace declares carries its header wherever it is called from: a rule outside written R = Ns.E reads E through D too, exactly as parse Ns.E does.

The contrast with an ordinary declaration of the same name is the whole of what this section adds:

B = 'c'
A = B

namespace Ns
{
    B = 'd'                 // GRAM3012: 'B' already resolves out here, and a
    E = A                   // declaration would be a second, unrelated rule
}

namespace Ns2 with (B = D)
{
    E = A                   // E -> A, with B substituted -> D
}

D = 'd'

What replaces a rule may be any operand, not only another rule's name. One operand, the same bound a directive's target has — so a choice needs brackets:

parse List with (Comma = (',' | ';')) as Loose

An expression here becomes a rule of its own, declared where the with is written and named after what it replaces, so the substitution reads the trivia, the imports and the bindings that surround it. The left side stays a name, qualified or not: it identifies what is being replaced, and identifying is what a name is for. X with (Std.Digit = HexDigit) replaces the rule Std.Digit names, without a using, and is the same as Digit = HexDigit where Digit is that rule in view; both sides are checked the same way either form.

A binding is not a declaration — it does not introduce a rule named B — so it does not shadow anything and nothing inside the same namespace, at any nesting depth, may also declare a rule under a name that is actively bound; write a nested namespace Name with (B = ...) instead of redeclaring B. Both sides must already resolve to a visible rule. A parameterized rule (§4.2) may replace and be replaced by one of the same signature — the same parameter count, each parameter the same kind, a value where a value was and a recognizer where a recognizer was — because a rebinding substitutes the rule and keeps every call's arguments: A('a') under with (A = B) is B('a'), and an argument the call carried resolves through the same header's other bindings, like everything else the binding reaches. Mismatched signatures are refused (GRAM3009): a call's arguments have to fit the replacement for the substitution to mean anything.

An argument is written at the call site and means what it means there. A call into the namespace from outside, R = Ns.L(B) where Ns binds B = D, passes the B written in R, not the D the header puts in its place for what is reached from inside. The generator does not read it so yet: such an argument is refused (GRAM4040) rather than read wrongly — at any depth of the argument, through a parameter that passes it on, under a header the namespace inherits from an enclosing one, and where a rebinding is what makes the call one into the namespace (L(B) with (L = Ns.F)). An argument that names only rules the header does not rebind, Ns.L(Y), is read as written; a call written inside the namespace is reached from inside, and its argument is rebound with the rest; and a name both headers bind to the same rule — a caller inside O with (B = D) passing B into a namespace nested in O, which inherits that binding — means the same on both sides. A with expression inside an argument, L(D with (D = Y)), is refused too (GRAM4041): two calls passing the same argument share one instance, and the rebinding has no instance of its own to apply to. Declare a rule with the rebinding, X = D with (D = Y), and pass that.

Bindings in one header resolve simultaneously, against the namespace the header itself is written in: namespace Name with (A = B, B = C) sends a call to A all the way to C regardless of which entry is written first. A nested namespace inherits its enclosing one's bindings and may replace any of them with its own.

trivia is an ordinary rule, so it is an ordinary rebinding target: namespace Name with (trivia = none) reuses an already-written rule under different whitespace handling — the same substitution as any other binding, and a different mechanism from shadowing trivia locally (§4.5), which affects only what the block itself declares.

Which of the two to reach for is a question of what the result needs to be, not a style choice between them. A binding clones the whole call graph reached from inside the namespace and rewrites every call inside those clones — so the same shared rule, called from both inside and outside the namespace, behaves two different ways depending on which call path reached it. Shadowing does not do that: it changes what a name means only where the replacement is lexically visible, and a rule declared outside the shadowing scope never sees it, namespace block or not. Reach for a header when the point is exactly that a shared rule should mean something different from inside one place than from everywhere else it is called — LocaleNumberExample's two decimal points over one Number rule is the shape this exists for. Reach for shadowing — an ordinary declaration, no namespace needed at all — when a rule's meaning is simply different for the rest of the file or block from that point on, with nothing shared reaching back out to an unshadowed view of it: trivia = none at the top of a whole grammar is exactly that, and wrapping the entire file in namespace Name with (trivia = none) { ... } for it adds a block with nothing on the other side of the substitution to contrast against.

The same substitution is also available on a single expression, without declaring a block or a name for it: Expression with (A = B, ...).

ParseEuropeanNumber = Number with (Point = Comma)

is the one-line version of wrapping Number in a single-purpose namespace with (Point = Comma) { ... } just to reach the substitution once. with binds as tightly as a quantifier or recover (§3.8) — Number+ with (X = Y) is (Number+) with (X = Y), not Number+ of something already rebound — and reaches only the one expression it is written on, not the rest of the rule around it:

Row = a: Number & ',' & b: Number & ',' & c: Number with (Point = Comma)

only c's use of Number is affected; a and b still call the ordinary one. Reach for with when the substitution belongs to one place a rule is used; reach for the header once more than one call needs the same rebinding, or the substitution is worth a name of its own.

How substitutions stack. Where several reach one call, the one written closer to where the reading starts applies on top of the others, and rebinds what they put in place: an outer with over an inner one, a with or a caller's namespace header over the header of a namespace it calls into from outside, and a publication's with over everything. So (X with (D = Y)) with (Y = P) means X with (D = Y, Y = P), and reads P. A binding of a name a lower substitution already replaced does nothing, since nothing calls that name any more; a nested namespace header is the one exception, and replaces an inherited binding of the same name, as the header rule above says:

namespace Ns with (B = D) { E = B }
R = Ns.E with (B = Y)                           // reads D: inside Ns, B is already D

namespace O with (B = D) { namespace M with (B = C) { F = B } }
S = O.M.F                                       // reads C: M replaces the binding it inherits

A nested header otherwise resolves with what it inherits, as one header would: namespace O with (B = D) { namespace M with (D = C) { … } } sends B on to C. A substitution that loops once stacked, (X with (D = Y)) with (Y = D), is refused like a header that loops (GRAM3011); so is a with over the header of a namespace its operand calls into from outside, Ns.E with (D = B) under namespace Ns with (B = D), which is one header with (B = D, D = B). Where two of them each need the other applied first — a header that reaches a with calling back into its namespace from outside, or two headers each reaching a rule the other rebinds — there is no order, and the grammar is refused (GRAM4017).

A parse/find directive (§6) may carry the same header directly, rather than being wrapped in a namespace Name with (...) block just to reach it:

parse Number with (Point = Comma) as Evaluate

is parse's own equivalent of Number with (Point = Comma) above — one directive, no block, no name for the substitution beyond the publication's own. Like any other, it stacks on top of the headers of what it reaches rather than instead of them.

A publication named in an action means it under the same substitution. An action that reads a piece of the input again calls a publication by its name — TryParseHole(…) — and under a publication's with that name reads the rule the way the publication does:

private parse Assignment as ParseHole
internal parse Lambda with (Word = AsciiWord) as ParseAsciiLambda

Read so, ParseAsciiLambda reads the holes of its strings with ASCII words too. Where the author publishes the same rule under the same substitution, the name is that publication; where nobody does, the generator publishes it privately. A name the substitution changes nothing for is left as it is, and so is one written after a dot: Owner.TryParseHole is somebody else's method. A rebinding that only a condition asks about (below) does not redirect a name.

A rebinding is also what answers a condition. A guard of the form when A is B (§3.6) is decided when the parser is generated, against the rules as that parser has them — so a publication's own with is what gives it an answer:

Version = "2000" | "2008" | "2022"

Test = l: Name & "*=" & r: Name                         & when Version is "2000"
     | l: Name & "is" & "distinct" & "from" & r: Name   & when Version is "2022"
     | l: Name & "=" & r: Name

parse Test with (Version = "2000") as ParseOld
parse Test with (Version = "2022") as ParseNew
parse Test as ParseAny

ParseOld has the first alternative and not the second, ParseNew the other way round. The question is answered when the parsers are generated, and the three share one machine: what is left to ask while one of them runs is which of them it is — one test, at an alternative some of them have and the others do not. ParseAny names none, so it keeps the grammar's own Version — the choice of every version — and has all three. A parser that reads one version, one that reads several and one that reads everything are one construct with a narrower or a wider argument, which is also how products are said: on-premises SQL Server, Azure and Fabric are a set rather than a chain, and a set is what a choice is.

A range is a rule, not an operator. With Since2008 = "2008" | "2022", when Version is Since2008 asks exactly what when Version is "2008" asks — whether two languages meet — which is why nothing needs to know that versions happen to be ordered and products do not.

It is also what a chain of dialects cannot say. Each grammar in a chain adds to the one below it, so a construct taken out of the language — *= above — has nowhere to be written once; here it is an alternative with a condition on it, in the one grammar that has every version.

Write a rebinding in the header rather than as a same-named declaration in the body — namespace Name with (A = B) { ... } is a substitution, written where a reader expects one; a declaration with the same name sitting in the body, with no header entry for it, is an error. A declaration always means a new rule; a rebinding is the only way to replace one — so a rule declared inside a nested namespace { ... } whose name also resolves in an enclosing grammar scope, or through that namespace's own using import, is refused — GRAM3012. Scoped narrowly, to keep it a real mistake rather than noise: shadowing a built-in rule (trivia, wordboundary, word, any, none, eol, eof), at any depth, is the language's normal, silent mechanism and is never reported; neither is shadowing at the top level of a file, where there is no namespace Name with (...) header nearby to have meant instead.

5.2 The standard library, Std

The lexemes every grammar writes and none should have to — digits, an identifier, a number as a value, a comment, a quoted string — are a grammar of their own, carried inside the generator, and every grammar has it under the name Std:

trivia = { (Std.Spacing | Std.LineComment("--") | Std.BlockComment("/*", "*/"))* }

Pair : @int = a: Std.Integer & ',' & b: Std.Integer & eof => @(a * b)

The shape is C#'s. An included grammar (§6.7) is a reference, and the library is the one reference every compilation has, the way every C# compilation has the framework: Std.Integer names it in full with nothing declared, and using Std; opens the namespace as using opens any other, after which Integer is enough — on the terms every using has (§5): at the top of the file a rule of the grammar's own wins over an opened name, and a namespace that opens the library and declares one of its names is refused (GRAM3012). A grammar with lexemes of its own to declare names the library in full and keeps its names.

The library is spliced onto the end of every grammar, into a namespace called Std, exactly as an included grammar is — so it has no trivia of its own and a token is its characters, while the calling grammar spaces and comments around the call as it does around anything else (§4.5). Whatever the grammar does not call is not compiled: the library costs the rules used and nothing for the rest, and a grammar that never names it has nothing of it in what comes out. A grammar that uses it and is then included by another keeps it — the including grammar's own compilation has the same library, and a name resolves to it from inside the namespace the included grammar was spliced into.

There is no class behind the library, and that decides what it can mean. Its values are what the .NET parsers make of the text, in the invariant culture — Std.Integer is what int.Parse makes of its digits. A number too wide for its type is not a number of that rule: Integer, Long, Decimal and Double check the text with the type's TryParse in a guard (§3.4) and refuse what does not fit, as they refuse a letter — the Try method returns false and the other throws the FormatException every refusal throws, and neither lets an OverflowException out. Integer reads 0 to 2147483647, Long 0 to 9223372036854775807, Decimal up to 79228162514264337593543950335, and Double up to double.MaxValue: a Double that rounds to infinity (1e309) is refused too, where one that rounds to zero (1e-400) is read, as zero, because only the first is a number the type cannot hold. Leading zeros do not count against the width. A grammar that wants a message of its own, or a location, or a string with its escapes resolved, declares that rule itself: what a lexeme means takes code, and the code is the grammar's own. The library is the recognition, which every grammar spells the same way.

Rule What it reads Value
Digit one of '0'..'9' text
HexDigit one of '0'..'9', 'a'..'f', 'A'..'F' text
Letter one letter, \p{L} text
Space one space or tab text
Whitespace one space, tab, carriage return or line feed text
Digits one or more digits text
HexDigits one or more hexadecimal digits text
Blank one or more spaces and tabs text
Spacing one or more whitespace characters text
Identifier a letter or _, then letters, digits and _, in the Unicode reading text
Integer digits, if the number fits int int
Long digits, if the number fits long long
Decimal digits, then optionally a point and digits (3 and 3.25, not 3. or .5), if the number fits decimal decimal
Double digits, then optionally a point and digits, then optionally e or E, an optional sign and digits (3, 3.25, 1e5, 2.5E-3), if the number is finite double
LineComment(start) start to the end of the line, the line ending left unread text
BlockComment(open, close) open to the first close text
Nested(open, close) open to the close that balances it, holding other pairs to any depth — Nested("/*", "*/") reads /* a /* b */ c */ whole text
Quoted(quote) quote to quote, with quote doubled inside — Quoted('\'') is SQL's string, Quoted('"') its delimited identifier and CSV's field text, as written
Escaped(quote, escape) quote to quote, with escape in front of a quote or anything else inside — Escaped('"', '\\') is C's string text, as written

The runs — Digits, HexDigits, Blank, Spacing, Identifier and the body of LineComment — are atomic groups (§3.2): each reads to the end of what it recognizes and never hands a character back, so Std.Digits & '5' does not read 15, and a run beside a seam of non-empty trivia is read one way, not as many as it is long. A grammar that wants a run to give characters back writes the repetition itself.

A comment or a string is parameterized by what delimits it, because that is all that differs between one language's and the next: Std.LineComment("--") is SQL's and Std.LineComment("//") is C's, and each call is a specialization that costs what the rule written out would (§4.2). The strings are written with the until idiom, (?!quote & any)*, rather than an element set — a set names its characters and cannot take a parameter — and the idiom is the one lookahead a lexer reads as a pattern (§6.3), so they are tokens in a grammar read over tokens. The numbers are unsigned: whether - is part of a number or an operator in front of one is a question about the calling grammar, not about digits.

Nested is the one rule of the library that reaches itself, and it is written as the rule that says what it means:

Nested(open, close) = open & (?!close & (Nested(open, close) | ?!open & any))* & close

Inside a pair close is asked first and ends it, an open always begins another, and anything else is passed over; a pair that never balances is refused where it opened. The engine reads it as written. A scanner cannot — braced trivia (§4.5) commits to a first reading by reading what it calls in place — and neither can the automaton of a lexer (§7.1), which reads regular languages; both read it instead with a counter, a loop that looks for where either delimiter can begin and counts the levels, which has no depth to run out of and reads what the rule reads. So the comments of SQL and of most languages written since nest in trivia as they do in the language:

trivia = { (Std.Spacing | Std.LineComment("--") | Std.Nested("/*", "*/"))* }

The counter has to know which delimiter stands where it stopped, so the arguments are two literals, "…" or "…"i, neither empty, that cannot begin at one place: their first characters differ, under folding where a literal folds. Anything else is refused at the call (GRAM4037). It is recognized by being the library's: a rule of the same shape written under another name is read as written, and so is not a scanner's or a lexer's to read.


6. Publication

A rule on its own creates no public API. A directive does:

parse Feed
find Row
parse Feed as ReadFeed          // an explicit name instead of ParseFeed

There are two, and the whole of the difference is whether input that does not match is allowed to sit between the matches.

Directive What it says Generated
parse R the whole input is an R R ParseR(input) — throws FormatException
Match<R> TryParseR(input)
bool TryParseR(input, out R value) — whether it is one, and nothing about why not
find R there are Rs inside something else FindR(input) — a lazy sequence of Match<R>
positional parse R as parse R, and an R may also be read where the caller says it begins the three above, and TryParseR(input, at), TryParseR(input, at, length) and their bool forms (§6.3)

The whole directive, every bracketed part optional:

[access] [positional] parse|find <operand> [with (…)] [as Name] [: @T] [stream [bytes]] [yield [: @T]]

Left of the verb are modifiers of the methods the directive makes: who may call them, and whether they may begin where the caller says. Right of it is what is read and what is returned: the operand, the rebindings it is read with, the method's name, the result, the input forms and whether the result is lazy. The words on the left are written in that order, each once (GRAM2013).

A publication is a method of the generated class, and a parse is two, Name and TryName, so what it is called is the name of members of the class: it may not be Match, Outcome, SourceSpan, ParserInput, OnRecovered, OnHandingOff, OnTakingOver, Limits or ParserLimits, which the class declares for its callers, nor Failure, ParserEntry, DefaultBufferSize or DefaultMaxRetained, which it declares internal for its own use, nor in a grammar read over tokens Scan, which it declares internal for the host's own code, nor GramTrace, GramRead, GramWhy, GramTraceLog, GramProfile or Tracing, which a trace build of the grammar declares (§6.9) — in every build, traced or not, so that a grammar a project traces in Debug alone means the same names in Release — nor the name of the class itself, and neither of its two names may be the other publication's. That is refused where the directive is written (GRAM5018); give it another name with as. A rule whose type would be called one of them is given another name for the type (§7.3). Every other type and member the class writes for its own use has _DotGram in its name (§7.1), which no publication can have (GRAM1012), so find Word as Lines, parse Row as Parser and parse Row as Construct_Row compile. A name the class makes from a name of the grammar's — the walk, the factory and the scanners of a rule, the readers of a publication, everything a machine writes for the rule it was compiled for — is its kind, then _DotGram_, then the grammar's name: New_DotGram_Row is the factory of Row, Rec_DotGram_Row its walk, Buf_DotGram_ParseFeed the buffered reader of parse Feed; a variant is a kind of its own (New1_DotGram_Row for the second construction, RecWhole_DotGram_Row for the walk that insists the input ended). Nothing is written after the grammar's name, so two such names are one only where they are made from one name for one purpose, and no name an author can write — a publication, a rule's type, a member written by hand in the class, an external @M — is one of them. Inside the classes the generator declares for its own use, which no name of the author's reaches, the mark is left out: Read_Row is the reader of Row there, ReadBody_Row and ReadPart0_Row its parts.

A whole parse reads the rule's trivia on either side of it, and the value leaves it out. parse R is the whole input an R, and where R is read with trivia (§4.5) the input may begin and end with it: the trivia before the rule's first operand and after its last is the parse's, since no operand of the rule stands there to have it woven in. It is not the rule's, so it is not in what the rule gives back. A rule whose value is the text it matched (§4.1 case 4) gives the text from where it began reading to where it stopped: in a namespace with trivia = { ' '* }, Word = ['a'..'z']+ read whole from " ab " is "ab". The same in every reading of the publication — a string, a reader, a stream or bytes, read by methods or by the shared automaton, on every carrier, and over tokens (§4), where the lexer has skipped the trivia before the rule ever sees it — and the same as a reading that begins where it is told (§6.3). The same holds for every value built from that extent: the bounds of a @SourceSpan rule (2 and 2 for " ab " read whole by Pair : @SourceSpan = 'a' & 'b'), and what parserText and parserSpan say in the rule's own => and when. A value the rule builds from what it captured never held any trivia from outside it. Over characters a seam woven inside the rule before operands at its end that read nothing is the rule's own reading, and stays in its extent (status.md says where this differs from a reading over tokens).

The form that describes a refusal may pay for the description, and whether it does is a property of the grammar rather than of the form. Where the parse can read without recording — no context, or one the parser can put back, and no recover — it reads quietly first and reads a refused input a second time to say where and what was expected, so a refusal through Match<R> is two readings and the out form is one. Where it cannot, every input is read once, recording, and the two forms cost the same (§7.7). An accepted input is one reading in every case.

find is a sequence and needs no companion for "all of them" or "the first one": First(), Where(), Take() are LINQ's job and it would be strange to reinvent three of them. It yields occurrences as it finds them, so a document with a million matches costs one at a time rather than an array of a million.

A rule whose value is a sequence — Feed : FeedItem[] — is published with parse like any other, and what comes back is that sequence. Reading a feed is not a third directive: it is one parse of a rule that happens to be a list, and §6.3 decides whether the list is materialized or walked.

Explicit lazy results

yield is an output modifier on parse, independent of the stream input modifier:

Node : @FeedNode = v: Header => @(v) | v: Record => @(v)
Feed : @FeedNode[] = { Node* }

parse Feed as Array
parse Feed as ByteArray stream bytes
parse Feed as Nodes yield : @FeedNode
parse Feed as ByteNodes stream bytes yield : @FeedNode

The first two publications return FeedNode[]. The last two return IEnumerable<FeedNode>; Nodes(string) is lazy even with contiguous input. stream adds a TextReader input; stream bytes adds a native byte Stream input, and the same over bytes the caller already holds, byte[] and ReadOnlyMemory<byte>, read in place where the memory is backed by an array: no copy and no buffer parameters, since the whole input is there. Memory that is not array-backed is copied once (input.ToArray()) by the generated constructor. Both forms also keep their string overload. An explicitly buffered publication without yield materializes its declared result.

yield : @T states the element type. Bare yield infers it from the collection's @T[] type. Elements must be assignable to that type; derived nodes preserve their concrete types. The optional type belongs to the publication's output contract, not to the collection rule, and cannot change how its elements are constructed.

The current proof accepts a complete Rule* or Rule+ collection, including a constructing group lowered to an internal element rule, optionally inside atomic groups or transparent collection wrappers. The element rule must consume input and cannot be marked as giving back a successful match. The collection must have no custom factory, outer choice, prefix/suffix or implicit trivia. A recovery on the outer repetition is supported. Unsupported shapes receive GRAM4027; the compiler does not silently materialize the collection or change its backtracking behavior.

Enumeration parses consecutive elements and stops at clean EOF. Without recovery, malformed input throws FormatException from MoveNext; earlier elements may already have been returned. With Rule* recover Sync => @(Bad(...)), a rejected element is yielded in its place and parsing resumes after synchronization. A recovery without a factory drops the rejected element and reports it through the ordinary recovery hook. Recovery ordinals remain global to the enumeration; absolute source positions retain their ordinary meaning. Each iteration reads only one successful or recovered element. There is no Try companion for the lazy publication. Publish the ordinary parse form separately for an all-or-nothing TryParse. Each buffered element is constructed before yielding; completed input can then be released when lookbehind or location tracking does not require it. Readers remain caller-owned. Stopping early may leave read-ahead in the iterator's buffer; a new enumeration does not recover that buffered input.

Anything else is a consequence rather than a directive. Where a match may sit is the grammar's business, how much is held is the input's (§6.3), and picking things out of a sequence is the caller's.

What a directive says about its methods. A directive publishes public methods unless it says otherwise, and it may say so the way C# does; and a parse publishes the forms that read the whole input unless it also says positional:

parse Lambda as ParseLambda                                     // public
internal parse Lambda with (Word = AsciiWord) as ParseAsciiLambda // the assembly and its friends
private positional parse Assignment as ParseHole                // the class, and from a position

The access is every method the directive makes: the whole form, the one taking a position, the one taking a window, the ones over a reader. An entry point left public beside a private pair is exactly what it is for. positional adds the four forms that begin where the caller says and may stop short of the end (§6.3); the access comes first, internal positional parse, and a wrong order or a word written twice is GRAM2013. A find already looks at every position of the input, and a yield has no Try form to begin anywhere, so neither takes the word (GRAM2012). Each word is one only in front of parse or find, so a rule may still be called internal or positional. A private publication in a nested reading ([GramParserVariant], §6.6) is private to that nested class, which is where that reading's own constructions call it from.

What a directive names is an expression, not only a rule. Wherever the notation refers to a rule, any operand may stand — the same bound recover's synchronization expression has (§8.2), so a choice needs brackets and the with that may follow is the directive's own:

parse Padded(Word, ' ') as Spaced       // a parameterized rule
parse ('a' | 'b')       as Ab
find  ['0'..'9']+       as Numbers

An expression has no name to make a method name from, so as is required for anything but a bare name — parse ('a' | 'b') on its own is refused (GRAM2007) rather than given a name nobody wrote. What the expression becomes is an ordinary rule of that name, declared where the directive is written: it reads the trivia, the imports and the rebindings that surround it, exactly as a rule written in its place would, and everything after the front end sees a publication of a rule.

Being an ordinary rule also settles its value — §4.1 case 4, the extent it matched — and lets it be given the third part a rule has, in the place that reads as the method's own:

parse (v: Padded(Word, '#') => @(v)) as Marked : @string

With a type declared, everything §4.1 offers is reachable from the directive, a => included; without one a construction is refused where it always is (GRAM4008). The type supplies construction for an inline expression. On a named rule, it instead sets the public result contract while preserving the rule's construction:

parse Trade : @FeedNode
parse Trades as All : @FeedNode[] stream bytes
find Trade : @IFeedNode

parse returns the specified type, and its TryParse forms return Match<T>, but for the one that answers only yes or no. find returns IEnumerable<Match<T>>. The rule's actual result must be assignable to T through identity, reference conversion or boxing; no numeric or user-defined conversion is introduced. An incompatible contract receives GRAM4028. Without a contract, the existing type inference is unchanged. An extent-only rule returns string for text and byte[] for byte input, so a shared contract must accept both.

A named publication with an explicit contract uses stream to request buffered reader input. It does not infer the legacy reader API that changes an array result into an enumerable. Use yield : @T to request enumerable output explicitly; place its element type after yield (GRAM2008 if written before it).

6.1 The result

public readonly struct Match<T>
{
    public Outcome Outcome  { get; }   // Success | NoMatch | Starved (§7.5)
    public T       Value    { get; }   // meaningless unless IsSuccess
    public string? Error    { get; }   // null when it matched
    public long    Position { get; }   // where it matched, or where it gave up
    public int     Length   { get; }

    public bool IsSuccess { get; }
}

One out parameter, and only where nothing is said. int.Parse and int.TryParse are a pair because an int has no room to carry a failure; a result that has room does not need a second shape for it, and every later thing a match might want to say — what was expected, which record it was, whether the record was broken rather than absent — is a field here instead of another parameter on every signature. bool TryParseR(input, out R value) is the pair's second shape for a caller who asks only whether: it reads once and says nothing, so there is nothing for a Match to carry.

What is left of the pair is a real choice, and it stays: ParseR asserts that the input is an R and throws when it is not, TryParseR asks and answers. Assertion is the common case in application code and deserves to stay one line.

Position is not only for failures. On a match it is where the match began, which is what find is usually asked for; on a failure it is the furthest the input could be followed before the match gave up, which for a parser that backtracks is the only position worth naming.

6.2 Why the signatures use BCL types only

.Gram ships no runtime assembly: everything a generated parser needs is emitted beside it. What is emitted into a namespace is internal; a parser's own types — Match<T>, SourceSpan and the types its grammar generates — are nested in the host class, so their names are the host's, and are public where a caller reads them.

SourceSpan is the one a caller often never sees: the grammar's own C# is handed it (parserSpan, a recover factory), and what the host builds from it is the host's business. So it is internal unless a public signature the generator writes names it — a public publication whose value is a span, a property of a rule's generated type — and then public. A host whose own public API hands one out raises it by declaring its part:

[Gram("Expressions.gram")]
public static partial class Expressions
{
    public partial struct SourceSpan { }   // the generated part then says nothing of who may see it
}

The generated part is readonly partial struct SourceSpan, and the struct is readonly whatever the host's part says. A host whose one reading goes into a class of its own (§6.6) may declare the part there or in the host, and the span is written where it is declared; a host with several readings has one span, in the host, and a part declared in the class of a reading is refused (GRAM5018). A consumer therefore takes one analyzer package, acquires no dependency, and has nowhere for a "generator of one version, runtime of another" skew to come from.

The shape of the public API follows: an internal type cannot appear in the signature of a public method. So besides the host's own nested types only BCL types face outward — string, int, FormatException (the very type int.Parse throws).

Match<T> and a rule's own type are not exceptions to this. They are generated from one grammar into the assembly that uses it, so there are no two versions of them to skew, and nothing crosses an assembly boundary.

Nothing is shared, and that is the design rather than a stage of it. A library exposing a parser in its public API exposes its own generated types, and a consumer uses those — exactly as it would use any other type the library declares. There is no mode in which two assemblies bind to one copy of anything.

6.3 The input type picks the execution mode

Each directive gains overloads, and which one is called decides how the parse runs. There is no directive for this and no option: the choice belongs at the call site, because it is a property of the data rather than of the grammar.

Input How it runs Retains
string (whole or a slice by start and length) everything in memory all of it, and the result may be walked again
IEnumerable<string>, TextReader through a reused, growable buffer whatever the parse cannot yet let go of — one record's worth, for a well-formed feed — and the result is walked once

The shape of what comes back does not change with the input: parse of a sequence rule yields a sequence either way, and find yields one either way. What changes is how much is held while it is walked: over a reader, the window grows to the longest element it has had to hold, with no limit of its own (the stream forms below take one), so memory follows the longest record rather than the input; what the caller keeps of the result is the caller's. In every form the reader is the caller's: a parse never disposes it, whether the result was walked to the end, left early or ended in an exception.

A grammar that names eos takes sequences and nothing else (§3.1.1). Each of its parse publications is Parse…, TryParse… answering a Match<T>, and TryParse… with an out value, over IReadOnlyList<string>, over IEnumerable<string> and over a TextReader, and each find and yield publication takes the same three; no string, span, position or window form is generated. A string is passed as a list of one. A reader is a sequence of lines, split as File.ReadLines splits a file: every line ending — \r\n, \n or \r — ends a segment, a last line without one is a segment all the same, and a last line ending makes no empty segment after it. Where the publication streams, the forms over IEnumerable<string> and over a reader are the streamed ones — the segments read as they are asked for — and the list is read whole. Whether it streams is measured in segments rather than in lines: only eos ends a segment, so a record fits the window when no eos stands in it but its last, and a class such as [^ '|']+ that admits \n reads it as a character of the segment and keeps the stream. A repetition marked recover keeps it only where its synchronization is eos itself: the skip over a bad element reads anything up to the synchronization, so any other one — ';', eol, "END" & eos — may cross segments, and the rule is read whole (GRAM5001). A recover inside a record, whatever it synchronizes on, reads on past the segment after its skip, and does the same. A yield publication has no streamed reading over segments: its forms over a sequence and over a reader read the input whole, then hand the elements over one at a time, and it is told so (GRAM5001, information); a plain parse of the sequence rule is the reading that streams. A segment that holds U+0000 is refused: Parse… throws a FormatException, TryParse… answers a refusal at it, and a streamed reading throws when it reaches it; what is said says where as a line, the segment, and a column, the offset of U+0000 in it, over a reader too.

A reader and a string give the same result for constructions without side effects. A construction that changes state — the context included — may run a different number of times in a streamed reading than over a string: a result that reaches the end of what is held is not an answer while the reader has more, and is read again: its => runs again, on every carrier and under recover too (§3.7). A construction that assigns to, or increments, a member of context is told as it is written (GRAM5017, information; syntactic and best-effort).

The same grammar serves both. Feed : FeedItem[] = Header & Row* & Trailer & eof checks that there is exactly one header, that the trailer is there and that nothing follows — which is precisely what is lost when the caller chops the input into records and parses them one by one.

The reader overload is emitted only where retention analysis can prove it needs none of what a window has already let go of. A rule whose repeated part can begin with the same input as what follows it has not settled where it ends until backtracking says so, and the overload does not appear; naming a rule's value a SourceSpan into input a window will have moved past does the same. So does a recognizer of the host anywhere the rule reads — a recovery's synchronization (recover @M) included — and a repetition marked recover inside a part, whose skip may read past the end of the line. Where the overload is refused, the reason is reported at the publication:

'ParseFeed' gets no overload taking a reader: in 'Feed', the repetition 'Row' can
begin with the same input as what follows it, so where it ends is settled by
backtracking. A streamed parse hands each element to the caller as it reads it and
cannot take one back. docs/syntax.md §6.3 says which rules get one, and why.

What the reader hands over is what the string reads. The parts are read in order, and what is handed over is the value of each call, or of each element of a repeated call; a part that is not a call — ('[' & Word & ']')*, ('#' & Word)? — hands over nothing, so one that collects a value inside it gets no reader, and neither does a rule that builds its own value with =>, since the elements are gone by the time it could. A repetition that hands over nothing is still read a turn at a time, so what is held is one turn of it and not the run: ('#' & eol)* holds a line. One marked recover is the exception — it recovers inside the part, read whole — and gets no reader where the run may take more than one line, since the window would hold all of it. Only the repetition marked recover asks the rest of the rule first and steps over a bad element; any other one is read for as long as its element matches, as over a string. A repetition is held to its least and its most — and one with a most is asked the same question as one without, so A? & A+ gets no reader — the rule's trivia is read before and after it as a whole parse reads it, and input left over after the last part is refused where the string refuses it. A part is read once, so one that a choice of literals lets end in two places — ("a" | "ab") & "b", where the string tries ab once a led nowhere — gets no reader either; a line ended by eol ends where its line does, and keeps it.

Which is the shared responsibility: the author picks an overload, and the compiler offers one only where it provably works.

An additional buffered input form. stream on a parse or find publication requests a synchronous pull reader that continues recognition when its buffer is refilled:

parse Document stream
parse Packet stream bytes
find Row stream
find Packet stream bytes

The modifier follows any with, as, or publication result-type clause. It adds methods. An explicitly requested buffered character form replaces the legacy reader overload for that publication. The added methods use the same names, overloaded by input type:

Match<Document> TryParseDocument(TextReader input,
    int? bufferSize = null, int? maxRetained = null);
Document ParseDocument(TextReader input,
    int? bufferSize = null, int? maxRetained = null);

A null buffer parameter takes the grammar's own default, and a number takes precedence for that call. The defaults are [Gram(..., InitialBufferSize = 4096, MaxBufferedInputLength = int.MaxValue)], the values shown being what applies where the attribute does not say; a [GramParserVariant] inherits them and may set its own. The generated class holds them as the read-only DefaultBufferSize and DefaultMaxRetained, internal to the assembly: code beside the grammar can read them, a caller in another assembly cannot. Either set to zero or less is GRAM0009. What a null maxRetained takes is the class's Limits.MaxBufferedInputLength, which starts as DefaultMaxRetained and which a program may change while it runs (§6.5, Limits at run time).

The byte form uses Stream under the same method names. Explicit buffered input does not imply a lazy result: parse returns its declared result unless yield is present. Older inferred reader forms remain available for publications that do not request buffered character input.

An untyped root returns an owned string for characters or an owned byte[] for bytes. Typed roots retain their declared result type. Context, when used, precedes the buffer parameters. The caller owns the reader or stream; parsing does not dispose it. Parsing consumes input and may read ahead, including when recognition fails; it cannot restore the underlying source for another consumer. A sequence of lines is the exception in one respect: the enumerator the parse takes from an IEnumerable<string> is its own, so it is disposed when the parse ends, or when the caller stops walking a lazy result; the sequence itself stays the caller's.

[Gram(..., BufferedText = true)] adds the character form to parse and find publications; BufferedBytes = true adds the byte form. Both default to false. GramParserVariant inherits these settings and can override either with false. An explicit publication modifier still requests its form. Buffered find returns a lazy IEnumerable<Match<T>> for TextReader or Stream. It finds the same non-overlapping occurrences as contiguous find, including empty matches; it skips unmatched input. A completed occurrence is yielded without probing for EOF first. Once enumeration resumes, its consumed prefix can be released unless lookbehind or line/column tracking requires earlier input. Buffered character find replaces the legacy reader overload when explicitly requested or enabled by host options.

The generated machine uses a concrete buffered reader and block I/O, with no input interface dispatch per symbol. A short nonempty read is not EOF. Refilling does not restart recognition or rerun semantic guards. Backtracking changes a logical index into retained input; the source need not support seeking.

bufferSize is the initial logical capacity. maxRetained bounds retained input elements, not total parser memory; both must be positive. Storage is rented from ArrayPool<T>; a larger pool bucket does not increase the read size or retention limit. Buffers are cleared and returned on completion, failure, or disposal of a partially consumed iterator, except a buffer longer than 1,048,576 elements, which is let go instead: the shared pool keeps what it is given for the life of the process, so a buffer grown for one long input would otherwise stay after the parse that needed it. Below that length a buffer goes back to the pool, because renting a fresh one costs every parse that grows it. The caller still owns the input reader or stream. The buffer grows when needed and reuses a proven-dead prefix, compacting on refill rather than on every symbol. Exceeding retention or position capacity throws IOException, separately from a grammar mismatch; for retention the message names the limit and says to pass a larger maxRetained. Determining EOF at the retention limit may consume one additional element before reporting that limit.

Release analysis is currently conservative: source-independent, single-rule deterministic loops can release completed iterations. Other grammars retain input until completion, including roots returning the entire matched text. This form does not promise bounded memory for arbitrary grammars, nor incremental result delivery for ordinary parse; yield delivers elements and find delivers occurrences incrementally. Captured strings own their contents; a SourceSpan remains an extent, not an owner of the input. Positions currently fit in int, including after buffer compaction; inputs approaching that limit produce a resource error rather than wrap.

Byte input is compared numerically without text decoding. Byte literals are case-sensitive values in 0..255; sets use byte values or any. Unicode categories, case folding, external sets, and line/column recovery are unsupported. Typed scalar values and typed rule captures are supported. Raw captures and parserText are passed to byte-form semantic actions and guards as ReadOnlySpan<byte>; a type the grammar makes for a rule from a raw capture, whose member is a string, is refused over bytes (GRAM4026) — declare the rule's type and build it with =>. No decoding, byte-to-character conversion, or intermediate string is performed for these captures. Encoding syntax remains future work.

Native capture spans

[Gram(..., UseSpanCaptures = true)] (or the same property on a [GramParserVariant]) changes raw character captures and parserText in actions/guards from string to ReadOnlySpan<char>. It applies to both the contiguous string parser and its buffered character form. It defaults to false to preserve existing string-based actions, and follows GramParserVariant inheritance and explicit overrides. The byte form always uses ReadOnlySpan<byte> for raw captures, independently of UseSpanCaptures.

Number : @int = text: ['0'..'9']+ => @(ToInt(text))
parse Number stream bytes

Provide ToInt(ReadOnlySpan<char>) and ToInt(ReadOnlySpan<byte>) overloads in the host. C# selects the overload directly; the generator does not insert conversions or a runtime interface. The author controls validation, overflow, encoding and ownership. Missing or incompatible overloads are normal C# compilation errors. The character parser requires UseSpanCaptures = true to avoid its usual string capture allocation. A small helper is eligible for JIT inlining; inlining is not guaranteed by the generator.

A contiguous capture borrows a slice of the input. Repeated captures whose pieces do not touch are joined into one temporary char[] or byte[], preserving the existing exclusion of separators. In span mode an absent optional raw capture is an empty span, not null; retain the default string mode if that distinction is required. Typed rule captures keep their declared types.

Spans are valid during the action/guard call. The buffered parser retains source needed by pending captures and parserText until materialization; it may therefore retain the whole parse. To store source in the result, explicitly copy it or construct an owned value inside the action. A span cannot be stored in a normal class or survive asynchronous work. These options do not silently change the return type or ownership of an untyped publication.

Explicitly requested unsupported forms report GRAM4026. Current exclusions also include token-kind machines, span-based external recognizers, and parserInput factories. External recognizers using ParserInput<T> support buffered input (§7.1). Async refill, caller-fed chunks, and a contiguous byte publication are not supplied by these options.

A position and a window. Beside TryParseX(string input) a positional parse gets two more forms, and two that answer only whether:

Match<T> TryParseX(string input, int at);              // begins at `at`, need not reach the end
Match<T> TryParseX(string input, int at, int length);  // and sees nothing from `at + length` on
bool TryParseX(string input, ref int at, out T value);             // and moves `at` past it
bool TryParseX(string input, ref int at, int length, out T value);

The bool forms are §6.1's bool form with a position — one quiet reading, no message — and on a reading at moves to the end of what was read; on false it stays where it was and nothing is built. A position outside the input is NoMatch in the forms that answer with a match, and ArgumentOutOfRangeException in the two that move one: a position of the caller's own making is the caller's mistake, not something the input answers for.

None of them demands the end of the input, and none reads the trivia after the rule: a reading that begins where it is told stops where the value ends, which is the extent a host holding the text is asking for, and the trivia after it is the leading trivia of the next reading. The trivia such a reading starts on is sealed: the rule reads from where the trivia ended and takes nothing back from it, so an input a whole reading accepts by reading less trivia, a reading from that position may refuse. A repetition marked recover at the end of such a reading reads its fewest turns (§8.2). Position says where the value began, past the trivia the reading started on, and Length is its own extent: what comes back is the value and neither the trivia before it nor the trivia after, as from a whole parse (§6). What comes back says where the reading began and how far it got, and every position in it — and in whatever the reading builds — is an offset into input, so a host reading a piece of a text it holds keeps what those positions mean. eof written in a rule is still the end of the whole input, and inside a window the end of the window.

Over a grammar cut into tokens (§4) a reading begins at a token, so it begins at the first one at or after at: the trivia between two tokens — a line break, a comment, whatever this grammar calls trivia — is the lexer's to skip and not the caller's to know, and a host reading a script a statement at a time hands in the position after the last statement, which is one of those as often as not. Position then says where the reading began, which is where the value begins and not where the caller was looking, and where nothing is left but trivia the answer is Starved. A character no token begins with is not trivia, and input that ran out is not what refuses a reading there: one that begins on it, or reaches it, is answered as over characters — NoMatch at it, or the empty reading where the grammar allows one. A published rule of a namespace without trivia reads none over tokens either: trivia before its first token, or after its last where the end is asked for, refuses it as it does over characters. A token the text or the window ends inside of — an unclosed string, a comment the syntax reads, half an operator — is not such a character: more input could finish it, so a reading that reaches it, a whole reading among them, is Starved whether it is refused there or reads it, as over characters, where the reading of that token runs out of input (§7.5). A complete token the window's end leaves room to lengthen is read as it stands, and a comment that is trivia is skipped rather than cut, so one left unclosed is read as whatever tokens its characters make, or refused at the first no token begins with. A pair the trivia reads with Std.Nested (§5.2) is the exception: where the trivia, reading from where it stops, opened such a pair and the text or the window ended inside it, the tokens end where the trivia stopped, as at a character no token begins with, and the reading is refused there. Its counter reads to the end before it knows the pair is open, and every opening inside it would be asked again if its characters were tokens, each reading to the end: the square of the text's length. A pair asked for under a lookahead (?! or ?=) is not one the trivia opened, and leaves the tokens alone; that is also where the guarantee of one pass stops, since trivia that asks a lookahead over a pair at every step, { (?!Std.Nested("(", ")") & '(')* }, reads to the end once for every unclosed opening, within the one call. A character no token begins with ends the tokens rather than refusing the reading — in all of these forms, since none of them is required to reach the end of the input, and a reading must not be refused by what it never read: one character the language does not know in the last line of a script leaves the statements before it readable. The window form cuts only the window into tokens, so it may also begin anywhere: a hole in an interpolated string, read up to the : its format begins with, is the shape it is for. Only the whole-input forms refuse there, because reaching the end is what they are for.

They are written because the directive asks for them, and only then: whether the generator reads the rule by methods, by the shared automaton or by one flat method does not decide it. A publication compiled as a flat method keeps it for the whole input, whose speed the request does not touch, and is read from a position by a second entry of its own, by methods or by the shared automaton, since its rules were proved to need nothing else only against the end of the input: that entry is the size the request costs. A position is the string forms': positional parse X stream adds the reader as stream always does, and the reader begins at its start. A grammar that names eos reads its segments joined, which no position of the caller's can stand in, and refuses the word (GRAM4055).

What a reading from a position still costs, said here rather than discovered. Over a grammar cut into tokens it cuts the whole input, and the cutting is kept for the next reading of the same string, so a loop of readings over one text cuts it once. One reading of a short value out of a huge text cuts the whole text all the same, and that is known and not intended to be otherwise: cutting only as far as the reading goes would mean a second machine for the same grammar, which every build would pay for.

What "how far back" means is fixed by §4, and this is the whole of the retention rule:

  • a call may resume choices in its callee, so rule extraction does not reduce retention;
  • an explicit atomic group discards alternatives created inside it when it succeeds;
  • recovery and streaming continuation boundaries provide the other points after which earlier input can no longer be revisited.

For parse that is the whole input, and a grammar of one rule over a whole file streams no better than reading it. What bounds it is a construct that says the parse will not go back past a point, and recover is one by construction: its synchronization expression is exactly such a point, so a marked repetition retains one element and not the file.

A capture is materialized when the rule that owns it accepts — not when the parse ends, and not lazily afterwards. Since a rule's extent is also its retention, a captured string is made while the input it names is still there, and a buffer may be reused the moment the rule that read it has answered. That is what makes a capture and a reused buffer compatible at all, and it is why construction runs at the accepting state (§7.3) rather than at the end of the parse.

Absolute offsets are long; extents are int. A position is into the input, and an input may be a file larger than an int can index. An extent — a span, a length, a capture — is into a buffer, and a buffer never is. Counts of things, like a line number or an ordinal, are int: nothing has two billion lines.

Inside recognition, a position is an ordinary index into whatever currently holds the input — a reused window, or the in-memory buffer itself. Match<T>.Position (§6.1) is a long regardless of mode, since even in-memory input could in principle be a string an int cannot index; it is only ever widened once, at the one place a position crosses a publication's own boundary out to the caller, so an error at offset 8,432,109,553 can be reported as such.

6.4 TargetMethodPartSize, the one thing a host may tune

A recognizer too large for one method is written in several. Past about sixty thousand bytes of IL the JIT stops optimizing a method altogether, and well before that its code quality falls off.

How large a part is aimed to be is counted in the generator's estimated basic blocks, and the default is chosen on grammars that are not yours:

[Gram("…", TargetMethodPartSize = 80)]
public partial class MyParser { }

It is a wish, not a setting. Every value generates a parser and none can fail a build: below one asks for the finest division there is, anything past the size of the recognizer asks for one part, zero means nothing was asked, and everything between is taken at its word. A number that made a grammar stop compiling would be a knob nobody could safely turn.

Whether to divide at all is not tunable and is not the same question — a grammar small enough to hold in one method is faster that way, and one too large for it is far slower undivided. The generator decides that from the size it estimates.

6.5 MaxExtraStacks, how deep a reading may go

A grammar that recurses can be handed input the author did not write: a thousand brackets, or a hundred thousand. Recursive descent reads that on the machine stack, and a machine stack ends.

So a rule a cycle re-enters probes the stack as it begins — once in every sixty-four entries, because the runtime reserves far more than sixty-four frames of a reader — and where the margin has gone the reading is carried onto a stack of its own and goes on from that rule. Nothing is re-read and nothing is lost. A reading deep enough to run the new stack low takes another, and by default it may take them for as long as there is memory to take one with.

Say how many is enough where that is not what you want:

[Gram("…", MaxExtraStacks = 4)]
public partial class MyParser { }

Past that many the parse fails with InsufficientExecutionStackException. Zero, the default, is no limit. A reading that never goes deep takes none whatever this says, and a grammar with no cycle in it never probes.

One thing is not carried: a reading over a window (§6.3) has no whole input to hand to another stack, so a streamed parse that runs low fails.

What goes across is the reading's own state, the execution context and the cultures. What a host keeps for its semantic actions outside the reading — a thread-static field, or an AsyncLocal where the caller suppressed the flow of the context — stays behind. A host that keeps such state says what to carry, in two partial methods the generated class declares wherever a rule probes:

static partial void OnHandingOff(ref object? state)   // on the thread that hands off: fill the slot
{
	state = Scope.Current;
}

static partial void OnTakingOver(ref object? state)   // on the thread that takes it, before and after
{
	state = Scope.Swap((Scope?)state);                // the handed state in, this thread's own out
}

The second runs before the reading and again after it, so the exchange puts the thread's own state back; the slot is filled afresh for every hand-off, including one to a thread that took an earlier one. Left unimplemented, both are removed at compile time with their calls. A second reading of the grammar (§6.6) declares its own pair in its own class. A hook that throws fails the reading with what it threw, as an action that throws does, and leaves no thread waiting: the first is asked before a thread is taken, and the second still runs, and puts the thread's own state back, where the reading threw. A thread whose hook threw is not used again: it may still hold the host's state, so the next hand-off goes to a new one.

A rule a cycle re-enters is also where a reading over tokens remembers what failed. A bracket may be read as a condition, then as a value, then as a subquery, and each attempt reads all that is inside it again: left to itself a nest of brackets costs a power of its depth. So such a rule, entered again at a token where it has already failed in the same reading, fails at once — one bit a rule and a token, forgotten when the reading ends. A success is read again, except in the rules of a recursion an ordered choice reads twice before it decides (§4.7): there the reader remembers where the rule succeeded and what it built, and answers the second entry with it. A rule is not remembered where its answer could depend on more than where it begins: one that reaches a hook naming context or the reading's state (§7.2), one that gives back (?), every rule of a reading that recovers (§8.2) or reads a buffered input, and every rule read over characters. This relies on §7.2's contract: a guard, a selector, an external recognizer and a construction whose value one of them reads answer from their arguments, captures and the text, or from context named as such. One that reads state some other way breaks it, and the memo then answers with the failure it remembered.

Limits at run time

MaxExtraStacks and MaxBufferedInputLength are written when the parser is generated; the program that uses it may change them while it runs. Every class a reading is compiled into — the host, and the class of each [GramParserVariant] — declares a static property and the immutable value it holds:

public static ParserLimits Limits { get; set; }      // ParserLimits.Default until set; null is refused

public sealed class ParserLimits
{
	public static ParserLimits Default { get; }      // the values [Gram] wrote
	public int MaxBufferedInputLength { get; }       // int.MaxValue is no limit
	public int MaxExtraStacks { get; }               // 0 is no limit
	public ParserLimits WithMaxBufferedInputLength(int value);   // zero or less: ArgumentOutOfRangeException
	public ParserLimits WithMaxExtraStacks(int value);           // negative: ArgumentOutOfRangeException
}
MyParser.Limits = MyParser.Limits.WithMaxExtraStacks(4);

A parse reads Limits once, as it begins, and holds to what it read: setting it replaces the whole value at once, so a parse already running — on this thread or another, on the stack it began on or one it was carried to, in its first reading of a refused input or the second one that writes the message — keeps the limits it began with, and one begun after the set reads the new ones. Nothing is locked, and a parse pays one read of a static field for it.

Which value applies, first to last: a call's own maxRetained, where a buffered overload is given one; then Limits; then the attribute's value, which is what ParserLimits.Default holds. MaxExtraStacks has no argument of a call.

The setting is the process's, one for each reading of each grammar class: two parts of a program that want different limits for the same grammar share them, and a test that changes them runs apart from the tests that read them. A reading whose locations are asked for per call (UsePerCallLocations) is the same reading, and reads its host's Limits. A class whose readings publish nothing declares none. Limits and ParserLimits are names the class keeps: a publication or a rule's type called either, a class a reading is compiled into called either, and a member Limits or ParserLimits the author declares in that class are GRAM5018.

A library whose grammar classes are internal says so in its own words: the SQL parsers are public classes, and TransactSqlParser.Limits is theirs; DotGram.Web sets every one of its grammars at once through WebParsers.Limits, one setter at a time. Each grammar holds its own limits, so change them before parsing: while they change, the grammars of DotGram.Web may briefly see different values.

6.6 [GramParserVariant], a second reading of the same grammar

[Gram] is written once: it says which grammar, which is a thing a class has one of. [GramParserVariant] may be written as many times as there are further readings wanted, and each is a compilation of its own that names the nested class it goes into:

[Gram("Sql.gram", Lexical = true)]
[GramParserVariant("Immediate", Carrier = GramCarrier.Immediate)]
public static partial class Sql { }

Sql.ParseQuery is the first; Sql.Immediate.ParseQuery is the second. Two files come out, one per attribute.

Everything a [GramParserVariant] does not say it takes from the [Gram] — the grammar, whether it is read as tokens, how it is divided — and what it does say is the difference. That is the shape this is for: the class's own parser, compiled the other way and no other way. The options themselves are the same on both — they are declared once, on the abstract GramReadingAttribute both derive from — except Source and DefaultAlias, which are the grammar's own and only on [Gram], and UsePerCallLocations, only on [GramParserVariant]. The class a reading goes into is said differently on each: a [GramParserVariant] names it as its one argument, which cannot be left out, and [Gram] may name one with Name where the first reading is not to be the host class itself.

Why a class rather than a suffix on the method names. Everything a parser needs is emitted beside it (§6.2), and a file's share of that — the match, the failure, the lexer, the value tables — is written once and named for what it is. Two compilations in one scope would collide on every one of them. A class is a scope, so nothing collides and neither compilation can see the other. What the host itself declares stays in reach: a nested class reads the static members of the class around it by their simple names, which is what a grammar's => calls are.

What the host's own C# names is the host's. SourceSpan (§4.1, §6.2), Match<T> (§6.1) and ParserInput<T> (§7.1) appear in the signatures a grammar calls and a caller reads, so where a class carries several grammars they are written once, in the class itself, and every scope reads them from around it. Otherwise a factory handing a span to a method of the host would be handing it a type of the same name that is not the same type, and neither compilation would build. Each is written where at least one reading needs it, and only there: a traced reading beside a plain one adds no SourceSpan and no ParserInput<T> to a host whose grammar asks for neither. They go in a file of the host's own, Host.gram-shared.g.cs, beside the readings' files.

A host with one reading keeps them in the reading's own class, so a second reading moves them. [Gram("…", Name = "Fast")] alone answers with Host.Fast.Match<T>; add a [GramParserVariant("Slow")] and both answer with Host.Match<T>:

Host.Fast.Match<Row> m = Host.Fast.TryParseRow(text);   // one reading
Host.Match<Row>      m = Host.Fast.TryParseRow(text);   // two: the same call, the host's match

Code that names the type through the class it calls — var, or Host.Fast.Match<Row> only where the host has one reading — is the code a second reading leaves alone.

The nested class is public unless the host declares it. A nested class would be private by default, so the generator writes it public. Declared by the author, it is the author's to decide, and the generated part adds no accessibility of its own:

[Gram("Sql.gram", Lexical = true)]
[GramParserVariant("Immediate", Carrier = GramCarrier.Immediate)]
public static partial class Sql
{
    internal static partial class Immediate { }   // a reading for tests and measurements
}

Two readings wanting the same scope — a [GramParserVariant] naming the class another reading is compiled into, or the one [Gram(…, Name = …)] already names — is refused (GRAM0006), because one of them would silently win. The name is the attribute's one argument and cannot be left out; an empty one, or one that is not an identifier, is GRAM0007.

The value types a grammar generates are the compilation's own, so two compilations of a grammar that builds its own types build two families of them. They are named alike in every reading: a rule's type is named against the host and the classes of all its readings, whichever reading writes it, so a rule Url in a host Url builds Url.UrlValue and Url.Traced.UrlValue, and code written against one reading moves to another by its prefix. For the same reason no publication, and no rule's type, may take the name of a reading's class: parse Body as Traced beside a reading Traced is refused (GRAM5018) in every reading, and a rule Traced builds a TracedValue. Where the types are written by hand and named with @, both build the same ones, which is what makes two carriers over one grammar comparable at all.

Value-table storage

A direct deferred reader keeps what it builds in a table per value type, and how those tables are held is the generator's to choose: flat arrays indexed by record, dense indexing where a machine's materializer runs once at the end, and arrays that grow into lazy pages where a grammar has many types. The choice is made from the grammar's structure at generation time and costs no runtime dispatch. It is not offered as an option, and no generated layout is promised: a parser is asked what it reads, not how it stores what it read.

Tables are shared by a compilation and its publications, so the choice is the compilation's. Immediate readers and the non-direct engine do not use them.


6.7 [GramInclude], a grammar built on another

[GramInclude(typeof(Sql92Parser), Alias = "Sql92")]
[Gram("TransactSql.gram", Lexical = true)]
public abstract partial class TransactSqlParser { }

[GramInclude] is the reference. It names a class that carries a grammar — one with a [Gram] of its own, in this project or in one this project references — and that grammar is compiled into this one, wrapped in a namespace called what Alias says, or what the class's DefaultAlias says, or the class's own name. Its rules are reached in full, Sql92.Identifier, and using Sql92; opens the namespace as using opens any other (§5). Written as many times as there are grammars to build on; what an included grammar includes comes along too, each grammar once however many paths lead to it, so a cycle ends rather than being reported.

An included grammar is a whole file, and it stays one. What it sees outward is what a compilation sees of its references and no more: the built-in rules, the standard library, and the grammars it included itself — never the rules of the grammar that included it, which were not written for it, and never that grammar's trivia, wordboundary or context, each of which is its own to declare and defaults as it would in a file of its own. Its parse directives are its own class's public API, already generated there, and are left where they were written; the including grammar publishes what it means to publish. Nothing has to derive from anything: the host is its own class, and what its grammar built on is a matter of the attribute.

Two includes under one name are one namespace, and then their rules can collide — that is refused (GRAM0008), and the fix is an As of its own for all but one. Under different names they cannot collide at all, whatever they are called inside.

The C# comes with the grammar. A rule that came from another grammar goes on calling the methods its author wrote on that grammar's class: the generated file names each included class with using static, and the code is in scope without the host deriving from anything. The class is named by its full name under the root it is reached from — global::App.G, or X::App.G for an assembly referenced under the extern alias X, which the generated file then declares — and so it is the class the include names. Written unrooted, as it once was, the import was read from inside the host's namespace, where App.G beside a namespace App.App meant App.App.G: that was C#'s reading of what was written, and the rooted import is a change of what an included rule binds to, not a correction of it. What that does not settle is two grammars' C# using one name, and the answer is that it settles nothing: two included classes offering the same method is the compiler's ordinary ambiguity error, a method that resolves nowhere is its ordinary missing-method error, and a method of the host's own under a name an included rule calls wins silently if its signature fits. Reading what you include is the provider's responsibility, and the generator does not stand between a grammar and its C#.

A grammar travels with its assembly. A .gram file is read at compile time and is not part of what ships, so the generator writes the grammar's text onto the class it compiled — [GramSource("…")] — and an include across a project reference reads it off the type it already names. A class of a referenced assembly is always read from there: it is the grammar the assembly was compiled from, and a .gram file of the same name in this project is somebody else's — a fixture, a copy — and is not read in its place (GRAM0017, information, says so where the two differ). A class compiled in this project is read from its file, so that a diagnostic points at something somebody can edit. It costs the size of the grammar, and it follows what the class already says: a host that is public, with every class around it, carries its grammar and one nobody outside can name does not, and [Gram(ExportGrammar = …)] says otherwise where that guess is wrong. An include that finds neither a file nor a carried text is GRAM0003.

A grammar written only to be included elsewhere publishes nothing of its own. Where no [Gram] class of its compilation includes it or derives from its class, the build takes it for a grammar whose parse was forgotten (GRAM4059, a warning), unless it says ExportGrammar = true in so many words: written out, that is the mark of a library grammar, which the default for a public class is not.

6.8 Generation options

The options written on [Gram] and [GramParserVariant] change how a grammar is compiled into a parser — which machine reads it, how it carries what it read until it builds, how its methods are divided, what a value is told about where it was written — and not what the grammar means. Under every setting a grammar accepts the same texts and builds the same values, except where an entry below says otherwise: Lexical reads over tokens, where a rule's answer stands (§4); Carrier decides whether a construction may run for a reading that is abandoned or refused, and ConstructionsMayThrow whether what one throws there escapes; LocationType hands values their positions; MaxExtraStacks fails a reading deeper than it allows. The build property DotGramPositionalFollow, below, is one more: it changes what a reading from a position answers, and what the generator tells a grammar left to choose about its carrier.

Lexical and Carrier are requests rather than settings. Where a grammar cannot be compiled the way one asks, the parser is compiled the way it would have been without the request, and a diagnostic says why: GRAM5004, GRAM5007, and GRAM5005 for a rule of a grammar cut into tokens that the methods refuse. TargetMethodPartSize is a wish (§6.4), and no value of it fails a build.

Option Default What it says
Source the .gram file named after the class [Gram] only, as its constructor argument: a path to a .gram file, or the grammar text itself. A single-line value ending in .gram is a path (§1).
DefaultAlias the class's own name [Gram] only: the name another grammar includes this one under where its [GramInclude] gives no Alias (§6.7).
Name none — the host class itself [Gram] only: the nested class the first reading goes into (§6.6). A [GramParserVariant] names its class as its one, required argument: [GramParserVariant("Immediate", …)].
TargetMethodPartSize 0, the measured default how large the parts of a divided recognizer are aimed to be (§6.4).
MaxExtraStacks 0, no limit how many stacks one parse may take beyond the one it began on, where the class's Limits is not set (§6.5).
ExportGrammar not set: exported when the class and every class around it are public whether the grammar's text travels on the class, for an include across a project reference (§6.7). Written as true, it also marks a grammar that publishes nothing as one for other assemblies to include (GRAM4059).
Lexical false read the input as tokens, the grammar cut into a lexer and a syntactic half (§4, §7.1). A grammar that cannot be cut is GRAM5004. The lexer's Scan(text, pos, out kind) is internal: the kind it answers with is the grammar's own numbering, which changes with the grammar. A host that wants token boundaries writes a method of its own under another name that calls it.
Carrier GramCarrier.Auto how a reader carries what it read until the constructions run; below.
ConstructionsMayThrow false a construction may throw on a reading the parse gives up: the immediate carrier holds what it throws and throws it only where the deferred carrier would have (§7.5). Ignored by the deferred carrier.
LocationType none an interface whose implementors are told where they were written; below.
UsePerCallLocations false on a [GramParserVariant] with a LocationType: the locations are asked for per call, not compiled in; below.
Trace false a trace build: the parser reports what it reads to a sink (§6.9). Changes no answer.
BufferedText false adds the buffered character form to parse and find publications (§6.3).
BufferedBytes false adds the buffered byte form, with no text decoding (§6.3).
UseSpanCaptures false hands character captures over as ReadOnlySpan<char> rather than string (§6.3).
MaxBufferedInputLength int.MaxValue, no limit the most a buffered parse may hold at once, where neither a call nor the class's Limits says otherwise; zero or less is GRAM0009 (§6.3, §6.5).
InitialBufferSize 4096 the capacity a buffered parse's buffer starts with, where a call does not say; zero or less is GRAM0009 (§6.3).

Every option but Source, DefaultAlias, Name and UsePerCallLocations may be written on either attribute, and a [GramParserVariant] takes what it does not say from the [Gram] (§6.6).

Carrier

A reader holds what it has read until the constructions (§3.7) run, and the carrier is how:

  • Auto — the default: Immediate wherever that carrier can carry a machine, Deferred for a machine it refuses (in silence; the carriers report says which). Where Deferred would hold back constructions the immediate carrier runs, the generator says so: GRAM5016, a warning, where it would be safer — constructions share context with a guard, a switch selector or a recognizer, so what is accepted and what is built can differ, or a refused input can rebuild a list on every turn given back, in memory quadratic in its length; and GRAM5012, information, where a construction can run for text the parser then reads another way or a second time. Naming either carrier silences both, and every reason found later.
  • Deferred — what was read is recorded, and built into values once the parse is accepted. No construction runs for input that is refused (§3.7). Called Tape before 0.3.0.
  • Immediate — no deferral: a construction runs the moment its alternative has been read, and one abandoned afterwards has already run. That is once per derivation tried rather than once per derivation accepted: invisible to a pure allocation, visible to a counter. It is for factories the author knows to be pure. Two things bound what an abandoned reading runs. A refusal is read a second time to say what was expected, and that reading builds nothing but what a guard names. And once a repetition or a choice has given a turn back a second time, the attempts after that build nothing but what a guard names either, until one stands; that attempt is then read once more and built, so a list of a thousand members refused after its last one builds its members a constant number of times — at most two attempts for each enclosing loop that gives back — and not half a million times. (The first turn given back is read building as before: that is how a choice reads its next alternative, and an attempt that stands then is built once.) What a parse that fails has run is at most that: two attempts per enclosing loop, of what it read — in a grammar with no context and no recovery, and outside a rule whose own guard asks for its value so far. There neither bound holds: the second reading builds again, and every way back taken rebuilds what stood before it, as often as the input gives ways back (GRAM5016). What a construction throws on an abandoned reading escapes the publication, unless the grammar says ConstructionsMayThrow = true: then it is held and thrown only where the deferred carrier would have thrown it (§7.5).

A machine the immediate carrier cannot carry is compiled deferred, the rest of the grammar keeping the carrier. Where Carrier = Immediate was named, GRAM5007 says which publications moved and why — among the reasons, that no part of the grammar is read by methods, since a carrier is what a reader holds; left to the generator, the fallback is silent.

LocationType

[Gram("Sql.gram", Lexical = true, LocationType = typeof(ISqlSpan))]

Name an interface declaring void Locate(int at, int length) — with UsePerCallLocations, void Locate(int at, int length, int gapStart) (below) — and every rule whose value implements it is handed the range of input it was built from: the rule's own text, without the trivia around it, so that a comment falls between two values rather than inside one. Locate is called once, by the reader, on a value it has just made and nothing has yet seen, and it is called through the interface, so an explicit implementation serves as well as a public one. A class declaring Locate, or inheriting it, may be named instead, and is called on the class. A type that is neither is GRAM0011.

An implementor may be a class or a struct; a struct is told on the value the rule returns. A rule whose value is a Nullable of a struct has nothing to write it on, and is refused (GRAM4046).

A place is an int. Read through a reader, a place past int.MaxValue characters into the input cannot be told, and the reading throws InvalidOperationException where it would tell one rather than tell one that has wrapped round; so does a guard's parserSpan, a recovery's and a mark's there. A reading that tells no place that far in reads on.

It changes nothing about what is read, and a grammar that names no interface pays nothing. Being an option, it may be given to one reading of a grammar and not to another (§6.6).

UsePerCallLocations

[Gram("TransactSql.gram", Lexical = true)]
[GramParserVariant("Located", LocationType = typeof(ISqlLocatable), UsePerCallLocations = true)]
public abstract partial class TransactSqlParser { }

A second reading that differs from the first only in being told where its values were written need not be a second parser. With UsePerCallLocations, the [GramParserVariant] compiles nothing of its own: the grammar is compiled once, its constructions are told where they were written only when a call asks, and the nested class it names — TransactSqlParser.Located — holds the same published methods, each of them asking. A call through the class itself does not ask, and pays a test per construction for the choice. The interface must then declare a three-argument Locate(int at, int length, int gapStart), where the gap start is where the text between the value and the token before it begins: the end of that token, or where the reading began.

The nested class holds the forms over a string and over segments. The forms over a buffered input — a TextReader, a Stream, bytes — are written on the class itself only; a grammar that wants them located names a second reading without UsePerCallLocations, compiled with locations in.

DotGramPositionalFollow (experimental)

An MSBuild property rather than an attribute option: it applies to every grammar the build compiles, and is off unless set to true.

<PropertyGroup>
  <DotGramPositionalFollow>true</DotGramPositionalFollow>
</PropertyGroup>

A positional parse has whole forms, which demand the end of the input, and the forms that begin at a position or read a window (§6.3), which demand nothing after the rule. The rule is compiled once for both, and by default against the end of the input. Some decisions taken on the strength of that end hold for the whole forms only: a way back to an optional's skip is not kept, a repetition's turn is taken as final because the end could not begin where it stopped. From a position such a decision can refuse or cut short the rule's first reading, which is what §4 says a reading from a position is. Which reader goes wrong depends on the shape: Start = (R1 | R1)? with R1 = 'a' & 'k', read from 0 in ab, answers no reading where the rule reads nothing, in the shared automaton only; '"' & ("\"\"" | [^'"'])* & '"' from 0 in "a""x refuses where it reads "a", in a publication read by methods only; and ('a' & 'b' | 'a' & 'c')* & ?!'x' from 0 in abacx refuses where it reads ab in both. The whole forms are right either way.

Set, every parse is compiled knowing that it is also read from a position, whether or not its directive says positional, and the forms of those that do give the rule's first reading. The whole forms accept the same texts, but lose the proofs they rested on, and that is the cost: in this repository's own packages the JSON, JSON Pointer and URI Template readers stay on the immediate carrier and are told (GRAM5012) that their constructions can now run again for text read a second time. A token grammar (Lexical) changes only the order of its expected-token tables. The property is for a build that needs the positional forms right now and accepts that cost; the default stays off until the analysis can tell the two kinds of entry apart.

Set to split instead, it is the same switch with the two kinds of entry told apart where that changes no answer: experimental too, and off unless the property names it. After a reading from a position nothing is demanded, so nothing after the rule can fail; the proofs that ask only that — whether a repetition may be asked to give back a turn it completed, whether a longer literal may be asked to give way to a shorter one — are told so, and hold for the whole forms as they did without the switch. A look, a guard (when), a selector — even one with a case that reads nothing, since it picks that case and does not try the others — or a recognizer the host writes between the construct and the end of the rule can fail, and from there the proof is answered as true answers it. Every other question — whether what follows can begin where a body that failed began — is answered as true answers it too. Every reading is meant to answer as under true, and the tests hold it to that on this repository's web grammars and on generated shapes; what differs is the reader the generator writes. In this repository's packages only the readers whose rule ends behind a when would move from the immediate carrier: the fragment form of JSON Pointer, which does, and the Set-Cookie reader, which names its carrier and keeps it.

DotGramNoCache

An MSBuild property like the one above, and off unless set to true. It changes nothing a parser reads or builds; it changes only whether the generator compiles a grammar it has compiled before.

The generator keeps the parsers it has compiled, in memory, for as long as the process that loaded it lives. A command-line build runs in the compiler server, which outlives the build by some minutes, and the next build of the project after an edit to its C# alone — one that leaves the grammar, the attribute's options and every answer about the host's C# types as they were — takes the parser from there instead of compiling the grammar again: seconds a build for a grammar of a thousand rules. A parser is found by everything its compile reads, so an edit that changes any of it compiles afresh. What is kept is bounded — up to about 80 MB for each version of the generator the server has loaded, and at most 64 parsers — and a parser the compile failed inside of (GRAM0001) is not kept. Builds inside an editor keep nothing. A generation report says cached where its time would be.

<PropertyGroup>
  <DotGramNoCache>true</DotGramNoCache>
</PropertyGroup>

Set, every grammar is compiled afresh. dotnet build-server shutdown empties what is kept as well, with the server it lives in: either is the thing to try where a parser looks older than the grammar it was compiled from.

Attributes for tooling

These describe the language to editors. An editor reads them rather than executing them, and they change nothing a parser reads or builds.

Attribute What it says
[GramLanguage(id, Extensions = …)] a stable identifier for the language, unique to whoever owns it — a reverse domain name is the usual shape — and the file extensions it claims, with the dot
[GramClassify(target, role)] gives a rule (Keyword) or a capture of one (Declaration.type) a role from GramClassification: Keyword, Identifier, Type, Variable, Function, Method, Property, Number, String, Comment, Operator, Punctuation, Namespace, Parameter or Label. A capture's role overrides its rule's
[GramToolingGuard(expression, accepted)] the answer an editor takes for a guard it does not execute
[GramToolingExternal(method, rule)] a grammar rule equivalent to an external recognizer, for an editor to read in its place

A role says what something means, not how it looks: an editor's theme decides that.

Two more are written by the generator and never by an author. [GramSource] carries the grammar's text on the class it compiled, which is how an include across a project reference finds it (§6.7). [GramLanguageDescriptor] carries a versioned description of the language on a generated parser, for tooling to read.

6.9 Tracing a grammar

Trace = true on [Gram] or [GramParserVariant] makes a reading a trace build: its parser reports what it does — each rule it enters and leaves, each refusal and what it wanted, each guard it asks — to a sink the caller sets. The build property DotGramTrace asks the same of every grammar in a project, typically for a Debug build only:

<PropertyGroup>
  <DotGramTrace Condition="'$(Configuration)' == 'Debug'">true</DotGramTrace>
</PropertyGroup>

Off, nothing of it is written: the parser is the same text byte for byte as a parser built without the option. A traced reading may stand beside an untouched one, the way any second reading does (§6.6):

[Gram("Expressions.gram")]
[GramParserVariant("Traced", Trace = true)]
public static partial class Expressions { }

Expressions.TryParseSum is the parser as it was, and Expressions.Traced.TryParseSum the same grammar traced.

The sink and its scope

A trace build declares, in the class its parser goes into and public when that class is, the abstract class GramTrace, whose methods do nothing until overridden, and the scope that sets one — here in Expressions.Traced, with the sink that says why an input was refused:

var why = new Expressions.Traced.GramWhy();

using (Expressions.Traced.Tracing(why))
{
    var match = Expressions.Traced.TryParseSum("1+(2+");
}

Console.WriteLine(why);
// Expected ['(' | '0'..'9']. (line 1, column 6)
// The rules below were reading there, each wanting what it names.
//   wanted ['(' | '0'..'9'] in Sum 1:1 > More 1:2 > Term 1:3 > Sum 1:4 > More 1:5 > Term 1:6

Tracing(sink) reaches every reading begun in the same flow of control until the scope is disposed, which puts back what was set before: a reading carried onto a stack of its own (§6.5), a nested parse that a construction or a guard starts, a reading awaited in a task begun inside the scope. A find or a yield takes the sink that was set where it was called, not where its first element is asked for: each step it reads reports there, and so does a parse a guard or a construction starts during the step, the sink set where the step is asked for being put back before the element is handed out. Each traced class has a GramTrace of its own — two hosts do not share one, and a sink that serves both is an adapter over the two.

What a sink is told, all of it as numbers so that nothing is allocated per event:

Method When
Begin(GramRead read) a reading begins: a TryParse that refuses reads quietly first and again recording, and a find reads at every start
End(read, end, position, expected, expectedMore) the reading ends where end says, or -1 where it refused, with the furthest refusal it recorded: the sets Match.Error is worded from. When more than 16384 sets tied there, the list holds the first 16384 and ends with a set holding only GramTrace.TruncatedTies, which is no thing wanted: the message names the sets before it and says "among others"
Enter(rule, position) / Exit(rule, position, end) a rule is entered, and leaves at end, fails (-1), or is left by an exception (GramTrace.Thrown, -2)
Retracted(rule, position) on the engine, a rule that returned has what it read taken back: the engine went back to a way it left open before the rule ended, or inside it — then an Enter at the same position follows, the rule read on from inside
Remembered(rule, position) a rule entered where it already failed in this reading fails at once without being read (a reading over tokens remembers)
Guard(guard, position, passed) a guard (when) was asked
Refused(position, expected) a recording reading could not go on, wanting one of expected; null where the refusal names nothing. Quiet readings and lookaheads refuse without a word, as neither's refusals are ever the answer
Recovered(rule, from, to, reach) a repetition marked recover stepped over an element (§8.2)
Deepened(position) the reading moved to a stack of its own (§6.5)
Unlexed(text, position) over tokens, no token begins at a character, so the input was refused before any rule was read; with a sink set, and where the grammar runs nothing of its author's (below), the tokens before it are then read once more, as a reading of its own, to tell which rules were reading where they ran out
Rejected(position, message) the call answered with a refusal: the match's position and its Error. Wording the message costs a refused call more than reading it did, so a sink that does not read it overrides HearsRejections to say false, as GramProfile does, and is not told

A sink is the host's own code, as a guard or a construction is (§7.5): what one of its methods throws goes out of the call that was reading, Try or not, and the reading stops there. Whatever leaves a reading by an exception — a sink, a guard, a construction — the sink is told all the same that each rule it was told was entered is left, innermost first, with GramTrace.Thrown for an end, and then that the reading ended, refused: every Enter has its Exit and every Begin its End. What a sink throws while it is told this is dropped; the exception that left the reading is the one that goes out.

GramRead says what the reading is: the rule published, whether it is Quiet, whether it is one start of a find, which Machine reads it — methods, a method a rule; engine, one automaton over an arena; flat, one method for the whole reading — the Text, the names of the rules and the C# of the guards by the numbers the events carry (RuleName, GuardText), OverTokens, whether the positions the events carry are tokens rather than characters (a grammar read over tokens, §4), and CharacterOf, which turns a position into a character of the input — a position over tokens is a token, and is turned into the character its token begins at — and Locate, its line and column. A reading over a TextReader, a Stream or bytes (§6.3) has no Text, and counts its positions from the beginning of the input, not of the part of it held in its buffer. Every position the trace tells or hands back — an event's, Start, CharacterOf, the positions of GramWhy's paths and elements — is a long, as Match.Position is (§6.3).

Three sinks, ready-made

  • GramWhy — why the last call watched was refused. Its Message and Position are the match's own, handed over by the call, and its Paths are the rules that were open where the input was followed furthest, outermost first with where each was entered, and the part of the expected set each wanted there. A refusal kept is one whose set the failure ended with, so what it explains is what the message says: a set a later refusal covered, a refusal inside a lookahead and the words of an on fail are already applied to what it is held against. A refusal that names no set is explained by the rules that refused there, a guard by its C#, the end of input by the rules it ended inside, a character no token begins with by the rules that were reading where the tokens before it ran out — where the reading got that far, the reading writes into no context (§7.7), and the grammar has no construction in C#, no constructor or initializer of a type, no guard and no recovery factory: the tokens are read once more to say it, and neither a context nor the host's code is to see a reading the caller did not ask for, which happens only with a sink. Elsewhere the stop is said alone. A rule remembered as failing (above) shows the path through its first caller, not through a second. A repetition marked recover is explained element by element in Elements, then the refusal itself if the reading still failed. It explains the parser's own answer: a host that rewrites a refusal after the parse answers in words of its own. Each refusal costs it one entry however deep the reading is: a JSON text opened fifty thousand deep and never closed is explained by a process of about a hundred megabytes.
  • GramTraceLog — an indented log to a TextWriter: each rule entered with the text there, each rule left, each refusal and guard. It writes up to a budget of lines (10,000 unless said) and then counts the rest, and sums up the starts a find refused in one line.
  • GramProfile — for each rule, how often it was entered, read and failed, how often the engine took back what it read, how often it was answered from the memory of a failure, how often it was entered again at a position the same reading had entered it at, the time inside it with and without what it called, and the deepest stack it was entered on. Quiet readings and recording ones are counted apart: they are different programs, a quiet reading not sharpening where a refusal is and not trying what only a message would need.

None of the three throws for what it is told, whatever the order of the events; what GramTraceLog writes to is the caller's writer, and what that throws — a writer disposed before the scope is — goes out of the reading as anything a sink throws does. Each is for a reading at a time, and is not to be shared by readings that run at once. A reading begun inside another is bracketed by its own Begin and End: the log shows it nested, the profile counts it, and GramWhy explains the outermost.

What a trace build is

A slightly different program from the one it observes. Every return of a rule's method reports it, so its frames are larger, a deep reading moves to a stack of its own a little sooner, and what GramProfile times is the trace build — the proportions of the parser, a little slower than it. What it answers is the same, refusals word for word. With no sink set a reading pays a field read where each event would be, and allocates nothing.

A rule that only hands on another rule's value (Operand : @T = o: Guard => @(o) | o: Quantified => @(o)) is compiled into the rules that call it, and a trace reports it where it stood all the same, as a frame around what it became: a stack shows the rule where the author wrote it.

Every way a grammar is read is traced: by methods, on the engine, by one flat method, over a string, a reader, a stream or bytes, whole, from a position, in a window, as a find, a yield or a parse handed over a part at a time. What the reading is compiled into decides which rules report, as each has to be somewhere to report from:

  • Methods report every rule — a forwarding rule where it stood, as above.
  • The engine reports every rule it calls. A small rule it writes into its caller instead, and the rules a rule read at a stretch is made of — a rule that recognizes and keeps nothing, read by a scanner of its own — are code of the rule around them and report nothing of their own; a rule read by a scanner is entered and left where the scan began and ended. The engine can go back into a rule that has returned, which methods never do: a rule whose success is given up so is Retracted, once its entry on the arena is taken off it. A success given up with no entry left to take — inside an atomic group or a look ahead already passed — is not told.
  • A flat method reads a whole publication with every rule written into it, and reports the one rule it reads, what it refused and the rules it scans.

A parse over a reader handed over a part at a time (§6.3) reports each part it reads as a reading of its own; what it only asks — whether the trivia, the rest of the rule or the synchronization stands next — is not told. Constructions and the values they build are not traced.

7. The bond with C#

This is the language's other half, not an appendix to it: the grammar describes structure, C# describes meaning, and the seam between them has to be mechanical.

7.1 Recognizer signatures and C# values

Only a method used as a recognizer needs a shape the generator understands, because it participates in moving through the input. A method or expression used by when or => is emitted as C# and belongs entirely to the consumer's compiler:

C# signature Role Called from the grammar as
bool M(char c) element predicate [@M] inside an element set
bool M(ParserInput<char> input, ref int pos) external recognizer, the form to write: it serves strings, readers and streams bare @M as a grammar operand
bool M(ParserInput<char> input, ref int pos, out T value, Context context) the same with a value and the context; both trailing parameters are optional bare @M
bool M(ReadOnlySpan<char> input, ref int pos) external recognizer over a string only, faster where nothing else is read bare @M
bool M(ReadOnlySpan<char> input, ref int pos, out T value) the same with a value bare @M
any C# value construction => @M(a, b), => @(expr)
any C# bool value guard when @M(a), when @(expr)

A recognizer is written over ParserInput<char> unless there is a reason not to: one method then serves every publication of the grammar, a string, a TextReader and a stream alike. The span form is faster, and right where the grammar reads only strings; it cannot serve a buffered reading (below).

Everything under the @ is the consumer's own C#, and the grammar does not look inside it. => @M(a, b) and => @(M(a, b)) are one construction written two ways: both go across as text, so a name in either needs no @ of its own, and both see the same things — the rule's captures and the names of §8.2, which are what the generated method takes as parameters.

=> @int.Parse(digits, CultureInfo.InvariantCulture)      // a capture, then a C# name
=> @(int.Parse(digits, CultureInfo.InvariantCulture))    // the same thing, one bracket out
=> @Hold(parserInput, parserSpan)                        // and the supplied names, likewise

This is the one place §2's rule stops. Outside an @ a bare name is the grammar's — a capture, a rule, a parameter — and that is unchanged, including in the argument list of a call to a rule. The line is the @, not the bracket.

It stops there because resolving names inside a consumer's C# would mean keeping up with C#, and every construct this compiler has not learnt would become one the language forbids for no reason of its own — and two spellings of the same construction would not accept the same things.

There is one rule to read this by: syntactic position determines the call shape. [@M] emits M(c), bare @M emits M(text, ref p), and when and => emit their C# values. The generator never inspects a method signature to choose among those roles; overloads, accessibility, parameter types and result types are C#'s responsibility.

Two exceptions, narrow and specific, both about bare @M. The first: it alone does not say whether M is the second row or the third, since the notation is the same either way. The host is asked whether M has an out T recognizer overload with either input form, looked for where the generated call is bound — in the class the grammar is attached to, around it, in what it derives from, in the class of a grammar it includes, or in a class a global using static imports — as C# itself binds the call where the generated code stands: the host's own method of the name hides an imported one, and an import brings in neither what a class inherits nor its extension methods. Finding one hands the rule-shaped identity a value-producing call needs; finding none leaves bare @M the second row. More than one such overload with a different T is a tie, reported rather than guessed at, the same as an ambiguous constructor (§7.3).

The second: whether M can be called in its role at all — as a recognizer where it is bare, as a predicate over a character where it is [@M]. Where no method of that row's shape is in reach of the class the grammar is attached to — in it, around it, in what it derives from, or in the class of a grammar it includes — that is said about the grammar (GRAM4025), rather than by the C# compiler about a call in a generated file. It is said only where it is certain, and it changes nothing about what @M means: the role is still the position's. A method the generated class writes for a publication (ParseStart, TryParseStart, FindItems) is one of those in reach, and hides a method of the same name outside the class, so a recognizer named like one is refused the same way. The host also identifies whether a bare recognizer uses a span or ParserInput<char>, and whether the latter takes a context argument. Declare one character-input contract per recognizer name.

The same C# name may therefore implement both contracts without ambiguity:

One  = [@Foo]
Many = @Foo

The first call selects bool Foo(char), the second bool Foo(ReadOnlySpan<char>, ref int) by ordinary C# overload resolution.

The span-based recognizer's signature uses BCL types only; nothing emitted appears in it (§6.2). An input-view recognizer uses the host's generated ParserInput<T> instead. Both forms keep the same bare @M notation. Its value is the text it covered — the same as any rule that captures nothing.

The generated code calls a recognizer or a predicate through a method of its own, so that nothing the reader declares can hide the author's method and the overload is chosen as in the author's own C#. The names of the generated code contain _DotGram; a name written in a grammar that contains it is refused (GRAM1012), and the members of the host class whose names contain it are reserved for generated code. A parameter attributed [CallerMemberName] or [CallerArgumentExpression] is given the generated method's name and its argument's text, not the reader's.

A recognizer is trusted absolutely, and that is the bargain. The ref is the method saying that it moves the position; it is handed the parser's own, and nothing copies it away, bounds-checks it afterwards, or reasons about what came back. Move it backwards, move it past the end, leave it somewhere that makes the rest of the grammar nonsense — all of that is allowed and none of it is diagnosed.

This is deliberate. A seam that second-guessed the code on the other side of it would still not make a wrong recognizer right. Reaching into the parse means taking the parse's invariants on with it.

A span-based external recognizer gets no streaming overloads (§6.3): it cannot distinguish the end of a buffer from EOF. For buffered input, declare the callback in the parser host using the generated ParserInput<char> type. Add a ParserInput<byte> overload for stream bytes; the character overload also serves contiguous input. The optional last parameter receives the grammar's declared context : @Context. An optional out T precedes the context, if present.

Data = @ReadData
static bool ReadData(ParserInput<byte> input, ref int position, Context context)
{
    return input.TryAdvance(ref position, context.Length);
}

Ensure(position, length) reads until the requested extent is available or EOF is known. TryAdvance(ref position, length) does the same and advances only on success. Peek(position, out value) reads one element without advancing; Slice(position, length) returns a borrowed span and throws if the extent is unavailable. Negative arguments throw; an extent beyond int.MaxValue fails Ensure without advancing. Positions are absolute, including after earlier yielded records have been released. Do not access released input or retain a borrowed span across another input operation or callback return. Buffer growth and retention limits are the same as for grammar rules; callbacks cannot release buffers or bypass the configured limit.

Refilling does not restart a callback. Grammar backtracking can call it again, and value-producing callbacks are called again when their result is materialized, as with span-based recognizers. Keep speculative side effects and context changes consistent with those rules. Input-view recognizers use character parsing when a lexical split is requested; their reads can depend on the current syntactic context. No runtime assembly is required: the input view is emitted into the parser host.

A terminal the lexer begins and something else ends. In a grammar cut into a lexer and a syntactic half (§4, Lexical = true), a terminal is read by one automaton together with every other, and an automaton reads only regular languages. Comments that nest, interpolated strings, raw strings whose delimiter varies are not regular. They are written as a regular beginning followed by one operand that is not:

namespace Lexical
{
    trivia = none

    Comment = Std.Nested("/*", "*/")
    Remark  = "(*" & Rest
    Rest    = ([^ '*' | '('] | '*' & ?!')' | '(' & ?!'*' | "(*" & Rest)* & "*)"

    Blob    = '<' & @ReadBlob
}

The automaton reads the beginning with every other token, so longest match decides between them as it decides everything else, and nothing is asked where the beginning does not stand. Where it does, the rest is measured from where the beginning ended: by the grammar's own rule, read over characters, or by the host, handed the position after the beginning. The lexer learns nothing about nesting or quoting. A kind of it is simply measured elsewhere. Std.Nested(open, close) (§5.2), alone or last, is such a terminal without being written as one: its open is the beginning, and the rest is read by its counter, so a pair the text ends inside of is cut short as the rule over characters would say. A terminal written this way may build a value like any other, and its value is read over the whole token.

A terminal that binds text (§3.5.1) is begun the same way without being written as one, and its rest is read differently: the binding stands in the beginning, so a rest measured from where the beginning ended would have no text to compare with. The automaton reads the longest beginning it can — the leading operands up to the first that is not regular, a binding read as its body, a choice as either alternative's beginning — and the terminal's own rule then reads the whole token again from its start:

namespace Lexical
{
    trivia = none

    LongString = { '[' & $eq: '='* & '[' & (?!(']' & $eq & ']') & any)* & ']' & $eq & ']' }
    Heredoc    = { "<<" & $tag: Name & eol & (?!($tag & EndLine) & Line)* & $tag & ?=EndLine }
    Name       = ['a'..'z']+
}

Index = '[' & Lexical.Name & ']'
Shift = Lexical.Name & "<<" & Lexical.Name

LongString begins with '[' & '='* & '[' and Heredoc with "<<" & Name & eol; where either stands, its rule decides the token, and its length is that reading. Where the rule refuses — [==[ with no closing bracket, <<end with no closing line — the position is lexed again as if the terminal were not there, and the bracket or the operator stands, as it would over characters. The beginning read twice costs its few characters.

Such a terminal is one token only where that cannot change the answer. Its body is atomic: read over characters, the same rule could otherwise give part of its reading back and read on another way, where the token's length is settled. And no other token, nor trivia, can match a longer text that begins like it — a mark "abc" beside { $q: "ab" & $q }, a comment '#' & [^ '\n']* in the trivia beside { '#' & $q: '"'+ & … }, or two such terminals of which one's beginning begins the other's — since the token would then be shorter than what longest match gives a regular token in its place. A token as long as the beginning's string is no competitor: the kind is both, the rule decides, and the syntax asks for the one it wants. Anywhere else that part is read over characters, with a GRAM5004 that names the token in the way and the fix: write { } around the body, keep the competitor from continuing the beginning, or put both forms in one terminal as alternatives — Str = { $q: '"'{3,} & … & $q | '"' & … & '"' }, where the terminal's own ordered reading tells them apart, the same in both forms. A terminal that begins with nothing an automaton reads — a lookahead, a host recognizer, a rule that reaches itself first — is refused by name (GRAM4034).

A terminal that binds nothing gets the same reading where the automaton would otherwise read it wider than its rule does, which is a token its rule refuses and a value that is null: a guard, which the automaton takes as an empty match; an atomic group it reads with a way back that the group does not take; an ordered choice whose earlier alternative matches a proper prefix of a later one, where the rule stops at the earlier and the automaton reads on. Such a terminal is begun by the automaton's reading and measured by its own rule from the token's start, and where the rule refuses the position is lexed again without it. This is done only for a terminal in braces; one that is not atomic stays over characters with a GRAM5004.

Such a terminal's guard, and the construction of any terminal, may name the grammar's context (§7.7), and a rule it reads may hold a when … is … that two publications answer differently (§5.1). The lexer measures the terminal with the context the publication was handed and as the reading the publication is, and a value built from a token is built with both, as over characters. The tokens are cut before the syntax reads anything, so a guard there sees the context as it was handed over, not what the syntax's own guards have written into it by the time the parse reaches the token; and a token's value is read again when it is built, so a guard that answers otherwise by then gives another alternative's value, with nothing to say so, or refuses the token, which throws an InvalidOperationException naming the terminal and where its token stood. GRAM5019 warns of such a guard; a terminal whose value is its token's own text is not read again, and is not warned of. A check of the context in a terminal has to give the same answer throughout the parse: what it reads belongs in the context as configuration the syntax never writes. A grammar whose terminals depend on what the syntax has read so far is a grammar for Lexical = false, where a terminal is read where the parse reaches it. A cutting whose measuring reads the context is the parse's, not the string's: it is not kept for the next reading of the same string. One that only tests the reading is kept beside the reading it was cut as.

The beginning has to be the terminal's alone. One that can be empty, or that is also a token of its own, is refused (GRAM5004): the lexer would have a string it cannot give one meaning to. A terminal that is nothing but @M has no beginning at all, so the host is asked at the start of every token before the automaton runs, which GRAM5011 says.

An inline @(...) expression plays the same role as a value transformation, only without a name: it receives no input, sees captures as local variables, and is checked by C#'s type system exactly where the generator placed it.

Overloads, generic methods, extension methods and nullable annotations are resolved by ordinary C# rules.

7.2 What the C# side must guarantee

  • A value transformation has no access to the input — it physically never receives it.
  • An external recognizer must restore pos to its entry value on any outcome other than success.
  • An external recognizer may succeed without moving pos. Inside a repetition, the turns up to its fewest are read and counted however far each moved, as the repetition written out turn by turn would read them (§3.3: xs: V{3} holds three values); past the fewest, a turn that ends where it began is not taken, and the repetition ends before it. So (@M){3,} over an M that does not move reads M three times, and (@M)* none.
  • An external recognizer and a when guard execute during recognition. Ordered choice and lookahead may invoke them repeatedly or abandon the path on which they ran. Their code must therefore be safe for speculative invocation and must not perform effects that require rollback.
  • The answer of a when guard, a switch selector and an external recognizer depends only on its arguments and the text — not merely "no side effects": it may not read state that changes while the input is read. The same holds of a => construction whose value such a check reads: that value is built during recognition, and it may depend only on its captures and the text. A reader over tokens remembers where a recursive rule failed — and, for the rules §4.7 names, where it succeeded and what it built — and answers the next entry there without reading it again (§6.5), which holds only if asking again could not have answered otherwise. A hook may still read context by that name, which the generator can see: a rule that reaches one is read again every time. State reached any other way — a static field, a context kept somewhere else — it cannot see, and a check that reads it may be answered with a failure remembered from before the state changed.
  • When a => construction runs is the carrier's (§6.8). Carried immediately — the default for a grammar that names no carrier — it runs as its alternative is read: also for a path ordered choice later abandons, and for the prefix of a refused input, so its code must be safe for speculative invocation as a guard's is. It runs interleaved with the hooks that run during recognition: where a construction and a when, a switch selector or an external recognizer handed the context share context, the hook sees what constructions read before it wrote, and a construction that reads context sees it as it stands where the construction is read — in both directions, what the grammar accepts and the values it builds can differ from the deferred carrier's, and GRAM5016 says so. Deferred (Carrier = GramCarrier.Deferred), a construction is deferred until the accepted derivation is known unless a when guard explicitly inspects its value: captures record what matched and the chosen factory builds only the accepted path. A value requested by a guard is built during recognition, cached, and reused after acceptance; it may therefore have been built on a path the guard or later input abandons.

7.3 Captures and building the result

Captures are matched to the result type by name, in a fixed order:

  1. a constructor whose every parameter is covered by captures;
  2. init/required properties;
  3. an explicit => @Factory(...) when neither fits.

Names are matched by one mechanical casing transform: the capture symbol fits the parameter symbol and the property Symbol.

A handful of names are supplied rather than captured: declare a parameter with one of them and the generator fills it in. They are listed in §8.2, where the same names serve a rejected element — parserSpan and parserText for the extent and the input it covers, parserOrdinal, parserLine, parserColumn and parserPosition for where it was.

A rule that captures gets a type of its own, nested in the generated class and named after the rule, with its namespaces joined to the name by _. Where that name is already taken in the class — by the class itself, by a type or a member it declares under a plain name (Match, Outcome, SourceSpan, ParserInput, Failure, ParserEntry, and the rest of §6's list), by a method it makes from a name of the grammar's (Name and TryName of a publication), or by another rule's type — Value is appended until it is free, and a rule that keeps the name it has is never the one renamed. A name the class makes from a rule's (§6) carries _DotGram, so a rule may be called anything else: A_Whole beside a published A, Construct_R beside R, DotGram. Two rules whose names come out alike once their namespaces are joined (A.B and a rule called A_B), a rule whose joined name would hold _DotGram (DotGram_B in namespace A), and two captures of one rule that become one property (a and A), cannot be told apart in the code that is written, and are refused where they are declared (GRAM5018).

A capture's own type follows from what it captures:

Captured Type
a rule reference that rule's result type
a literal, an element set, or a group of those string — the matched text
a quantifier over something that yields text string, the text joined — not char[]
a quantifier over a rule that yields a value T[]

The two quantifier rows are what makes the regex-shaped case behave: scheme: ['a'..'z']+ gives "http", while items: Row* gives Row[]. Both are the same principle as §4.1 case 4 — where nothing produces a value of its own, the value is the matched extent — applied one level down, at the capture.

A binding $q: X (§3.5.1) is not a capture and is not a member of the result: the type of a rule is what its captures make it, whatever it binds.

A capture binds tighter than a quantifier (§3.8), so scheme: ['a'..'z']+ is one capture repeated rather than a capture of a run — and the two rows above are how that is read: repeated text is the text joined, a repeated rule is an array of its values.

An optional capture and an empty run are different answers and stay different: (sign: '-')? that did not match is null, while digits: ['0'..'9']* that matched nothing is "" — the text of no iterations. Every quantifier but ? is a run, whatever its bounds: digits: ['0'..'9']{0,3} that took no turn is "" as well, in a rule of one alternative or of several. ?, which {0,1} spells out, is the one option.

Url = scheme: ("https" | "http" | "ftp") & "://" & host: Host
// generated when no C# type exists
public sealed class Url
{
    internal Url(string scheme, Host host) { Scheme = scheme; Host = host; }

    public string Scheme { get; }
    public Host   Host   { get; }
}

This is what a regex's named group becomes: a member of a known type, checked at compile time, rather than Match.Groups["scheme"].Value looked up by string at run time. And it can be typed all the way — scheme: Scheme with Scheme : @UriScheme hands back the enum instead of the text.

When no accessible C# type exists for a rule, an ordinary class with the same members is generated — a constructor and a get-only property per capture, and nothing else. The constructor is internal: its parameters are the captures in the order the grammar writes them, so a grammar that swapped two captures of one type would swap what a caller in another assembly passes, and nothing would say so. The parser builds the value and code in the same assembly may; outside it, the value is read. A value to be built elsewhere — by hand, by a test, by another assembly — is a type of the host's own, named with : @T (§7.1). Not a bespoke node framework, and not a record: a positional record needs IsExternalInit, which lives in System.Runtime.CompilerServices, and §6.2 is why nothing is ever emitted into a namespace that is not ours. A consumer targeting an older framework has their own copy of that type from a polyfill package, and a second one is a compile error in their build rather than ours.

7.4 C# stays C#

The generator does not resolve or declare methods named by when and =>. It emits the call exactly as written, under the #line mapping of §7.6. A missing name, a wrong overload, an inaccessible member or an incompatible result is therefore an ordinary C# diagnostic at the corresponding place in the grammar.

Number : @int = digits: ['0'..'9']+ => @Tini(digits)

If the host contains Tiny rather than Tini, the compiler reports the misspelling. The generator does not turn an unknown name into a partial-method contract.

7.5 Recognition outcomes

Inside the language an outcome is an ordinary value, never an exception. The type is emitted by the generator into the assembly itself:

public readonly struct Match<T>
{
    public bool    IsSuccess { get; }   // Outcome == Outcome.Success
    public Outcome Outcome   { get; }   // Success | NoMatch | Starved
    public T       Value     { get; }
    public long    Position  { get; }
    public int     Length    { get; }
    public string? Error     { get; }
}

public, unlike the support types of §6.2, because a published method hands it back and an internal type cannot appear in a public signature (§6.2). Position is a long because an input may be larger than an int can index (§6.3), and Length an int because an extent is into a buffer. Error is built where it is asked for rather than where the match failed, so a caller who only wants to know whether the input matched pays nothing for the words.

Outcome says which kind of answer this is, and the two failures differ. NoMatch is input that was there and did not fit; Starved is input that ran out where more was needed — the answer a caller reading from a stream acts on differently from the one reading a finished document. Both are exact: the furthest position the parse reached (outside the trivia, below) is either the end of the input, or a place where something wanted more characters than remained. A literal the input ends inside has run out only where every character there agrees with it, and is then refused at the end; where one does not, more input could not change that, and the refusal is NoMatch at that character. So T = "/*" & ';' refuses / as Starved at 1 and /x as NoMatch at 1.

Over characters, inside the trivia — and in the rules it reaches, while it reads them — a refusal is recorded only where the input, or the window, ran out. A turn the trivia gives back, a look refused on input that was there, a rule it called and refused say nothing: the parse answers from what follows the trivia, as if the trivia had read what it could and stopped, so the furthest position is counted outside it. A literal the input ended inside, a terminal refused at the end, or a look whose body ran out starves the parse there, since more input could have finished the trivia. So with trivia = { ('#' & 'y'+)* } and R = 'z', #a is NoMatch at 0 — where R stands, not where y was wanted — and # is Starved at 1; and with trivia = { (' ' | Std.BlockComment("/*", "*/"))* } and R = 'z' & 'q', a comment left open at the end, z /* x, is Starved at 6. Over tokens the trivia is the lexer's, and a comment it leaves open is read as §6.3 says.

What Error names is sound, not complete. An alternative it names would have been accepted where it says; the set of them may be narrower in one form of the input than in another. A reading over a buffer or a stream cannot read its input twice, so it records while it reads, and a repetition whose next turn cannot begin here is left untried in one form and tried in another — a turn not tried says nothing about what would have ended it. The outcome, the position and the value do not vary this way: those are the same in every form, and what a host branches on.

A rule's own on fail (§4) is what Error says, where that rule is the refusal. The rule has to have been entered where the parse stopped and read nothing: a rule that read part of what it wanted and failed further in is not what went wrong here, and what it wanted there is the better answer. Where one applies, it is the whole of Error — the author took the wording, and nothing is appended to it. Being part of Error, the sentence is held to what Error is held to above, not to the outcome's standard: a form may name what it expected where another says the sentence (status.md lists where this version does).

A guard that said no is named where nothing else is. A when refused at the furthest place is recorded there like a terminal, as the guard the grammar wrote, and it is the weakest thing that can be said: where anything else is named at that place, that is what would have fit, and the guard is left out; where nothing else is, Error is that it said no, when @(IsTime(at)) said no. — several such guards joined by "or" — and a recovery's parserMessage and parserExpected say the same. The outcome is what it was: a guard refused at the end of the input is Starved, as any refusal there is.

A guard may say it in words of its own, with on fail after its C#, as a rule may after its type (§4):

Target : @string = text: TargetText & when @(Rfc3986.TryParseReference(text!, out _)) on fail "Expected a valid URI reference." => @(text)

The words are said exactly where the guard's C# would have been — where it refused at the furthest place and nothing else is named there — and are then the whole of Error, as a rule's on fail is; the position, the outcome and the ties are what they would have been without them. Where two guards refused at one place, the first with words of its own says them. on fail there without its string is GRAM2003.

Exceptions appear only at the publication boundary, and only in the methods without a Try prefix — where a .NET developer expects them. What is thrown is FormatException: the same type as int.Parse throws, and one that requires nothing shared between assemblies.

An exception the host's own code throws is not an outcome. A factory after =>, a guard after when, an external recognizer: what they throw propagates from every publication, with or without the Try prefix, as any exception of C# does (§7.4). A Try method that turned it into a refusal would report a defect of the host as input that did not fit. The parser never lets escape an exception from a reading it has abandoned — deferred (Carrier = GramCarrier.Deferred): host code is asked about what the parse reads, and a reading the parse gives up cannot fail it. Carried immediately, the default, a construction runs as its alternative is read, and one that throws on a reading the parse would have given up escapes the publication, Try or not, and a throwing Parse can surface it instead of the parse error. A grammar left to choose whose constructions can run there is told so (GRAM5012); one whose constructions may throw there names Deferred, puts every such construction behind a guard that answers first, or says so:

[Gram("…", Carrier = GramCarrier.Immediate, ConstructionsMayThrow = true)]

A grammar whose constructions may throw can say so. With ConstructionsMayThrow = true the immediate carrier holds what a construction throws: the reading goes on with the value left default, and the held exception is thrown where the deferred carrier would have thrown it — when the publication builds its answer, or where a when or switch asks for a value it was thrown under — from Try and Parse alike. An exception held in a reading the parse gives up goes with it, and a refused parse throws nothing it held: the refusal is the answer. A construction of a rule whose reading already holds an exception does not run, as with the deferred carrier, which would have thrown before it. Of several held, the one thrown is the first raised under what is asked for — at acceptance the first of all; a later one, handed the default an earlier left, is not. One thing is wider than the deferred carrier: a guard naming a fold's value so far, or a sequence gathered across turns, throws the first exception held since its rule began, under whichever value of that rule it was raised. What a guard or a recognizer throws is not held: it runs during recognition on both carriers and propagates at once. The hold is a handler around every construction and a copy at every way back, paid whether anything throws or not, so it is not the default: a grammar none of whose constructions throws is compiled without it. The deferred carrier ignores the option; it has nothing to hold.

7.6 Mapping positions back

Generated code carries #line directives mapping it back into the .gram file. This is not a convenience but a condition of the seam working at all: => @Add(l, r) is checked by C#'s type system, and when the types do not agree the error must appear on the grammar's line rather than in a machine-written file. The same goes for breakpoints and for "go to definition" in both directions.

7.7 What a parse works out and the API has nowhere to keep

Some grammars need somewhere to put what the reading works out: a table of names, the label a jump goes to, whatever the language being read means by scope. A => cannot hold it — deferred it runs after the whole match, and carried immediately it runs as its alternative is read, interleaved with the guards that would read it, which is what GRAM5016 warns of — and a when that writes into a static field has made that field global, which is a bug waiting for the second thread and the second parse.

So a grammar may declare one:

context : @Names

The type is a C# name this notation never resolves. It is written into the generated signature and checked where it is written, exactly as a rule's own : @T is.

The caller makes one and hands it over, and every publication of that grammar takes it:

var names = new Names();
var tree  = Grammar.ParseLambda(text, names);

context is then a name a => and a when may use, like the supplied names of §8.2 and under the same rule: a hook that does not name it is not passed it, so a grammar that declares a context and never uses it is compiled exactly as one that declares none, and its publications take no extra argument.

Local = type: Type & name: Word & when @(context.Declare(type, name, parserSpan)) & …
Name : @Expression = n: Word => @(context.Named(n, parserSpan))

Reading and writing are on either side of the match only where constructions are deferred: a when runs while the text is read, in the order it is written, and a deferred => runs afterwards, against what the guards have by then recorded. Carried immediately, a => runs as its alternative is read, interleaved with the guards, and sees what they have written up to that point and no further (GRAM5016 warns of it); a grammar whose constructions read what its guards write names Carrier = GramCarrier.Deferred (§3.7).

One per grammar (GRAM3014), and the one at the top of a file is the one a caller supplies. A grammar included in another (§6.7) may declare its own, and that is a contract rather than a second object: the rules written there see the caller's object through the type their own grammar named, and an including grammar may strengthen the type for its own rules without changing what the included ones were compiled against.

And what is handed over has to satisfy every contract along the way (GRAM3019). One object flows down, and the parts of a composed grammar see it through as many static types as there are grammars in it — the base’s rules through what the base declared, the including grammar’s through what it declared. The type actually supplied is the one at the top of the file, and it has to be assignable to every contract underneath it. Which is ordinary subtyping: virtual dispatch works, new members are invisible to the grammar that did not declare them, and inherited semantic code keeps meaning what it meant when it was written.

Where the top of the file declares none, the effective type is the contract that satisfies all the others — the most derived of what was inherited. Where no single one does, there is no object to hand over and the grammar has to say which type it means.

What it is not is somewhere to put state that has to be undone. Nothing here unwinds: a when runs on readings the parse goes on to abandon, and what it wrote stays written. That is why what belongs here is what can be written down more than once without harm — a position, a declaration keyed by where it was read — and why a grammar that needs "this holds while that is being matched" is asking for something this is not.

Where it can be put back, a refused input is read twice (GRAM5013). A parse reads first without recording what it would say if the input were refused, and reads a refused input a second time to say it; the answer is the one a single recording reading gives. Over an object the first reading wrote into, the second has to begin where the first began, and the generator cannot know how to rewind a type it did not write. So it asks the type: an instance Mark() returning anything, and an instance Rollback taking exactly that, both callable from the generated parser. Where they are there, the parser calls Mark() before the first reading and Rollback with what it returned before the second, and says so; where they are not, every input is read once, recording, and the message says the pair is what would change that. The two are the only place anything here is undone, and only between the two readings of one refused input — what a when writes during either of them stays written as before.

7.8 What holds while something is being read

§7.7's context is state a parse accumulates: written once, still written at the end. The other kind is state that holds while one thing is being read and is gone after it — what C# means by checked(...), what a language means by "inside a loop", "inside a query".

A grammar marks the extent:

state : @Overflow

Checked   : @Expression = "checked"   & '(' & e: Expression with state @(Overflow.Checked)   & ')' => @(e)
Unchecked : @Expression = "unchecked" & '(' & e: Expression with state @(Overflow.Unchecked) & ')' => @(e)

and the construction that cares reads what it stands under:

Additive : @Expression
	= left: Multiplicative & ('+' & right: Multiplicative)*
	=> @(Arithmetic.Add(left, right, parserState))

Additive is one rule. The mark changes nothing about what is read — the same characters, the same route, the same failures in the same places. What differs is which Expression.Add* the host calls, and that is decided after the parse, where the value is built:

static Expression Add(Expression left, Expression right, ReadOnlySpan<Overflow> state)
{
	for (var i = state.Length - 1; i >= 0; i--)
	{
		if (state[i] == Overflow.Checked)   return Expression.AddChecked(left, right);
		if (state[i] == Overflow.Unchecked) break;
	}

	return Expression.Add(left, right);
}

parserState is the marks standing over that construction, outermost first, so the last is the nearest. Named like the supplied names of §8.2 and given by the same rule: a hook that does not name it is not passed it, and a grammar that places no mark hands an empty span to one that does.

One type for all of them (GRAM3016, GRAM3020). A grammar included in another may declare it too, and what that declares is a claim to be the same type rather than a contract of its own — which is where state parts company with §7.7’s context, and the reason is not the variance that makes it mechanically impossible. A context is one object flowing down; a mark is a heterogeneous stack of values placed by several authors and read as one span, and a span admits exactly one element type.

Which is why a grammar meant to be inherited declares its state as a reference type: a consumer cannot extend an enum to add a concern of their own. Which mark a hook means is the hook's to decide — it reads back for the nearest value of its own concern and walks past everything belonging to another, which is why Overflow and a Strictness lying between it and its reader do not collide. The limit this sets is real and worth stating plainly: two unrelated concerns must be different values, not different declarations. An enum per concern, all of them in the one type the grammar declares.

Nesting is what a mark is for. checked(a + unchecked(b + c) + d) is not two flags cancelling: the inner mark stands over its own protraction and the outer one is in force again after it. That falls out of where the marks are kept — in the arena, in order — and so does the other half: an abandoned reading's marks are abandoned with it. Nothing unwinds them, because being gone is the whole of what unwinding owes them, and the walk that reads them runs over what was accepted.

And where each one was placed. A mark's value is what the grammar wrote at the site, the same every time the site is reached, so it says what stands over a construction and never which: two loops side by side both stand under Loop. A construction that has to tell them apart — a break, and the loop it leaves — names parserMarks:

Loop  : @Expression = "while" & '(' & test: Expression & ')' & body: Statement
                    => @(Looping.While(test, body, parserMarks))
Break : @Expression = "break" & ';' => @(Looping.Break(parserState, parserMarks))

Control : @Expression = c: Loop with state @(Scope.Loop) => @(c)

parserMarks is a ReadOnlySpan<int> parallel to parserState, outermost first: for each mark standing over the construction, where in the input the reading under it began, in the units of parserSpan.Start. Where the reading is over tokens (§4.5), that is where the token begins in the text and not which token it is. The loop above stands under its own mark, so it finds the same position the break inside it finds, and that position is what both say. Only the beginning is given: a construction built under a mark may run before the reading under it ends, and so may not be told where it will end. It is handed like parserState, to a hook that names it and to no other; a grammar that names it nowhere is compiled exactly as if it did not exist. A when is handed neither — a guard runs while the text is read, and what stands over a reading is not settled until it is accepted. What an abandoned reading placed is abandoned with it, positions and all.

with state and §5.1's with (...) share a word and no mechanism, which is why this one is qualified. A rebinding replaces rules before anything runs and is visible to the grammar; a mark leaves the grammar alone and is visible only to hooks. A rule named state stays ordinary and stays rebindable — with (state = other) is parenthesized and this is not.


8. Failure, recovery and streaming

A grammar that reads a feed has a requirement a grammar that reads a source file does not: a million records, one of them malformed, and the answer must be a message about that record and a parse that keeps going. Everything in this section is inert in a grammar that does not ask for it.

8.1 Recognition failure and C# exceptions

The seam already exists — §7.2: when runs during the match; => runs, deferred, after it, once the match is final and from the alternative that actually matched, and carried immediately where its alternative is read.

A recognition failure is a shape the grammar does not describe. It happens during the match, and ordered choice may undo it and try something else. A recovering repetition (§8.2) treats a failed element as an error when its complete continuation cannot match and input remains. Atomic groups govern backtracking, not this error classification.

Construction runs after recognition when deferred, and during it carried immediately. Its C# must produce the rule's declared value; compile-time mistakes are C# diagnostics, and an exception thrown while constructing a value leaves the parse — carried immediately, also one thrown on a reading the parse would have given up, unless the grammar says ConstructionsMayThrow = true: then it is held, dropped with a reading given up, and thrown only where the deferred carrier would have thrown it (§7.5). Nothing turns it into a refusal. The generator does not infer another parser outcome from a C# method's signature.

There is also a failure that belongs to no single record: the envelope — a missing Trailer, input that did not end, a declared count that does not match. It is settled when the whole parse finishes, which for a streamed parse is after the records have long since been handed out.

8.2 recover — a repetition that survives a bad element

Feed : FeedItem[] = Header
                  & Row* recover eol
                  & Trailer & eof

recover marks a repetition and says three things about it:

  1. Try the complete continuation first, once the repetition minimum is met. If it succeeds, the repetition ends. Otherwise try an element. If that fails and input remains, it is a malformed element even if it consumed no characters. Neither an atomic group nor a distinguishing prefix is required.
  2. On an error the parser skips past the next match of the synchronization expression — eol here — and starts the next iteration there. The ordinal advances, so a rejected record still occupies its place in the numbering.
  3. Resume only after the synchronization match, or at EOF. The parser does not test the continuation at every character of a rejected element. An invalid final fragment is recovered through EOF; an empty EOF is never invented as an error element. A missing required element or trailer still fails the enclosing parse.

Every recovery moves forward, so a recovering repetition always ends. The search for the synchronization begins where the bad element began and moves one character at a time; a match that consumes nothing there — a lookahead, an empty alternative, a recognizer of the host that does not move — does not count, and the search goes on past it. So a bad element is at least one character long, and the parse reaches either a synchronization that consumed input or the end of the input. An element consumes input as well: the compiler checks it (§3.3), and a turn through a recognizer of the host that does not move ends the repetition rather than repeating (§7.2).

What a bad element swallows is everything up to the end of the next synchronization match, or to the end of the input. The search does not look for the next good element, only for the synchronization: with recover ';', a record that lost its ; takes the next record with it, good or not. A synchronization that every element is guaranteed to end with — the record separator, eos in a grammar over lines — loses nothing but the bad element itself; a narrower one trades lost records for records kept whole (below, and the choice ('|' | eol) further down).

A reading that ends where the rule does — one that begins at a position or reads a window (§6.3) — has nothing after the rule, so a marked repetition at the end of it finds its continuation at once: past its minimum it reads no further. To read a recovering list from a position, publish with positional parse a rule that ends with what ends the list — eof, or a terminator: RowsToEnd = Rows & eof where Rows builds no value, and where Rows : @int[] builds the list, RowsToEnd : @int[] = r: Rows & eof => @(r).

At a boundary between elements, however, the parser first tries the complete continuation after the repetition. If that continuation succeeds, the repetition is finished. If it fails anywhere along that path, its work is undone and the parser tries another element. This is what lets a broad row shape coexist with a specific trailer:

Feed = Header & Row* recover eol & Trailer & eof

Trailer & eof gets first refusal at every boundary. Usually it fails on its first character and costs almost nothing; at the actual trailer it wins even if Row could also have consumed that line. This is general sequence/repetition behavior, not a feed-specific rule.

Nothing is ever caught. An exception out of a => leaves the parse, inside a marked repetition as anywhere else (one held under ConstructionsMayThrow, §7.5, leaves it where the deferred carrier would have thrown it). Catching would mean catching Exception — there is no way to tell "this record's quantity is not a number" from NullReferenceException by type — and a parser that turns a bug in the author's own C# into "row 400 was malformed" is worse than one that stops.

It is opt-in because it cannot be the default. The rule "consumed something, then failed, therefore malformed" is wrong for ordinary grammars, and this language's own example proves it:

IPv6 = (H16 & ':'){6} & LS32 | …

An iteration matches H16 and fails on ':' having consumed four characters. That is a healthy backtrack, not a broken address. Marking the repetition is how an author says which reading applies, and it changes nothing outside the repetition it is written on — a rule still means one thing everywhere it is called.

A rule may mark as many repetitions as it has, each with its own synchronization expression, its own => and its own sequence for a rejection to arrive in:

Sheet = "H" & eol & head: Row* recover eol => @(Bad("head", parserText))
      & "B" & eol & body: Row* recover eol => @(Bad("body", parserText))
      & eof

The one exception is a parse read from a TextReader (§6.3): the driver steps over a bad element as it hands the good ones back, one repetition at a time, so a rule that marks two is told it gets no reader overload (GRAM5001) rather than silently recovering in one place only. Read whole, it recovers in both. One marked inside the other's element or synchronization is not a second: it recovers inside what the other steps over or hands back (below). The one a stream steps over has to be the repetition of a rule that it hands back; one marked in a part read whole is told the same.

A repetition inside a lookahead does not recover in place. A lookahead (§3.4) is a reading of its own that answers yes or no, and its rule plans no recovery for it, so ?=(Row* recover ';') is refused (GRAM4038) rather than read as a plain Row*. Name the recovering repetition as a rule and call that from the lookahead — ?=Rows with Rows = Row* recover ';' — and it recovers as written: a rule plans its own.

A marked repetition inside another one's element or synchronization recovers as if it were its own rule in that place, with the enclosing rule's value, trivia and on fail:

Lines : @string[] = ('[' & (Word & ';')* recover ';' & ']' & eol)* recover eol

Read over [a;b;], [c;9;d;] and [e;], a line each, the inner one steps over 9; and the second line keeps c and d: a, b, c, d, e. The outer one steps over a line only where the inner one cannot: a bad element outside the inner repetition, or an inner one whose failure reaches the line's element because its synchronization cannot be found. What the inner one collects is the enclosing rule's, where it stands — the result above is one flat sequence, and a capture inside is a capture of the enclosing rule's — and its ordinals are its own. Its synchronization is looked for as far as it takes, past the end of the outer element if need be: [9] on a line of its own is stepped over to the next ;, the one in [e;], and e goes with it. A synchronization the outer element always has, or a choice with the outer one's, keeps the inner one inside its element. A recover inside a synchronization runs at every position the synchronization search tries. A guard or a capture written directly in a synchronization is a rule of its own in the same way: recover (c: ';' & when @(c == ";")) reads as recover Sync with Sync = c: ';' & when @(c == ";"). What it captures is its own and nothing outside reads it, and a guard in it reads what it captured before it, not what the rule around it did (GRAM4045).

It is a rule of its own in every other way too. A guard inside reads what the inner part has captured in this reading of it, not what earlier lines did: (w: Word & when @(w.Length <= 1) & ';')* is handed this line's words. What a rule of its own could not be handed or hand back is refused where the inner recover is written (GRAM4045): a guard inside reading a capture made outside it and not inside it before the guard, a guard outside reading one made inside, a value built inside it, a capture of a lookahead inside it. Move the part into its own rule and pass it what it needs; a => of the enclosing rule reads what was captured inside, which is built after the parse.

A grammar cut in two (Lexical = true) recovers in the syntax that reads the tokens. A recover in a rule the lexer reads — a terminal, what one is made of, or trivia — is refused (GRAM4044): a token is the longest match of a regular language, and there is no element in it to step over.

The synchronization expression is one operand, so a choice needs brackets.

fields: Field* recover ('|' | eol)      // either separator, whichever comes first
fields: Field* recover  '|' | eol       // (fields: Field* recover '|') | eol

recover binds tighter than |, the same way & does (§3.8), so the second line is a choice between a recovering repetition and eol rather than a recovery with two ways to resume. Both are legitimate things to write, which is why this is precedence rather than an error.

A choice is worth having. Resuming at the next field separator rather than the next line keeps the rest of a record instead of throwing it away, which is what a recovery inside a record wants — eol in the same choice is then the backstop for a record so broken that no separator is left in it.

The synchronization expression is also the retention bound. An element of a marked repetition cannot reach back past the previous synchronization point, so a streamed parse holds one element and not the file. This is what §6.3 promises to prove before emitting a streaming overload; recover eol proves it by construction.

The failure factory

With a =>, a failed element becomes an element of the sequence instead of vanishing from it:

Row* recover eol => @BadRow(parserOrdinal, parserLine, parserText, parserMessage)

The factory's result must fit the sequence's element type, exactly as a successful element must — so this form needs a declared : T[] whose type can hold both. Failure then needs no channel of its own: it arrives in the stream, in its place, and the question of matching a rejection to the record it came from does not arise.

Without a => the failed element is dropped and reported out of band (§8.3), which is what a grammar that has no type to spare should do.

Positions, and the names that are filled in

The factory's arguments are matched by name, the way §7.3 matches captures, and these names are supplied rather than captured:

parserOrdinal which element of the repetition this is, counting rejected ones, from 0
parserLine, parserColumn where it starts, for a person, from 1
parserPosition absolute offset, long — for a machine
parserSpan, parserText its extent, and the input it covers
parserInput the whole of what was read, string — see below
parserMessage why it was rejected — only here, never in a capture
parserExpected what would have fit where reading it stopped — only here
parserFailureLine, parserFailureColumn where reading it stopped, for a person, from 1 — only here
parserFailurePosition the same place as an absolute offset, long — only here

A => is handed parserText, parserSpan, parserInput and, where the grammar declares a state, parserState and parserMarks (§7.8); a when only parserText and parserSpan; a recover factory every name in the table but the marks. parserInput in a recover factory is the whole input, as it is in a =>, and is refused where there is none to hand over (a streamed parse, a buffered form, a grammar that names eos). Naming one where it is not handed is GRAM4053. The supplied names are reserved in the C# of a grammar — parserText, parserPosition, parserOrdinal, parserLine, parserColumn, parserSpan, parserMessage, parserExpected, parserFailurePosition, parserFailureLine, parserFailureColumn, parserInput, parserState and parserMarks — and so are the names the generated code gives parameters of its own beside them, which are handed to nothing a grammar writes: parserSource, parserStarts and parserLengths (the tokens a split grammar builds its values from), parserReading and parserLocating (which of a rule's readings is read, and where a located value began) and parserWhole (the input a reader probes). A host method, type, local, parameter or capture is not to be spelled like one; a capture or a rule's parameter that is is refused (GRAM4012), and so is C# in the grammar that names one of the parser's own (GRAM4053). Calling one, writing it as a type or a type argument, or declaring one as a parameter, a local or a pattern variable is GRAM4053. A method group handed on (new Func<string>(parserMessage)) or a static class of that name with a member cannot be told from the value without a compilation and is left to the C# compiler, which then says so in its own words.

Where a bad element began is not where it went wrong. Flat white 3,20 is rejected as a whole line, and parserLine and parserColumn say where that line begins; what a person wants to know is that the comma is where reading stopped and a . would have fit there. parserFailureLine and parserFailureColumn are that place, and parserExpected is what would have fit, said as Match<T>.Error says it — '.', Amount or '#' — or, where nothing more particular was recorded there, the name of the rule the element should have been. parserMessage puts the two together:

Expected '.' at 3:17.

The place in it is line:column, the same whichever overload read the input; over bytes a column counts bytes, which is the character for ASCII. Where a rule says its own refusal (§4's on fail), its sentence is the message and the place follows it; where nothing at all was recorded at that place, the message says only that the input does not match the rule.

What would have fit is what was refused at that place since the turn began: the element, and the continuation tried first at the same boundary where it got as far — end of input or 'a' where the repetition ends the input. An element before that stopped at the same place, having read across its line, keeps what it wanted, and this one is not told it. Where the continuation read further than the element and failed there, the parse's furthest refusal is elsewhere, and nothing more particular is said.

A line ends where eol ends one — at \r\n, \n or a \r alone — so every line and column here, parserLine and parserColumn included, counts lines as the grammar reads them, however a stream's buffer cut a \r\n in two.

Every one of them begins with parser, and that prefix is the whole of the collision story: the supplied names become parameters of the generated factory for a => or a when, sitting in the same scope as the captures, so a capture called text would take a name already spoken for. With the prefix nothing an author would naturally write collides, and a capture that takes one of these names anyway is refused by name rather than by a C# error in a file nobody wrote (GRAM4012).

parserInput is the one name here that hands over something the parse did not itself produce, and it is what a value that means to cut its own string later is built from: parserSpan says where, parserInput says what to cut it out of. Nothing else offers that, because nothing else has to — every other name is about the one element.

Host : @Text = (Unreserved | SubDelim)+ => @(new Text(parserInput, parserSpan))

What that buys and what it costs are both the grammar author's to choose. A value built this way is two integers and a reference where an eager one is a built string, so a caller who reads one part of seven pays for one; and it keeps the whole input alive for as long as any part of the result lives, which for three names lifted out of a large document is the document. Regex makes exactly this bargain — a Match holds its input — and it is invisible until somebody parses something large. The generator does not choose a default here: : @string is the eager form, : @SourceSpan is the extent with no string at all, and this is the middle one, said in the grammar rather than settled for everybody by a switch.

A rule asking for it gets no overload taking a reader, and is told so (§6.3, GRAM5001). A stream is what having no whole input is called: a window holds the part being read, and that is not what this name means.

parserOrdinal and parserLine are not the same number and neither substitutes for the other: a header shifts the first record off line one, a record may span lines, trivia swallows blank ones, and a recovery skips an unknown number of them. The first is the key a downstream system joins on, the second is what a person opens the file at.

The same names may be captured on a successful element, which is what lets a record carry its own position without the grammar saying anything else:

public sealed record Row(string Symbol, int Qty, long Ordinal, int Line);

Counting lines costs a scan of the text an element consumed, and is done only when a name that needs it was asked for — parserMessage among them, since it says a line and a column.

Why separate arguments and not one context object

The obvious alternative is a single parserContext carrying all of it, which would end the collision question outright and leave somewhere to put feedback later. It is refused on performance, which here outranks the convenience:

  • A parameter that is not asked for costs nothing. The generator sees which names a factory's C# mentions and passes only those. parserLine is a scan of everything consumed so far; on a million-record feed, computing it for every element whether or not anybody wanted it is quadratic. A context object has to be filled before it is handed over, so either every field is eagerly computed — the quadratic case — or the object computes them lazily.
  • Lazily is what it cannot do. Computing a line number later means holding the input, and the input is a ReadOnlySpan<char>. A class cannot hold one, so a lazy context would force the whole engine onto string or Memory<char>, which is the cost of the feature paid by every parse that never uses it.
  • A container also allocates, once per rejected element and once per => that asks for anything at all, in a design whose whole shape is that nothing is allocated while matching (§4).

Feedback out of the parse already goes through OnRecovered (§8.3).

What is left is the name collision, and a prefix costs nothing to solve it.

8.3 What a parse hands back

A recovering repetition hands its result back in one of two shapes, and neither requires the author to declare more than the grammar already says:

Wanted Shape Declared
failures in the stream as the author's own types IEnumerable<FeedItem> with a factory : T[]
successful records only, failures to a log IEnumerable<Row> and a sink nothing

The sink of the second row is a method of the host. A grammar with a recover that has no => (§8.2) gets this declaration in its host class:

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

It is called for every element a recovering repetition could not read, with the rule the element should have been, the input it covered up to where the parse picked up again, where it began, which element of the repetition it was, and why it was rejected — the numbers counted as §8.2 counts them. There is one per host class, which is why it is told the rule. It is a partial void without an access modifier, so an implementation is optional: where there is none the compiler removes every call to it together with its arguments, and a parse materializes no text and counts no lines for a channel nobody listens on.

A rejection carries the text it was rejected from. A position alone is useless in a streamed parse — a TextReader cannot be wound back and the buffer has been reused — so the text of a failed element is materialized. Only of a failed one: the premise is that failures are rare, and a grammar that fails on every record has a different problem.

Exceptions appear only where §7.5 puts them: in the published methods without a Try prefix. ParseFeed(string) throws on the first failure of any kind; everything else answers.


9. A complete example

@using System;

parse Feed

Feed : @FeedItem[] = Header & Row* & Trailer & eof

Header  : @Header  = "H" & '|' & date: Date & '|' & source: Text & eol
Row     : @Row     = "D" & '|' & symbol: Text & when @IsSupportedSymbol(symbol)
                   & '|' & qty: Number & '|' & date: Date & eol
Trailer : @Trailer = "T" & '|' & count: Number & eol

Date : @DateOnly =
    y: Digits(4) & '-' & m: Digits(2) & '-' & d: Digits(2)
    => @(new DateOnly(y, m, d))

Digits(n: int) : int = ['0'..'9']{n} => @int.Parse(parserText)
Number         : int = ['0'..'9']+   => @int.Parse(parserText)
Text        : string = [^ '|' | '\r' | '\n']+
[Gram]
public partial class FeedGrammar
{
    static readonly HashSet<string> Symbols = new(StringComparer.Ordinal) { "AAPL", "MSFT", "NVDA" };

    static bool IsSupportedSymbol(string symbol)
        => Symbols.Contains(symbol);
}

public abstract record FeedItem;
public sealed record Header(DateOnly Date, string Source)          : FeedItem;
public sealed record Row(string Symbol, int Qty, DateOnly Date)    : FeedItem;
public sealed record Trailer(int Count)                            : FeedItem;
var feed  = FeedGrammar.ParseFeed(text);
var match = FeedGrammar.TryParseFeed(text);

if (!match.IsSuccess)
    Console.WriteLine($"{match.Error} at {match.Position}");

10. The grammar of .gram itself

A consistency check, and a real one: the notation above is parsed by a grammar written in itself, with no more than two tokens of lookahead.

That grammar is not printed here, because a printed one is not checked. examples/DotGram.Examples/Languages/GramExample.cs holds it, this generator compiles it, and ExampleTests.The_notation_reads_its_own_corpus runs it over every grammar in this repository — the snapshots on disk and the text of every [Gram] in the examples assembly, which a new grammar joins without anyone remembering to add it.

That grammar is a check, not the definition. What the generator reads is decided by its own parser, written by hand: src/DotGram/Grammar/Parsing/GramLexer.cs and GramParser.cs. Where the two disagree, the hand-written parser is the authority and the example grammar is the one to correct. The language guide's quick reference (docs/guide/language/17-reference.md) is held by a test to every word and sign that parser reads.

Two things in the running grammar are worth knowing about, since neither is visible in a production list:

  • The lexical rules sit in a namespace with trivia = none (§4.5), so an identifier is letters with nothing allowed between them while everything outside is spaced and commented freely.

  • @(...) is not recognized by the grammar at all. Finding the parenthesis that closes it means knowing C#'s own strings and comments, which no grammar can do; the rule is a bare external recognizer (§7.1) that reads the input itself. What follows is about that seam.

@( is the only place in the whole language holding raw C# text, and the only one needing a foreign lexer. Everything else with @ (@Name, @Name.Name, @Name<T>, @Name(args)) is parsed by .gram's own parser through the Reference and Call productions; the arguments there are .gram values rather than C# text, and the names go to Roslyn later, during symbol resolution.

Balanced is the text up to the matching close parenthesis. It is found with C#'s tokenizer (SyntaxFactory.ParseTokens) and a depth counter: string, verbatim, interpolated and raw literals, and comments too, arrive as whole tokens, so a ) inside one cannot change the depth.

C#'s parser will not do, tempting though it looks: SyntaxFactory.ParseExpression is greedy and knows nothing of .gram's terminators, while &, |, *, +, ?, [ and .. are all valid C# operators. On when @(qty > 0) & b: Y it would consume (qty > 0) & b and stop only at the colon.

Consequences. .gram's lexer is not single-mode: after @( it switches to C# tokenization and returns at the matching ), as Razor does. This does not affect the two-token bound above. And Razor's limits on implicit expressions — no spaces, no generics — do not carry over: there they exist because the end has to be guessed inside a stream of markup, whereas here a grammar token marks the end. So @ int . Parse ( text ) and @List<int> are both fine — < and > are free, since the grammar has no comparison operators.


11. Deliberately out of scope

None of what follows changes the notation described above.

  • Back-references beyond one rule's own text. A binding is read by a reference in the same alternative of the same rule, over characters (§3.5.1). A reference in another rule would be a run-time text handed to a rule, and a rule is specialized at build time (§4.2). The same goes for a reference that matches without regard to case, for one over kinds (a guard does that: when @(close == open)), and for arithmetic in a count ({#q-1}; the ?! idioms of §3.5.1 cover what C# needs). Length-prefixed data — 5:hello, where the count is a number that was read — is a different decision again.

  • Repairing a document. When a whole input is one construct — a source file in an editor — there is no notation for it: recovery here is scoped to one repetition (§8.2), for a feed. A general repair pass over a whole broken document — finding the edit an author most likely meant — is a different kind of engine.

    The two do not overlap in what they'd answer even if both existed: repair answers "what did the author most likely mean" for one document; §8.2 answers "this record is bad, say why and go on" for a hundred million of them, holding nothing but the current record.

  • Alternatives are never reordered. | is ordered choice and stays so, including where one literal alternative is a prefix of another. Over characters a prefix does not shadow anything, because backtracking is what ordered choice means there; over kinds the first alternative that matches is the one (§4), and an alternative written first does shadow what follows it — as it does in a parser written by hand.

    The rule is the first alternative that succeeds, and what counts as succeeding is the directive's business rather than the choice's. parse needs the whole input, so a shorter alternative that leaves a character over is not a success and the choice is tried again:

    A = "http" | "https"
    
    parse A as WholeA      // WholeA("https") is "https"
    find  A as EveryA      // EveryA("https") yields "http"
    

    find asks for an occurrence, and "http" at that position is one — so it is the answer, and reading goes on from the s. Both follow the same rule; they differ in what they are asking for. Where the longer reading is the one wanted, write it first: "https" | "http" answers https to both.

    Reordering by length looks like the obvious fix to a problem that is not there, and would not be one anyway: it produces a different grammar rather than a corrected one. In

    Rule = part: ("x" | "xy") & 'y'?
    

    input xy gives part = "x" as written and part = "xy" reordered — both parses succeed, and even full backtracking would not make them agree. Order stops being incidental the moment two alternatives can match different lengths, and which of "first that matches" and "longest that matches" is wanted is the author's call — .NET regular expressions take the first, POSIX the longest.

    Normalization does merge alternatives automatically where order provably cannot matter: single-element sets, where the match is always exactly one item, so 'a' | 'b' becomes ['a'..'b'].

  • trivia — the mechanism is in §4.5. It needs no notation of its own: an ordinary rule and ordinary shadowing.

  • Atomic groups are explicit. { X } has the same matches and value as X, but when it succeeds the parser discards alternatives created while recognizing X. Failure before the closing brace remains an ordinary failure. Rule boundaries never imply this behavior; an author chooses it only where the grammar has a real commit point.

  • Keyword boundaries — §4.6, the same mechanism again.

  • Incomplete does not exist. An outcome is Success, NoMatch or Starved. A source that cannot block — an async socket, where control has to go back to the caller mid-parse — is what would need it; a file, however large, is read by a reader that simply fetches the next chunk. Adding it means a rule for every construct (repetition, both lookaheads, recovery, find) plus a resumption model, and that is a lot to carry before anything asks for it.

  • A sliding window over input that is neither memory-sized nor line-oriented. Source files fit in memory; feeds are line-oriented; what is left is huge binary input, which is out of scope. If it ever arrives, it slots in beside the two modes in §6.3 without disturbing them.

  • A precedence table separate from the rules, the way yacc declares one. What it would buy is in §4.3.1 instead, written on the alternatives themselves — an operator and its strength in one place rather than two that must be kept in step.

  • Telling an error from a non-match. A guard is recognition and stays a non-match: a failing when @IsSupportedSymbol(symbol) is an ordinary non-match, not an error carrying a message like "unsupported symbol XYZ". Most of what an author wants to say there is not about recognition at all — it is about a value, after a match, which is what the C# of a construction is for (§8.1), or what a repetition's recover is for (§8.2). Neither changes what a guard means.