Sub topic 10
LL(1) Grammars and Predictive Parsing Tables
Prerequisites and working model
Assume you know context-free grammars, derivations, parse trees, and set notation. An LL(1) parser reads input from Left to right, constructs a Leftmost derivation, and uses one lookahead token. Its predictive parsing table chooses the production without backtracking.
Consider this expression grammar:
E -> T E'
E' -> + T E' | ε
T -> F T'
T' -> * F T' | ε
F -> ( E ) | idThe grammar gives * higher precedence than + because multiplication is handled inside T, before E combines terms. The transformed grammar also removes left recursion, which would prevent a simple recursive-descent implementation from terminating.
FIRST and FOLLOW sets
FIRST(X) contains terminals that can begin strings derived from X. If X can derive the empty string, ε is also included.
FOLLOW(X) contains terminals that can appear immediately after X in some sentential form. The end marker $ belongs to FOLLOW(E) because E is the start symbol.
| Symbol | FIRST | FOLLOW |
|---|---|---|
| `E` | `{ (, id }` | `{ ), $ }` |
| `E'` | `{ +, ε }` | `{ ), $ }` |
| `T` | `{ (, id }` | `{ +, ), $ }` |
| `T'` | `{ *, ε }` | `{ +, ), $ }` |
| `F` | `{ (, id }` | `{ *, +, ), $ }` |
For a production A -> α, place it in M[A, a] for every a in FIRST(α). If ε belongs to FIRST(α), also place it in M[A, b] for every b in FOLLOW(A).
A grammar is LL(1) when every table cell contains at most one production. Two productions in one cell indicate a predictive-parsing conflict.
Parsing with the table
The parser maintains a stack containing grammar symbols and $. Initially it contains $ E. At each step:
- If the stack top is a terminal matching the input token, pop both.
- If the top is a nonterminal, consult the table using that nonterminal and the lookahead token.
- Replace the nonterminal with the selected production's right side in reverse order.
- If no table entry exists, report a syntax error.
The table entries for the example include:
M[E, id] = M[E, (] = E -> T E'
M[E', +] = E' -> + T E'
M[E', )] = M[E', $] = E' -> ε
M[T, id] = M[T, (] = T -> F T'
M[T', *] = T' -> * F T'
M[T', +] = M[T', )] = M[T', $] = T' -> ε
M[F, id] = F -> id
M[F, (] = F -> ( E )class Parser:
def __init__(self, tokens):
self.tokens = tokens + ["$"]
self.i = 0
def parse(self):
self.E()
if self.tokens[self.i] != "$":
raise SyntaxError("extra input")
return True
def eat(self, token):
if self.tokens[self.i] != token:
raise SyntaxError(f"expected {token}, found {self.tokens[self.i]}")
self.i += 1
def E(self):
self.T()
self.Ep()
def Ep(self):
if self.tokens[self.i] == "+":
self.eat("+")
self.T()
self.Ep()
elif self.tokens[self.i] not in {")", "$"}:
raise SyntaxError("invalid continuation of expression")
def T(self):
self.F()
self.Tp()
def Tp(self):
if self.tokens[self.i] == "*":
self.eat("*")
self.F()
self.Tp()
elif self.tokens[self.i] not in {"+", ")", "$"}:
raise SyntaxError("invalid continuation of term")
def F(self):
if self.tokens[self.i] == "id":
self.eat("id")
elif self.tokens[self.i] == "(":
self.eat("(")
self.E()
self.eat(")")
else:
raise SyntaxError("expected id or (")
print(Parser(["id", "+", "id", "*", "id"]).parse())Exercise
Why does E' -> ε appear under + only when + starts another term, and under ) or $ when the expression ends?
Show answer
+ selects the nonempty production. ) and $ are in FOLLOW(E'), so they select the empty production and finish the expression.