In computer science, an operator-precedence parser is a bottom-up parser that interprets an operator-precedence grammar. It is a form of shift-reduce parser that uses the relative precedence of operators to decide when to reduce a sequence of symbols on its stack, rather than relying on a full state machine of the kind used in LR parsing. The technique is most commonly applied to the parsing of arithmetic and logical expressions, and it appears in many calculators and programming-language compilers.
Definition and relation to other parsers
An operator-precedence parser operates on grammars satisfying certain restrictions. It is capable of parsing a subset of LR(1) grammars: more precisely, it can parse the LR(1) grammars in which no production contains two adjacent nonterminals in its right-hand side and no production contains the empty string (epsilon). Grammars of this restricted class are called operator-precedence grammars (also operator grammars).
Because the parser deliberately ignores the distinction between individual nonterminals, treating all nonterminals as interchangeable for the purpose of locating handles, it is simpler than more general shift-reduce parsers such as LALR parsers. This simplification is also the source of its limitations, since it cannot parse grammars whose disambiguation depends on the identity of a nonterminal.
Precedence relations
The method rests on three precedence relations defined between terminal symbols (primarily the operators of the language):
- a ≐ b — a has the same precedence as b
- a ⋖ b — a "yields precedence to" b
- a ⋗ b — a "takes precedence over" b
These relations make it possible to delimit the handle (the substring to be reduced) in a right-sentential form: the left end of the handle is marked by a ⋖ relation, its interior consists of ≐ relations, and its right end is marked by a ⋗ relation. These dotted relations do not have all the algebraic properties of ordinary comparison operators; for example, ⋖ does not generally imply that ⋗ does not hold, and the relations are not necessarily transitive.
For a simple expression grammar with the terminals id, +, * and the end-of-string marker $, the relations follow from the facts that + has lower precedence than * and that both are left-associative. An input string such as id1 + id2 * id3, after end markers are added and relations inserted, becomes a sequence in which the handle is readily identified by the surrounding ⋖ and ⋗ markers.
Parsing algorithm
The parsing algorithm uses a stack. With a the topmost terminal on the stack and b the next input symbol, the standard formulation proceeds roughly as follows:
- If a ⋖ b or a ≐ b, push b onto the stack and advance to the next input symbol.
- If a ⋗ b, repeatedly pop the stack until the new top terminal is related by ⋖ to the terminal most recently popped.
- If no relation applies, report an error.
When the end marker is at the top of the stack and at the current input position, the parse is accepted.
Rather than storing the full precedence table, implementations frequently define precedence functions f and g that map terminals to integers, so that the relations are realized by numerical comparison. Not every precedence table admits such functions, but in practice they can be constructed for most grammars; a table admits precedence functions exactly when an associated directed graph (built from the relations) contains no cycles. The graph and its longest paths then yield the values of f and g.
Implementations and related algorithms
Several widely used algorithms realize operator-precedence parsing or closely related ideas:
- Shunting-yard algorithm. Described by Edsger Dijkstra in connection with early ALGOL 60 compilation, this algorithm keeps operators on a stack until their operands are available, and is commonly used to produce Reverse Polish notation or to evaluate expressions directly.
- Precedence climbing. A compact, efficient, and flexible method first described by Martin Richards and Colin Whitby-Strevens in the context of the BCPL compiler, and later named and analyzed by Theodore Norvell. It uses recursive calls to implement the stack, making the size and running time of the parser essentially independent of the number of precedence levels. It is used in the Clang C/C++ front end and in the ANTLR parser generator, among other systems.
- Top-down operator precedence (Pratt parsing). Introduced by Vaughan Pratt in 1973, this method associates with each token a "null denotation" and a "left denotation" and uses binding powers to decide the grouping of operands. It can be viewed as a generalization of precedence climbing, and it is well suited to dynamic languages that permit user-defined operators with custom precedence and associativity.
- Full parenthesization. An early approach, used in the FORTRAN I compiler, rewrites an expression by inserting parentheses so that a simple left-to-right parser reproduces the correct precedence. Knuth noted that "the resulting formula is properly parenthesized, believe it or not."
Worked example
For the input 2 + 3 * 4 + 5 , assigning precedence 0 to equality, 1 to addition, and 2 to multiplication, a precedence-climbing parser consumes 19
+ first, then recursively consumes the higher-precedence * to form 3 * 4, reduces to 2 + 12, then handles the second + to obtain 14 + 5, and finally applies , yielding a truth value.
Applications
Operator-precedence parsers are not used as the sole parsing mechanism for most large languages, but they have properties that make them valuable as components within a larger design. They are simple enough to write by hand, which is generally not the case for more sophisticated right shift-reduce parsers, and they can be written to consult an operator table at run time, which suits languages whose set of operators can change while parsing. Examples include:
- Hand-coded recursive-descent parsers for C and C++ in GCC, which use an operator-precedence parser to examine arithmetic expressions quickly.
- The Haskell language, which permits user-defined infix operators with custom associativity and precedence, requiring that operator-precedence parsing be performed after all referenced modules have been parsed.
- Raku, which sandwiches an operator-precedence parser between two recursive-descent parsers to balance speed and dynamism.
- The Mathics3 implementation of the Wolfram language, which uses precedence climbing to handle a large number of operators with individual precedence levels.
Languages and theory
The class of languages described by operator-precedence grammars is strictly contained in the class of deterministic context-free languages and strictly contains the visibly pushdown languages. Operator-precedence languages enjoy several closure properties—union, intersection, complementation, and concatenation—and they are the largest class known to be closed under all of these operations while still having a decidable emptiness problem. They also possess the property of local parsability, which enables efficient parallel parsing, and they admit characterizations in terms of an equivalent form of automata and monadic second-order logic.
Limitations
Because all nonterminals are treated alike, operator-precedence parsing cannot directly express grammars in which nonterminal identity is needed for disambiguation. The requirement that no production contain two adjacent nonterminals further restricts the applicable class of grammars. Implementations that build only "shift" and "reduce" decisions are also noted to accept some malformed input, such as expressions with omitted operators between arguments, so that additional error checking may be necessary for robust use.
See also
- Operator-precedence grammar
- Shift-reduce parsing
- Shunting-yard algorithm
- LR parser
- Recursive descent parser
References
- Aho, Alfred V.; Sethi, Ravi; Ullman, Jeffrey D. (1988). Compilers — Principles, Techniques, and Tools. Addison-Wesley.
- Clarke, Keith (1986). "The top-down parsing of expressions". Research Report 383, Queen Mary College.
- Norvell, Theodore S. "Parsing Expressions by Recursive Descent".
- Pratt, Vaughan R. (1973). "Top Down Operator Precedence". Proceedings of the 1st Annual ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages.
- Crespi Reghizzi, Stefano; Mandrioli, Dino (2012). "Operator precedence and the visibly pushdown property". Journal of Computer and System Sciences.