Sub topic 14
Shift-reduce parsing and handles
This chapter assumes you know context-free grammars, derivations, and parse trees. It also assumes you are comfortable with stacks. The main idea is that a bottom-up parser builds a parse tree from the leaves up. It does this by tracing a rightmost derivation backwards.
The shift-reduce model
A shift-reduce parser keeps a stack of grammar symbols and an input buffer. The input ends with the end marker $. The parser starts with an empty stack and picks one of four actions at each step:
- Shift: move the next input token onto the stack.
- Reduce: the top of the stack holds the body of a production
A -> β. Popβand pushA. - Accept: the stack holds only the start symbol and the input is
$. - Error: no action is legal.
Each reduction is one step of a rightmost derivation, read in reverse. That is why this family is called LR: it scans the input Left to right and produces a Rightmost derivation.
Handles
A right-sentential form is any string that appears in a rightmost derivation from the start symbol. A handle of a right-sentential form γ is a substring β with two properties:
βis the body of some productionA -> β.- Replacing
βbyAgives the previous right-sentential form in the rightmost derivation.
The second property matters. A substring can match a production body without being a handle. Take the grammar
E -> E + T | T
T -> T * F | F
F -> ( E ) | idIn E + T * id, the substring T matches E -> T. Reducing it would give E + E * id, which is not a right-sentential form. The handle is id, reduced by F -> id.
If the grammar is unambiguous, each right-sentential form has exactly one handle. In an ambiguous grammar, a form can have more than one rightmost derivation, so the handle may not be unique.
Handle pruning and the stack
Repeatedly finding a handle and reducing it is called handle pruning. A key fact makes the stack work: the handle is always at the top of the stack, never buried. The parser therefore never has to search inside the stack. It only decides between shifting and reducing at the top.
The stack contents are always a viable prefix. That is a prefix of a right-sentential form that does not extend past the right end of the handle. As long as the stack is a viable prefix, the parser can still reach a successful parse.
Worked trace
Here is the trace for id + id * id with the grammar above.
| Stack | Input | Action |
|---|---|---|
| `$` | `id + id * id $` | shift |
| `$ id` | `+ id * id $` | reduce `F -> id` |
| `$ F` | `+ id * id $` | reduce `T -> F` |
| `$ T` | `+ id * id $` | reduce `E -> T` |
| `$ E` | `+ id * id $` | shift |
| `$ E +` | `id * id $` | shift |
| `$ E + id` | `* id $` | reduce `F -> id` |
| `$ E + F` | `* id $` | reduce `T -> F` |
| `$ E + T` | `* id $` | shift |
| `$ E + T *` | `id $` | shift |
| `$ E + T * id` | `$` | reduce `F -> id` |
| `$ E + T * F` | `$` | reduce `T -> T * F` |
| `$ E + T` | `$` | reduce `E -> E + T` |
| `$ E` | `$` | accept |
The row $ E + T with input * id $ is the important one. The top of the stack matches both E -> E + T and, by its last symbol, E -> T. The parser must shift, because the multiplication has higher precedence. The decision uses the lookahead *. A reduction by E -> E + T is only valid when the lookahead is in FOLLOW(E), and * is not in that set.
A small simulator
The program below reproduces the trace. It tries the longest matching production first. It reduces only when the lookahead is in the left-hand side's FOLLOW set. This is the SLR(1) rule applied without states. It is enough for this grammar and for the inputs shown, but it is not a general parser, because it has no item sets and no table.
PRODS = [
("E", ("E", "+", "T")),
("E", ("T",)),
("T", ("T", "*", "F")),
("T", ("F",)),
("F", ("(", "E", ")")),
("F", ("id",)),
]
FOLLOW = {
"E": {"+", ")", "$"},
"T": {"+", "*", ")", "$"},
"F": {"+", "*", ")", "$"},
}
def parse(tokens):
stack, rest = [], list(tokens) + ["$"]
while True:
look = rest[0]
for lhs, body in sorted(PRODS, key=lambda p: -len(p[1])):
n = len(body)
if tuple(stack[-n:]) == body and look in FOLLOW[lhs]:
del stack[-n:]
stack.append(lhs)
print(f"reduce {lhs} -> {' '.join(body)} stack={stack}")
break
else:
if stack == ["E"] and look == "$":
print("accept")
return True
if look == "$":
raise SyntaxError(f"cannot continue with stack {stack}")
stack.append(rest.pop(0))
print(f"shift {look} stack={stack}")
parse(["id", "+", "id", "*", "id"])Conflicts
A grammar is not suitable for a given shift-reduce method when the parser cannot choose an action from the stack and lookahead alone. There are two kinds of conflict:
- Shift-reduce conflict: both a shift and a reduction are legal. The classic example is the dangling
else. Afterif E then Swithelseas lookahead, the parser can shiftelseor reduce the shortif. - Reduce-reduce conflict: two different reductions are legal on the same stack top and lookahead.
Why the next chapters matter
This chapter left one question open: how does the parser decide between shifting and reducing? LR parsers answer it with a finite automaton over the stack. Its states are sets of items, and the next chapter builds them. The automaton recognizes viable prefixes, and the handle is the part of the stack that completes an item.
Exercise
Using the grammar E -> E + T | T, T -> T F | F, F -> ( E ) | id, give the handle of the right-sentential form `E + T id and state the reduction. Then explain why T in this form is not a handle even though E -> T has body T`.
Show answer
The handle is id, reduced by F -> id. The rightmost derivation ends with ... => E + T * F => E + T * id, so the last step in reverse replaces id by F. Reducing T by E -> T would produce E + E * id. That string is not a right-sentential form of this grammar, so that step does not reverse a rightmost derivation.
Exercise
A shift-reduce parser for this grammar has stack $ E + T and lookahead *. Should it shift or reduce, and why?
Show answer
It should shift. Reducing by E -> E + T needs the lookahead to be in FOLLOW(E) = { +, ), $ }, and * is not in it. Shifting * lets T * F be built first, so * binds tighter than +.