Incomputer science, aparsing expression grammar (PEG) is a type ofanalyticformal grammar, i.e. it describes aformal language in terms of a set of rules for recognizingstrings in the language. The formalism was introduced by Bryan Ford in 2004[1] and is closely related to the family oftop-down parsing languages introduced in the early 1970s.Syntactically, PEGs also look similar tocontext-free grammars (CFGs), but they have a different interpretation: the choice operator selects the first match in PEG, while it is ambiguous in CFG. This is closer to how string recognition tends to be done in practice, e.g. by arecursive descent parser.
Unlike CFGs, PEGs cannot beambiguous; a string has exactly one validparse tree or none. It is conjectured that there exist context-free languages that cannot be recognized by a PEG, but this is not yet proven.[1] PEGs are well-suited to parsing computer languages (and artificial human languages such asLojban) where multiple interpretation alternatives can be disambiguated locally, but are less likely to be useful for parsingnatural languages where disambiguation may have to be global.[2]
This section includes alist of references,related reading, orexternal links,but its sources remain unclear because it lacksinline citations. Please helpimprove this section byintroducing more precise citations.(December 2022) (Learn how and when to remove this message) |
Aparsing expression is a kind of pattern that each string may eithermatch ornot match. In case of a match, there is a unique prefix of the string (which may be the whole string, the empty string, or something in between) which has beenconsumed by the parsing expression; this prefix is what one would usually think of as having matched the expression. However, whether a string matches a parsing expressionmay (because of look-ahead predicates) depend on parts of it which come after the consumed part. Aparsing expression language is a set of all strings that match some specific parsing expression.[1]: Sec.3.4
Aparsing expression grammar is a collection of named parsing expressions, which may reference each other. The effect of one such reference in a parsing expression is as if the whole referenced parsing expression was given in place of the reference. A parsing expression grammar also has a designatedstarting expression; a string matches the grammar if it matches its starting expression.[citation needed]
An element of a string matched is called aterminal symbol, orterminal for short. Likewise the names assigned to parsing expressions are callednonterminal symbols, ornonterminals for short. These terms would be descriptive forgenerative grammars, but in the case of parsing expression grammars they are merely terminology, kept mostly because of being near ubiquitous in discussions ofparsing algorithms.[citation needed]
Bothabstract andconcrete syntaxes of parsing expressions are seen in the literature, and in this article. The abstract syntax is essentially amathematical formula and primarily used in theoretical contexts, whereas concrete syntax parsing expressions could be used directly to control aparser. The primary concrete syntax is that defined by Ford,[1]: Fig.1 although many tools have their own dialect of this. Other tools[3] can be closer to using a programming-language native encoding of abstract syntax parsing expressions as their concrete syntax.
The two main kinds of parsing expressions not containing another parsing expression are individual terminal symbols and nonterminal symbols. In concrete syntax, terminals are placed inside quotes (single or double), whereas identifiers not in quotes denote nonterminals:
"terminal"Nonterminal'another terminal'
In the abstract syntax there is no formalised distinction, instead each symbol is supposedly defined as either terminal or nonterminal, but a common convention is to use upper case for nonterminals and lower case for terminals.
The concrete syntax also has a number of forms for classes of terminals:
. (period) is a parsing expression matching any single terminal.[abcde] form a parsing expression matching one of the numerated characters. As inregular expressions, these classes may also include ranges[0-9A-Za-z] written as a hyphen with the range endpoints before and after it. (Unlike the case in regular expressions, bracket character classes do not have^ for negation; that end can instead be had via not-predicates.)In abstract syntax, such forms are usually formalised as nonterminals whose exact definition is elided for brevity; in Unicode, there are tens of thousands of characters that are letters. Conversely, theoretical discussions sometimes introduce atomic abstract syntax for concepts that can alternatively be expressed using composite parsing expressions. Examples of this include:
!.), andIn the concrete syntax, quoted and bracketed terminals havebackslash escapes, so that "line feed orcarriage return" may be written[\n\r]. The abstract syntax counterpart of a quoted terminal of length greater than one would be the sequence of those terminals;"bar" is the same as"b" "a" "r". The primary concrete syntax assigns no distinct meaning to terminals depending on whether they use single or double quotes, but some dialects treat one as case-sensitive and the other as case-insensitive.
Given any existing parsing expressionse,e1, ande2, a new parsing expression can be constructed using the following operators:
Operator priorities are as follows, based on Table 1 in:[1]
| Operator | Priority |
|---|---|
| (e) | 5 |
| e*,e+,e? | 4 |
| &e, !e | 3 |
| e1e2 | 2 |
| e1 /e2 | 1 |
In the concrete syntax, a parsing expression grammar is simply a sequence of nonterminal definitions, each of which has the form
IdentifierLEFTARROWExpression
TheIdentifier is the nonterminal being defined, and theExpression is the parsing expression it is defined as referencing. TheLEFTARROW varies a bit between dialects, but is generally some left-pointing arrow or assignment symbol, such as<-,←,:=, or=. One way to understand it is precisely as making an assignment or definition of the nonterminal. Another way to understand it is as a contrast to the right-pointing arrow → used in the rules of acontext-free grammar; with parsing expressions the flow of information goes from expression to nonterminal, not nonterminal to expression.
As amathematical object, a parsing expression grammar is a tuple, where is the set of nonterminal symbols, is the set of terminal symbols, is afunction from to the set of parsing expressions on, and is the starting parsing expression. Some concrete syntax dialects give the starting expression explicitly,[4] but the primary concrete syntax instead has the implicit rule that the first nonterminal defined is the starting expression.
It is worth noticing that the primary dialect of concrete syntax parsing expression grammars does not have an explicit definition terminator or separator between definitions, although it is customary to begin a new definition on a new line; theLEFTARROW of the next definition is sufficient for finding the boundary, if one adds the constraint that a nonterminal in anExpression must not be followed by aLEFTARROW. However, some dialects may allow an explicit terminator, or outright require[4] it.
This is a PEG that recognizes mathematical formulas that apply the basic five operations to non-negative integers.
Expr←SumSum←Product(('+'/'-')Product)*Product←Power(('*'/'/')Power)*Power←Value('^'Power)?Value←[0-9]+/'('Expr')'
In the above example, the terminal symbols are characters of text, represented by characters in single quotes, such as'(' and')'. The range[0-9] is a shortcut for the ten characters from'0' to'9'. (This range syntax is the same as the syntax used byregular expressions.) The nonterminal symbols are the ones that expand to other rules:Value,Power,Product,Sum, andExpr. Note that rulesSum andProduct don't lead to desired left-associativity of these operations (they don't deal with associativity at all, and it has to be handled in post-processing step after parsing), and thePower rule (by referring to itself on the right) results in desired right-associativity of exponent. Also note that a rule likeSum←Sum(('+'/'-')Product)? (with intention to achieve left-associativity) would cause infinite recursion, so it cannot be used in practice even though it can be expressed in the grammar.
The fundamental difference betweencontext-free grammars and parsing expression grammars is that the PEG's choice operator isordered. If the first alternative succeeds, the second alternative is ignored. Thus ordered choice is notcommutative, unlike unordered choice as in context-free grammars. Ordered choice is analogous tosoft cut operators available in somelogic programming languages.
The consequence is that if a CFG is transliterated directly to a PEG, any ambiguity in the former is resolved by deterministically picking one parse tree from the possible parses. By carefully choosing the order in which the grammar alternatives are specified, a programmer has a great deal of control over which parse tree is selected.
Parsing expression grammars also add the and- and not-syntactic predicates. Because they can use an arbitrarily complex sub-expression to "look ahead" into the input string without actually consuming it, they provide a powerful syntacticlookahead and disambiguation facility, in particular when reordering the alternatives cannot specify the exact parse tree desired.
Each nonterminal in a parsing expression grammar essentially represents a parsingfunction in arecursive descent parser, and the corresponding parsing expression represents the "code" comprising the function. Each parsing function conceptually takes an input string as its argument, and yields one of the following results:
An atomic parsing expression consisting of a singleterminal (i.e. literal) succeeds if the first character of the input string matches that terminal, and in that case consumes the input character; otherwise the expression yields a failure result. An atomic parsing expression consisting of theempty string always trivially succeeds without consuming any input.
An atomic parsing expression consisting of anonterminalA represents arecursive call to the nonterminal-functionA. A nonterminal may succeed without actually consuming any input, and this is considered an outcome distinct from failure.
Thesequence operatore1e2 first invokese1, and ife1 succeeds, subsequently invokese2 on the remainder of the input string left unconsumed bye1, and returns the result. If eithere1 ore2 fails, then the sequence expressione1e2 fails (consuming no input).
Thechoice operatore1 /e2 first invokese1, and ife1 succeeds, returns its result immediately. Otherwise, ife1 fails, then the choice operatorbacktracks to the original input position at which it invokede1, but then callse2 instead, returninge2's result.
Thezero-or-more,one-or-more, andoptional operators consume zero or more, one or more, or zero or one consecutive repetitions of their sub-expressione, respectively. Unlike incontext-free grammars andregular expressions, however, these operatorsalways behavegreedily, consuming as much input as possible and never backtracking. (Regular expression matchers may start by matching greedily, but will then backtrack and try shorter matches if they fail to match.) For example, the expression a* will always consume as many a's as are consecutively available in the input string, and the expression (a* a) will always fail because the first part (a*) will never leave any a's for the second part to match.
Theand-predicate expression &e invokes the sub-expressione, and then succeeds ife succeeds and fails ife fails, but in either casenever consumes any input.
Thenot-predicate expression !e succeeds ife fails and fails ife succeeds, again consuming no input in either case.
The following recursive rule matches standard C-style if/then/else statements in such a way that the optional "else" clause always binds to the innermost "if", because of the implicit prioritization of the '/' operator. (In acontext-free grammar, this construct yields the classicdangling else ambiguity.)
S←'if'C'then'S'else'S/'if'C'then'S
The following recursive rule matches Pascal-style nested comment syntax,(* which can (* nest *) like this *). Recall that. matches any single character.
C←BeginN*EndBegin←'(*'End←'*)'N←C/(!Begin!End.)
The parsing expressionfoo&(bar) matches and consumes the text "foo" but only if it is followed by the text "bar". The parsing expressionfoo!(bar) matches the text "foo" but only if it isnot followed by the text "bar". The expression!(a+b)a matches a single "a" but only if it is not part of an arbitrarily long sequence of a's followed by a b.
The parsing expression('a'/'b')* matches and consumes an arbitrary-length sequence of's and's. Theproduction ruleS←('a'S'b')? matches the simplecontext-free language.The following parsing expression grammar describes the classic non-context-free language:[1]
S←&(A!'b')'a'*B!.A←('a'A'b')?B←('b'B'c')?
Any parsing expression grammar can be converted directly into arecursive descent parser.[5] Due to the unlimitedlookahead capability that the grammar formalism provides, however, the resulting parser could exhibitexponential time performance in the worst case.
It is possible to obtain better performance for any parsing expression grammar by converting its recursive descent parser into apackrat parser, which always runs inlinear time, at the cost of substantially greater storage space requirements. A packrat parser[5]is a form ofparser similar to a recursive descent parser in construction, except that during the parsing process itmemoizes the intermediate results of all invocations of themutually recursive parsing functions, ensuring that each parsing function is only invoked at most once at a given input position. Because of this memoization, a packrat parser has the ability to parse manycontext-free grammars andany parsing expression grammar (including some that do not represent context-free languages) in linear time. Examples of memoized recursive descent parsers are known from at least as early as 1993.[6]This analysis of the performance of a packrat parser assumes that enough memory is available to hold all of the memoized results; in practice, if there is not enough memory, some parsing functions might have to be invoked more than once at the same input position, and consequently the parser could take more than linear time.
It is also possible to buildLL parsers andLR parsers from parsing expression grammars,[citation needed] with better worst-case performance than a recursive descent parser without memoization, but the unlimited lookahead capability of the grammar formalism is then lost. Therefore, not all languages that can be expressed using parsing expression grammars can be parsed by LL or LR parsers.
A pika parser[7] usesdynamic programming to apply PEG rules bottom-up and right to left, which is the inverse of the normal recursive descent order of top-down, left to right. Parsing in reverse order solves the left recursion problem, allowing left-recursive rules to be used directly in the grammar without being rewritten into non-left-recursive form, and also confers optimal error recovery capabilities upon the parser, which historically proved difficult to achieve for recursive descent parsers.
Many parsing algorithms require a preprocessing step where the grammar is first compiled into an opaque executable form, often some sort of automaton. Parsing expressions can be executed directly (even if it is typically still advisable to transform the human-readable PEGs shown in this article into a more native format, such asS-expressions, before evaluating them).
Compared to pureregular expressions (i.e., describing a language recognisable using afinite automaton), PEGs are vastly more powerful. In particular they can handle unbounded recursion, and so match parentheses down to an arbitrary nesting depth; regular expressions can at best keep track of nesting down to some fixed depth, because a finite automaton (having a finite set of internal states) can only distinguish finitely many different nesting depths. In more theoretical terms, (the language of all strings of zero or more's, followed by anequal number ofs) is not aregular language, but it is easily seen to be a parsing expression language, matched by the grammar
start←AB!.AB←('a'AB'b')?
HereAB !. is the starting expression. The!. part enforces that the input ends after theAB, by saying “there is no next character”; unlike regular expressions, which have magic constraints$ or\Z for this, parsing expressions can express the end of input using only the basic primitives.
The*,+, and? of parsing expressions are similar to those in regular expressions, but a difference is that these operate strictly in a greedy mode. This is ultimately due to/ being an ordered choice. A consequence is that something can match as a regular expression which does not match as parsing expression:
[ab]?[bc][cd]is both a valid regular expression and a valid parsing expression. As regular expression, it matchesbc, but as parsing expression it does not match, because the[ab]? will match theb, then[bc] will match thec, leaving nothing for the[cd], so at that point matching the sequence fails. "Trying again" with having[ab]? match the empty string is explicitly against the semantics of parsing expressions; this is not anedge case of a particular matching algorithm, instead it is the sought behaviour.
Even regular expressions that depend on nondeterminismcan be compiled into a parsing expression grammar, by having a separate nonterminal for every state of the correspondingnondeterministic finite automaton (NFA for short) and encoding its transition function into the definitions of these nonterminals —
A←'x'B/'x'C/'y'D
is effectively saying "from state A transition to state B or C if the next character is x, or to state D if the next character is y". It would not make use of the parsing expression variants of the repetition operations.
For accepting states of the NFA, the definition of the nonterminal should be surrounded by?. Concerning the entry states of the NFA, they should all be listed, separated by/, in the definition of the starting non-terminal.
Note that while it's possible to transform a regular expression into adeterministic finite automaton (DFA for short) instead of an NFA, this should beavoided because the DFA equivalent of a regular expression can be exponentially larger. In fact, there is a sequence of regular expressions for which all of the DFA equivalents are exponentially larger.
PEGs can comfortably be given in terms of characters, whereascontext-free grammars (CFGs) are usually given in terms of tokens, thus requiring an extra step of tokenisation in front of parsing proper.[8] An advantage of not having a separate tokeniser is that different parts of the language (for example embeddedmini-languages) can easily have different tokenisation rules.
In the strict formal sense, PEGs are likely incomparable to CFGs, but practically there are many things that PEGs can do which pure CFGs cannot, whereas it is difficult to come up with examples of the contrary. In particular PEGs can be crafted to natively resolve ambiguities, such as the "dangling else" problem in C, C++, and Java, whereas CFG-based parsing often needs a rule outside of the grammar to resolve them. Moreover any PEG can be parsed in linear time by using a packrat parser, as described above, whereas parsing according to a general CFG is asymptotically equivalent[9] toboolean matrix multiplication (thus likely between quadratic and cubic time).
One classical example of a formal language which is provably not context-free is the language: an arbitrary number of's are followed by an equal number of's, which in turn are followed by an equal number of's. This, too, is a parsing expression language[1], matched by the grammar:
S←&(A!'b')'a'*B!.A←('a'A'b')?B←('b'B'c')?
ForA to match, the first stretch of's must be followed by exactly the same number of's and no more, and in additionB has to match where the's switch to's, which means those's are followed by an equal number of's.
PEG parsing is typically carried out viapackrat parsing, which usesmemoization[10][11] to eliminate redundant parsing steps. Packrat parsing requires internal storage proportional to the total input size, rather than to the depth of the parse tree as with LR parsers. Whether this is a significant difference depends on circumstances; if parsing is a service provided as afunction then the parser will have stored the full parse tree up until returning it, and already that parse tree will typically be of size proportional to the total input size. If parsing is instead provided as agenerator then one might get away with only keeping parts of the parse tree in memory, but the feasibility of this depends on the grammar. A parsing expression grammar can be designed so that only after consuming the full input will the parser discover that it needs to backtrack to the beginning,[12] which again could require storage proportional to total input size.
For recursive grammars and some inputs, the depth of the parse tree can be proportional to the input size,[13] so both an LR parser and a packrat parser will appear to have the same worst-case asymptotic performance. However in many domains, for example hand-written source code, the expression nesting depth has an effectively constant bound quite independent of the length of the program, because expressions nested beyond a certain depth tend to getrefactored. When it is not necessary to keep the full parse tree, a more accurate analysis would take the depth of the parse tree into account separately from the input size.[14]
In order to attain linear overall complexity, the storage used for memoization must furthermore provideamortized constant time access to individual data items memoized. In practice that is no problem — for example a dynamically sizedhash table attains this – but that makes use ofpointer arithmetic, so it presumes having arandom-access machine. Theoretical discussions of data structures and algorithms have an unspoken tendency to presume a more restricted model (possibly that oflambda calculus, possibly that ofScheme), where a sparse table rather has to be built using trees, and data item access is not constant time. Traditional parsing algorithms such as theLL parser are not affected by this, but it becomes a penalty for the reputation of packrat parsers: they rely on operations of seemingly ill repute.
Viewed the other way around, this says packrat parsers tap into computational power readily available in real life systems, that older parsing algorithms do not understand to employ.
A PEG is calledwell-formed[1] if it contains noleft-recursive rules, i.e., rules that allow a nonterminal to expand to an expression in which the same nonterminal occurs as the leftmost symbol. For a left-to-right top-down parser, such rules cause infinite regress: parsing will continually expand the same nonterminal without moving forward in the string. Therefore, to allow packrat parsing, left recursion must be eliminated.
Direct recursion, be that left or right, is important in context-free grammars, because there recursion is the only way to describe repetition:
Sum→Term|Sum'+'Term|Sum'-'TermArgs→Arg|Arg','Args
People trained in using context-free grammars often come to PEGs expecting to use the same idioms, but parsing expressions can do repetition without recursion:
Sum←Term('+'Term/'-'Term)*Args←Arg(','Arg)*
A difference lies in theabstract syntax trees generated: with recursion eachSum orArgs can have at most two children, but with repetition there can be arbitrarily many. If later stages of processing require that such lists of children are recast as trees with boundeddegree, for example microprocessor instructions for addition typically only allow two operands, then properties such asleft-associativity would be imposed after the PEG-directed parsing stage.
Therefore left-recursion is practically less likely to trouble a PEG packrat parser than, say, an LL(k) context-free parser, unless one insists on using context-free idioms. However, not all cases of recursion are about repetition.
For example, in the arithmetic grammar above, it could seem tempting to express operator precedence as a matter of ordered choice —Sum / Product / Value would mean first try viewing asSum (since we parse top–down), second try viewing asProduct, and only third try viewing asValue — rather than via nesting of definitions. This (non-well-formed) grammar seeks to keep precedence order only in one line:
Value←[0-9.]+/'('Expr')'Product←Expr(('*'/'/')Expr)+Sum←Expr(('+'/'-')Expr)+Expr←Sum/Product/Value
Unfortunately matching anExpr requires testing if aSum matches, while matching aSum requires testing if anExpr matches. Because the term appears in the leftmost position, these rules make up acircular definition that cannot be resolved. (Circular definitions that can be resolved exist—such as in the original formulation from the first example—but such definitions are required not to exhibit pathological recursion.) However, left-recursive rules can always be rewritten to eliminate left-recursion.[2][15] For example, the following left-recursive CFG rule:
string-of-a←string-of-a'a'|'a'
can be rewritten in a PEG using the plus operator:
string-of-a←'a'+
The process of rewritingindirectly left-recursive rules is complex in some packrat parsers, especially when semantic actions are involved.
With some modification, traditional packrat parsing can support direct left recursion,[5][16][17] but doing so results in a loss of the linear-time parsing property[16] which is generally the justification for using PEGs and packrat parsing in the first place. Only theOMeta parsing algorithm[16] supports full direct and indirect left recursion without additional attendant complexity (but again, at a loss of the linear time complexity), whereas allGLR parsers support left recursion.
A common first impression of PEGs is that they look like CFGs with certain convenience features — repetition operators*+? as in regular expressions and lookahead predicates&! — plus ordered choice for disambiguation. This understanding can be sufficient when one's goal is to create a parser for a language, but it is not sufficient for more theoretical discussions of the computational power of parsing expressions. In particular thenondeterminism inherent in the unordered choice| of context-free grammars makes it very different from the deterministic ordered choice/.
PEG packrat parsers cannot recognize some unambiguous nondeterministic CFG rules, such as the following:[2]
S←'x'S'x'|'x'
NeitherLL(k) nor LR(k) parsing algorithms are capable of recognizing this example. However, this grammar can be used by a general CFG parser like theCYK algorithm. However, thelanguage in question can be recognised by all these types of parser, since it is in fact a regular language (that of strings of an odd number of x's).
It is instructive to work out exactly what a PEG parser does when attempting to match
S←'x'S'x'/'x'
against the stringxxxxxq. As expected, it recursively tries to match the nonterminalS at increasing positions in this string, until failing the match against theq, and after that begins to backtrack. This goes as follows:
Position: 123456 String: xxxxxq Results: ↑ Pos.6: Neither branch of S matches ↑ Pos.5: First branch of S fails, second branch succeeds, yielding match of length 1. ↑ Pos.4: First branch of S fails, second branch succeeds, yielding match of length 1. ↑ Pos.3: First branch of S succeeds, yielding match of length 3. ↑ Pos.2: First branch of S fails, because after the S match at 3 comes a q. Second branch succeeds, yielding match of length 1. ↑ Pos.1: First branch of S succeeds, yielding match of length 3.
Matching against a parsing expression isgreedy, in the sense that the first success encountered is the only one considered. Even if locally the choices are ordered longest first, there is no guarantee that this greedy matching will find the globally longest match.
LL(k) and LR(k) parser generators will fail to complete when the input grammar is ambiguous. This is a feature in the common case that the grammar is intended to be unambiguous but is defective. A PEG parser generator will resolve unintended ambiguities earliest-match-first, which may be arbitrary and lead to surprising parses.
The ordering of productions in a PEG grammar affects not only the resolution of ambiguity, but also thelanguage matched. For example, consider the first PEG example in Ford's paper[1](example rewritten in pegjs.org/online notation, and labelled and):
A = "a" "b" / "a"A = "a" / "a" "b"Ford notes thatThe second alternative in the latter PEG rule will never succeed because the first choice is always taken if the input string ... begins with 'a'..[1] Specifically, (i.e., the language matched by) includes the input "ab", but does not. Thus, adding a new option to a PEG grammar canremove strings from the language matched, e.g. is the addition of a rule to the single-production grammar A = "a" "b", which contains a string not matched by.Furthermore, constructing a grammar to match from PEG grammars and is not always a trivial task.This is in stark contrast to CFG's, in which the addition of a new production cannot remove strings (though, it can introduce problems in the form of ambiguity),and a (potentially ambiguous) grammar for can be constructed
S→start(G1)|start(G2)
It is anopen problem to give a concrete example of a context-free language which cannot be recognized by a parsing expression grammar.[1] In particular, it is open whether a parsing expression grammar can recognize the language of palindromes.[18]
The class of parsing expression languages is closed under set intersection and complement, thus also under set union.[1]: Sec.3.4
In stark contrast to the case for context-free grammars, it is not possible to generate elements of a parsing expression language from its grammar. Indeed, it is algorithmicallyundecidable whether the language recognised by a parsing expression grammar is empty! One reason for this is that any instance of thePost correspondence problem reduces to an instance of the problem of deciding whether a parsing expression language is empty.
Recall that an instance of the Post correspondence problem consists of a list of pairs of strings (of terminal symbols). The problem is to determine whether there exists a sequence of indices in the range such that. Toreduce this to a parsing expression grammar, let be arbitrary pairwise distinct equally long strings of terminal symbols (already with distinct symbols in the terminal symbol alphabet, length suffices) and consider the parsing expression grammarAny string matched by the nonterminal has the form for some indices. Likewise any string matched by the nonterminal has the form. Thus any string matched by will have the form where.