Semantics¶
This page defines what a grammar means: for a grammar, an input and a start rule, which tree a parse produces or where it fails. It is normative. The grammar language page defines the syntax this page refers to.
The definition has two steps. First, every grammar is translated into a small core language. Then a single matching relation gives every core expression its meaning. Engines and optimizations may work in any way, as long as they produce the results defined here.
Input¶
The input is a UTF-8 string. Positions are byte offsets from 0 to the length of the input, and every position used below lies on a code point boundary.
A character is one code point.
A line break is
\r\n,\nor\r. A line starts at position 0 and after every line break.The column of a position is computed over the characters between the start of its line and the position: each character advances the column by 1, a tab advances it to the next multiple of the tab width (
%tabs, default 8), and a form feed sets it back to 0. The first column is 0.
The core language¶
Core expression |
Meaning in short |
|---|---|
|
match the empty string |
|
match the string |
|
match one character in the set |
|
match one character |
|
match rule |
|
match each in turn |
|
ordered choice |
|
between |
|
lookahead |
|
commit the innermost choice point |
|
match the skip expression as often as it matches non-empty text |
|
match |
|
wrap what |
|
as |
|
label what |
|
fail when a word character follows |
|
match |
|
flags |
|
columns, |
|
the end of the input, after the skip if |
|
captures |
|
match |
|
fail, and where a failed parse is explained, give the error |
Modules¶
A grammar with %extends "m" is joined with the grammar m before anything else, into one grammar that the rest of this page reads:
mis joined with what it extends first.Each rule of the grammar whose name
mdefines takes the place ofm’s rule, and every reference means it. A...that stands as a whole alternative of it is replaced by the alternatives ofm’s rule, in their order.The other rules are added.
The skip expression is the ordered choice of
m’s%ignoreexpressions and then the grammar’s. The flags and soft keywords are those of both, and%wordand%tabsthe grammar’s where it gives them, otherwisem’s.A
%recoverof the grammar takes the place ofm’s for the same label, andm’s others are added.
A grammar with %import m (a, b) then adds rules of m, joined with what it extends and imports first:
aandbunder their names, and every rule they need, directly or through others, underm.rfor its namer, a name no grammar text can write. The levels of a precedence block come underm.l, and the aliasesxof a rule under a private name underm.x. References in the rules added follow the new names. A reference to a name thatmlacks is an error.A name keeps the kind of the name it replaces:
m.Ris a terminal asRis, andm._rmakes no node as_rmakes none.The flags of
mthat the rules added set or test join the grammar’s. Its other directives do not count, its recoveries among them: labels keep their names, so the labels of the rules added recover where the grammar gives them a%recoverof its own.All imports of one grammar
madd one set of rules, and one without names takes every rule ofmwhose name has no dot. A rule under a private name that the grammar has already, through what it extends or another import, is the same rule and is added once.
Translation into the core¶
The translation runs in this order.
Parameters. Every use
r<a1, ..., an>of a rule with parameters becomes a call of a rule instance whose body is the template with each parameter replaced by its argument. Uses with structurally equal arguments share one instance. All instances carry the name of the template.Precedence blocks. A rule
r: %precedence { L1 ... Ln }becomes one rule per level. The rule of levelLkischoice(A1, ..., Aj, call(Lk+1)), with the alternativesAof that level and the fall-through to the next level, which the last level does not have. A reference to a level name calls that level’s rule, from inside the block or from any other rule, since level names belong to the whole grammar. The ruleritself becomescall(L1).Sugar.
e?isrep(e, 0, 1),e*isrep(e, 0, ∞),e+isrep(e, 1, ∞).e ** sisrep(seq(e, rep(seq(s, e), 0, ∞)), 0, 1)ande ++ sisseq(e, rep(seq(s, e), 0, ∞)).e ^ lislabel(e, l, s), where a message forms a label of its own.()isε. A sequencee1 ... ek %error(m)iserror_alternative(seq(e1, ..., ek), m, s), and%error(m)alone iserror_alternative(ε, m, s). Nothing can follow%error(m)in a sequence (E302).Modes. Every expression is translated in the mode of the rule whose body it ends up in: syntactic for syntactic rules, lexical for lexical rules, plain for terminals and the skip expression.
In syntactic mode, a literal, class, property,
.orref(x)becomesseq(skip, token(k, h, a))with the atoma, a reference to a terminalTbecomesseq(skip, token(T, h, call(T))), and a reference to a lexical rule becomesseq(skip, call(R)).In lexical mode the same holds without the
skip.In plain mode atoms stay atoms and a reference to a terminal is
call(T). References to syntactic or lexical rules are errors.The kind
kof an anonymous token is the atom as written, normalized:"+",[0-9],.. A token is hidden (h) if it comes from an atom or a hidden terminal and is not captured by a field. A field captures the atoms and terminal references that are its whole match: reached from the field through choices, repetitions, the items of separated repetitions, labels, flags,%indentand%def, not through a sequence of several parts, a separator or a lookahead.In a grammar with
%word, a literal token whose last character is a word character becomestoken(k, h, seq(a, word_end)).!.becomesend(s), the end of the input.%indent,%same,%def,e ^ l,%errorand!.carrys = truein syntactic mode ands = falseotherwise.
Rules. The body of a terminal marked
@reservedbecomesunreserved(body). In a syntactic or lexical ruler, each top-level alternativeAbecomesnode(alias, A)when it has an alias, and otherwisenode(r, A),transparent(r, A)for a transparent rule, orAalone for an inlined rule or a precedence level.Fields.
label=ebecomesfield(f, e).Recoveries.
%recover l: rgives the named labellthe recoveryr, translated in syntactic mode. A label has at most one.
Matching¶
The meaning of a core expression e is a relation between e, a position i, a context κ, and a result.
The context
κhas four parts: the set of flags that are on, the reference column, the captures, which map names to texts, and the floor, a position or none. Two contexts are equal when all four parts are, however the captures came about.Matching knows besides the mode of the parse, normal or recovering, and whether it runs sheltered, inside a lookahead, a token or the skip expression. Neither is part of the context, so a rule that calls itself through a lookahead finds the entry of the table of left recursion made around it, in either mode.
A result is one of:
success
(j, items, Γ, c): the expression matched the input fromitoj, produced the listitems, leaves the capturesΓfor what follows, andcsays whether it passed a cut that no choice point has consumed yet.failure
(c): the expression does not match, andcsays whether a cut was passed before the failure.error
(l, p, D): the labeled errorloccurred at positionp, after the error itemsDthat the matches it ended had produced before it. An error is never caught by a choice and ends the whole parse.
Unless a rule below says otherwise, an error of a part is the error of the whole, with the error items among what the parts before it produced, at any depth, in front of its D, and the captures of a success are those of the context.
Expression |
Result |
|---|---|
|
success |
|
success at |
|
success after the character at |
|
success after the character at |
|
match |
|
match the alternatives at |
|
match |
|
match |
|
match |
|
success |
|
the result of |
|
failure |
The captures do not change inside a not or and: what e captures there is dropped.
Rules and left recursion¶
A call call(R) at position i in context κ starts a rule activation. The activation sees the captures of κ, and when it ends the caller continues with its own captures. A cut passed inside the activation does not reach the caller.
Rules may be left recursive, directly or through other rules. A table L holds, for some triples of rule, position and context, either failure or a success. The table belongs to the parse and starts empty.
If
Lhas an entry for(R, i, κ), the call returns that entry. This is a left-recursive use.Otherwise
Lgets the entry failure for(R, i, κ), and the body ofRis matched ati.If it fails, the entry is removed and the call fails.
If it succeeds ending at
j, the entry becomes that success and the body is matched again. As long as each new match succeeds and ends further than the entry, the entry becomes the new match and the body is matched again. When a match fails, or does not end further than the entry, the entry is removed and the call returns the entry.An error during these matches removes the entry and is the result of the call.
A rule that is not left recursive gives the same result as matching its body once. A rule that is left and right recursive at once groups to the right.
Skipping and tokens¶
skipmatches the skip expression ati, in plain mode, sheltered, with the current context, then again where it ended, as long as it succeeds and consumes input. Its result is success at the last end, without items, and with the captures of the context: what the skip expression captures holds for that one match. A grammar without%ignorehas an empty skip expression, soskipmatches the empty string.token(k, h, e)matchese, sheltered, drops whateproduces, and on success produces one token of kindkfromito the end of the match, hidden ifh.word_endsucceeds without consuming input unless a word character follows ati. The word characters are those of%word, and[A-Za-z0-9_]for reserved words in a grammar without%word.unreserved(e)matcheseand fails when the matched text is a reserved word. The reserved words are the texts of literals that occur as tokens of syntactic or lexical rules and consist only of word characters, minus the soft keywords. A case-insensitive literal reserves every ASCII spelling of its text.
Where what an expression produces is dropped, in a token, the skip expression and a lookahead, it runs sheltered and nothing recovers, so no recovery goes unreported.
Context¶
Expression |
Result |
|---|---|
|
the result of |
|
success |
|
let |
|
with |
|
with |
|
with |
|
success after the text |
Where indent, same, end and def take p from where skip ends, before anything else, and label after e failed, an error that skip ends in is their result.
Flags and the reference column hold for the extent of their expression, including the rules it calls. Captures hold until the rule activation that made them ends.
Items and the tree¶
Matching produces a list of items. An item is a token, with a kind, a position range and a hidden mark, or a node, with a kind and a list of items as children. Both may carry a field.
node(k, e)turns the items of a success ofeinto one node of kindk.transparent(k, e)does the same unless the items contain exactly one item that is not a hidden token. In that case the items are the result as they are.field(f, e)gives fieldfto each item of a success ofethat has no field yet and is not a hidden token. Hidden tokens never carry a field.The span of a node runs from the start of its first token to the end of its last token, at any depth, hidden tokens included. A node without tokens has the empty span at the position where its
nodeortransparentexpression was matched.The error item of a label
lfromptoq, with the itemsXof its recovery, is a node of kind<error>with the childrenXand the span fromptoq, or, whereqisp, a token of kind<missing>with the empty span atp, which is never hidden. It recordsl. Where the failed expression isfield(f, e), it carries the fieldf. Within the span of its parent it counts as a token.
Parsing an input¶
A parse runs in normal mode or in recovering mode. To parse an input with a start rule S, the expression for a reference to S in syntactic mode is matched at position 0 in the initial context: no flags, reference column 0, no captures and no floor. On success at j, skip is matched at j, and the parse succeeds if that reaches the end of the input. An error of that skip comes after the items of the success, whose error items come first in its D. The tree consists of the items of the success. Its recoveries are its error items in the order of the text, each with its label and span. A parse in normal mode has none.
A parse that does not succeed fails at the farthest failure position, with an expected set:
A
tokenexpression that fails at positionprecordspwith the floor of its context, outside ofnot,andand the skip expression. Of the positions recorded with no floor, outside every recovery, the largest is the farthest failure position. The expected set holds the kinds of the tokens that failed there, by display name where the grammar gives one.An
indentorsamewhose column check fails records the position it checked in the same way, expecting indentation, and anendthat fails records it expecting the end of the input.A labeled error at position
phas the expected set ofpunder the floor its label failed with: what failed there in the whole parse with that floor. So what a recovery tries, with a floor of its own, explains no error outside it. A named label shows the set after its name.An error item of a label
latpis explained as the errorlwould have ended the parse with where it first failed atpunder the floor it failed with: at the farthest position at or afterpwhere a failure had been recorded under that floor by then, with what had failed there by then, and atpwith an empty set where none had. So the first error of a parse in recovering mode is the error a parse in normal mode fails with. A later failure oflatpunder that floor changes nothing, since what fails inside a remembered match is recorded only once.If the input does not end where the parse ended, that position counts as a failure that expects the end of the input. The recoveries of the failed parse are the error items of the success.
A parse that ends in an error
(l, p, D)fails with that error instead, and its recoveries are the error items inD. Where the label failed outside every recovery and a failure outside every recovery was recorded beyondp, the parse got further than the label, and it fails at the farthest failure position with its expected set instead, as a parse that does not match, keeping those recoveries.
A parse that fails, other than at a limit, is explained where the grammar has an error alternative:
Its attempts under the floor of its error, which is that of the label and none for a parse that does not match, are tested in the order of their positions. At one position they go in the order their
%errorstands in the text of the grammar, where a module’s text comes after the text that uses it, and the instances of one rule come in the order the translation makes them.An attempt is tested by matching
eatiinκ, sheltered, as a parse of its own.The first alternative whose
esucceeds gives the errormin place of the error, with no expected set, and the parse keeps its recoveries.The error ends at
j, the farthest end whereesucceeds over the contexts it was tried in ati.The error starts at
p. Withs,pis the farthest end ofskipmatched atithe same way, over the contexts whereeends atj, andiwhereskipsucceeds in none of them. Withouts,pisi, as for a label. Wherepcomes afterj, the error ends atp.
Since an attempt is tested on its own, what the parse remembered and the order it tried things in cannot change which one explains it. Explaining is part of the parse, so a limit that the tests reach ends the parse at that limit.
An input that a parse in normal mode accepts fails no label outside a token, the skip expression and a lookahead, so a parse in recovering mode gives it the same tree and no recoveries.
Limits¶
An implementation stops a parse that exceeds a limit on time, recursion depth, memory or input size, and reports which limit it hit. A limit never changes the result of a parse that stays within it.
Recovery needs no limit of its own. A recovery that matches nothing is an empty match, which ends a repetition and takes part in left recursion like any other, and a recovery inside another starts past where the other started.