Sub topic 11
Recursive Descent and Shift-Reduce Parsing
Assume you know context-free grammars, parse trees, stacks, and recursion. This chapter uses the expression grammar:
E -> T E'
E' -> + T E' | ε
T -> F T'
T' -> * F T' | ε
F -> ( E ) | numThe grammar has no left recursion, so it can guide a top-down parser.
Recursive descent parsers
A recursive descent parser is a collection of mutually recursive procedures. Each procedure recognizes one nonterminal. The parser chooses a production by examining the next input token. For an LL(1) grammar, one lookahead token is enough.
The following parser evaluates expressions containing integers, +, *, and parentheses. The inherited argument passed to Ep and Tp carries the partial result.
class Parser:
def __init__(self, tokens):
self.tokens = list(tokens) + ["$"]
self.pos = 0
def peek(self):
return self.tokens[self.pos]
def eat(self, expected):
if self.peek() != expected:
raise SyntaxError(
f"expected {expected!r}, found {self.peek()!r}"
)
self.pos += 1
def E(self):
return self.Ep(self.T())
def Ep(self, inherited):
if self.peek() == "+":
self.eat("+")
return self.Ep(inherited + self.T())
return inherited
def T(self):
return self.Tp(self.F())
def Tp(self, inherited):
if self.peek() == "*":
self.eat("*")
return self.Tp(inherited * self.F())
return inherited
def F(self):
if self.peek() == "(":
self.eat("(")
value = self.E()
self.eat(")")
return value
if isinstance(self.peek(), int):
value = self.peek()
self.pos += 1
return value
raise SyntaxError(f"unexpected token {self.peek()!r}")
parser = Parser([2, "+", 3, "*", 4])
print(parser.E()) # 14The grammar structure gives multiplication higher precedence than addition because E contains T, while T contains F. A common error is to write a recursive descent function directly for a left-recursive rule such as E -> E + T. That function calls itself before consuming input and does not terminate. Eliminate left recursion first.
Shift-reduce parsing and handles
A shift-reduce parser works bottom up. It maintains a stack of grammar symbols and repeatedly performs one of these actions:
- Shift: move the next input token onto the stack.
- Reduce: replace a handle on the stack with the left side of a production.
- Accept: confirm that the start symbol was derived.
- Error: report that no valid action exists.
A handle is the substring that matches the right side of a production and should be reduced next. Reducing handles reconstructs a rightmost derivation in reverse.
For id + id with E -> E + T, E -> T, and T -> id:
| Stack | Action |
|---|---|
| `$ id` | shift `id` |
| `$ T` | reduce `T -> id` |
| `$ E` | reduce `E -> T` |
| `$ E + id` | shift `+`, then `id` |
| `$ E + T` | reduce `T -> id` |
| `$ E` | reduce `E -> E + T` |
The final reduction has E + T as its handle. LR parsers use states and lookahead tokens to decide when a handle is complete. A shift-reduce conflict occurs when both shifting and reducing appear possible.
Exercise
Why must left recursion be removed before using ordinary recursive descent?
Show answer
A rule such as E -> E + T makes the E procedure call itself without consuming a token, causing nontermination.