Sub topic 13
Recursive descent parsers
This chapter assumes you can compute FIRST and FOLLOW sets and fill an LL(1) table, and that you are comfortable reading short Python. A recursive descent parser is a top-down parser written as ordinary code. It has one function per nonterminal, and the call stack plays the role of the parse stack in a table-driven LL(1) parser.
The idea
A table-driven predictive parser keeps an explicit stack and looks up M[A, a] to pick a production. A recursive descent parser removes the table. Each nonterminal becomes a function, and the function body tests the lookahead token to choose a production. The program itself replaces the table.
The translation from grammar to code follows fixed rules.
| Grammar construct | Code | Column |
|---|---|---|
| Nonterminal `A` | A function `A()` | |
| Terminal `a` in a body | `eat(a)`, which checks the lookahead and advances | |
| Sequence `X Y` | Call `X()`, then call `Y()` | |
| Alternatives `A -> α \ | β` | `if` on the lookahead: the FIRST set of α selects α, the FIRST set of β selects β |
| Production `A -> ε` | Do nothing and return | |
| Tail `A' -> op T A' \ | ε` | Test for `op`. Otherwise return without consuming anything |
A complete parser
The grammar below is the LL(1) expression grammar from the FIRST and FOLLOW chapter. It has no left recursion.
E -> T E'
E' -> + T E' | ε
T -> F T'
T' -> * F T' | ε
F -> ( E ) | numEach function receives an inherited value inh, the value computed so far on the left. This turns the parser into an evaluator that keeps + and * left-associative.
class Parser:
def __init__(self, tokens):
self.toks = list(tokens) + ["$"]
self.i = 0
def peek(self):
return self.toks[self.i]
def eat(self, t):
if self.peek() != t:
raise SyntaxError(f"expected {t!r}, found {self.peek()!r}")
self.i += 1
def parse(self):
value = self.E()
self.eat("$") # reject trailing input such as 2 3
return value
def E(self): # E -> T E'
return self.Ep(self.T())
def Ep(self, inh): # E' -> + T E' | epsilon
if self.peek() == "+":
self.eat("+")
return self.Ep(inh + self.T())
return inh
def T(self): # T -> F T'
return self.Tp(self.F())
def Tp(self, inh): # T' -> * F T' | epsilon
if self.peek() == "*":
self.eat("*")
return self.Tp(inh * self.F())
return inh
def F(self): # F -> ( E ) | num
t = self.peek()
if t == "(":
self.eat("(")
v = self.E()
self.eat(")")
return v
if isinstance(t, int):
self.i += 1
return t
raise SyntaxError(f"unexpected token {t!r}")
print(Parser([2, "+", 3, "*", 4]).parse()) # 14
print(Parser(["(", 2, "+", 3, ")", "*", 4]).parse()) # 20
try:
Parser([2, "+"]).parse()
except SyntaxError as e:
print("error:", e) # error: unexpected token '$'The parse method adds a final eat("$"). Without it, the input 2 3 would stop after E() returns 2 and be accepted.
How the functions call each other
The static call structure mirrors the grammar. F calls E again for parenthesized input, which is the only place the recursion nests.
Why the grammar must be LL(1)
The if tests are the table entries in disguise. A function can choose correctly with one token of lookahead only when the alternatives of each nonterminal have disjoint FIRST sets. If a nonterminal can derive ε, FIRST of its other alternatives must also be disjoint from FOLLOW of that nonterminal. Two grammar defects break this.
- Left recursion. For
E -> E + T, the functionE()would callE()first, without consuming a token. The recursion never ends, and Python raisesRecursionError. Eliminate it before writing the code, as in the grammar transformations chapter. - Common prefixes. For
S -> if C then S | if C then S else S, one token of lookahead cannot choose between the alternatives. Left factor the grammar first.
Predictive versus backtracking
The parser above is predictive, because it never undoes a choice. A backtracking recursive descent parser instead tries alternatives in order and resets self.i after a failure. It accepts grammars that are not LL(1), but it can take exponential time and it must undo any side effects. GATE questions treat "recursive descent" as the predictive form unless the question says backtracking.
Common errors
- Writing
eatfor a nonterminal. Nonterminals are called, and only terminals are matched. - Forgetting the end-marker check, so trailing garbage is accepted.
- Folding left-associative operators the wrong way. Passing
inhleftward, as inEp(inh + self.T()), gives left associativity. Recursing on the right gives right associativity. - Treating the ε case as an error. An empty production is a normal return.
Exercise
A recursive descent parser for the grammar S -> a S b | ε is called on the token sequence a a b. It tests the lookahead for a to choose the first production, and otherwise returns. Does it accept the input? Explain where the error is found.
Show answer
No. S matches the first a, calls S recursively, which matches the second a and calls S again. This third call sees b, which is not a, so it takes the ε branch and returns. The second call then runs eat(b), which consumes b. The first call runs eat(b) but finds $, so it raises a SyntaxError. The input has two a's but only one b. The error is found by the caller's eat(b), not by the ε branch.
Exercise
Why can a recursive descent parser not be written directly from E -> E + T | T, and what is the fix?
Show answer
E() would call E() as its first action without consuming input, giving infinite recursion. Rewrite the grammar as E -> T E' and E' -> + T E' | ε, then write one function for each nonterminal.