Sub topic 18
Operator precedence parsing
This chapter assumes you know what a shift-reduce parser is (stack, input, shift, reduce, handle) and how FIRST and FOLLOW sets are built. Operator precedence parsing is a bottom-up method that decides between shift and reduce by comparing only the terminals. GATE CS asks you to fill in precedence tables, find precedence functions, and trace a parse.
Operator grammars
A grammar is an operator grammar if no production body is ε and no body has two adjacent nonterminals. This grammar qualifies:
E -> E + E | E * E | idThis one does not, because A B puts two nonterminals side by side:
S -> A BThe restriction guarantees that between any two nonterminals in a sentential form there is at least one terminal. The parser can therefore ignore nonterminals when choosing an action.
Precedence relations
For two terminals a and b, three relations are possible. Each is read as "a on the stack top, b as the next input".
| Relation | Meaning | Action |
|---|---|---|
| a <· b | a yields precedence to b | shift b |
| a =· b | a and b have equal precedence, as in the pair `(` and `)` | shift b |
| a ·> b | a takes precedence over b | reduce |
A blank cell means a syntax error. The relations are not symmetric, and a ·> b does not imply b <· a.
Computing the relations from the grammar
Two sets are needed for each nonterminal A:
- LEADING(A) is the set of terminals that can appear first in a string derived from A. The terminal may follow a single nonterminal.
- TRAILING(A) is the set of terminals that can appear last in a string derived from A. The terminal may precede a single nonterminal.
For E -> E + E | E * E | id, both sets equal {+, *, id}.
The rules, applied to every production body:
- If
a bora B bappears in a body, then a =· b. - If
a Aappears in a body, then a <· x for every x in LEADING(A). - If
A bappears in a body, then x ·> b for every x in TRAILING(A). - $ <· x for every x in LEADING(S), and x ·> $ for every x in TRAILING(S).
Applying these rules to the example grammar gives the table below. The rows are the stack-top terminals and the columns are the input terminals.
| Row | id | + | * | $ |
|---|---|---|---|---|
| **id** | ·> | ·> | ·> | |
| **+** | <· | ·> | <· | ·> |
| **\*** | <· | ·> | ·> | ·> |
| **$** | <· | <· | <· | accept |
Rows + and * show the grammar's priorities. + <· * makes * bind tighter. + ·> + and * ·> * make both operators left associative.
The parsing algorithm
- Let
abe the topmost terminal on the stack andbthe current input symbol. - If
a <· bora =· b, shiftb. - If
a ·> b, reduce. Pop the stack until the topmost terminal popped has<·to the terminal beneath it. The popped symbols are the handle. Replace them with the matching nonterminal. - If both are
$, accept. A blank cell is an error.
Trace of `id + id * id`
| Step | Stack | Input | Relation | Action |
|---|---|---|---|---|
| 1 | $ | id + id * id $ | $ <· id | shift |
| 2 | $ id | + id * id $ | id ·> + | reduce id |
| 3 | $ E | + id * id $ | $ <· + | shift |
| 4 | $ E + | id * id $ | + <· id | shift |
| 5 | $ E + id | * id $ | id ·> * | reduce id |
| 6 | $ E + E | * id $ | + <· * | shift |
| 7 | $ E + E * | id $ | * <· id | shift |
| 8 | $ E + E * id | $ | id ·> $ | reduce id |
| 9 | $ E + E * E | $ | * ·> $ | reduce E * E |
| 10 | $ E + E | $ | + ·> $ | reduce E + E |
| 11 | $ E | $ | $ and $ | accept |
In steps 6 and 7 the parser shifts * instead of reducing E + E. This is how * ends up binding tighter than +.
Precedence functions
A full table has n² cells. You can often replace it with two functions f and g, which store 2n numbers. The requirements are:
- a <· b means f(a) < g(b)
- a =· b means f(a) = g(b)
- a ·> b means f(a) > g(b)
One valid assignment for the table above is:
| Row | id | + | * | $ |
|---|---|---|---|---|
| f | 4 | 2 | 4 | 0 |
| g | 5 | 1 | 3 | 0 |
Check one cell: * ·> + needs f(*) = 4 > g(+) = 1, which holds. A left-associative operator has f > g, and a right-associative operator has f < g.
The functions lose information. Blank cells such as id id get numbers too, so errors are detected later, in a reduction step or at the end. Some tables have no valid functions at all. This happens when the relations contain a cycle in the comparison graph. In that case you must keep the full table.
Runnable example
This evaluator uses precedence functions for +, * and right-associative ^. Since f(^) = 5 is less than g(^) = 6, ^ shifts on ^.
F = {"$": 0, "+": 2, "*": 4, "^": 5}
G = {"$": 0, "+": 1, "*": 3, "^": 6}
def evaluate(tokens):
toks = list(tokens) + ["$"]
ops, vals, i = ["$"], [], 0
def reduce_once():
op = ops.pop()
if len(vals) < 2:
raise SyntaxError("missing operand")
b, a = vals.pop(), vals.pop()
vals.append(a + b if op == "+" else a * b if op == "*" else a ** b)
while True:
t = toks[i]
if isinstance(t, int):
vals.append(t)
i += 1
continue
top = ops[-1]
if top == "$" and t == "$":
break
if F[top] < G[t]:
ops.append(t)
i += 1
else:
reduce_once()
if len(vals) != 1:
raise SyntaxError("missing operator")
return vals[0]
print(evaluate([2, "+", 3, "*", 4])) # 14
print(evaluate([2, "^", 3, "^", 2])) # 512
print(evaluate([2, "*", 3, "+", 4])) # 10Limits and gotchas
- The unary minus is a problem. The token
-has one precedence as a binary operator and another as a unary one, so a single table row cannot describe it. Lexers often emit a separate token such asuminus. - The parser never checks which production it reduces. All nonterminals are treated as the same symbol, so it can accept strings the grammar does not generate. Real implementations add checks.
- Few grammars can be handled. Operator grammars exclude many practical languages. LR parsers accept every grammar this method accepts, and many more.
- Error cells can be shared across many different mistakes, which gives poor error messages.
Exercises
Exercise
For the grammar E -> E - E | E ^ E | id, with - left associative, ^ right associative and ^ higher than -, give the relations for the pairs (-, -), (^, ^), (-, ^) and (^, -).
Show answer
(-, -) is ·> because left associativity reduces first. (^, ^) is <· because right associativity shifts. (-, ^) is <· because ^ binds tighter. (^, -) is ·> because the higher-priority ^ on the stack is reduced before -.
Exercise
Is the grammar S -> A b, A -> a | ε an operator grammar? Give the reason.
Show answer
No. The production A -> ε has an empty body, and an operator grammar may not contain ε-productions.