Sub topic 10
Removing left recursion and left factoring
This chapter assumes you can read a context-free grammar, expand a derivation, and compute FIRST and FOLLOW sets. It covers the two grammar rewrites that make a grammar usable by a top-down parser.
Why top-down parsers need these rewrites
A top-down parser predicts a production by looking at the next input token. Two grammar shapes defeat it.
- Left recursion means a nonterminal can derive a string that starts with itself. A recursive descent function for
E -> E + TcallsE()first, which callsE()again without consuming any input, so it never terminates. - A common prefix means two productions of one nonterminal start with the same symbols. The next token cannot choose between them, so an LL(1) table cell holds two productions.
| Problem | Symptom | Fix |
|---|---|---|
| Left recursion | Infinite recursion, or a table with a FIRST set that repeats | Left recursion elimination |
| Common prefix | Two productions in one LL(1) cell | Left factoring |
Both rewrites keep the language the same. They change only the grammar's shape.
Immediate left recursion
A production is immediately left recursive if it has the form A -> Aα | β. Here α is a non-empty string of symbols, and β is any alternative that does not start with A. Replace it with:
A -> β A'
A' -> α A' | εThe original grammar generates β followed by zero or more α. The new grammar generates the same strings, but it consumes β before it recurses. For the standard expression grammar:
E -> E + T | T becomes E -> T E'
E' -> + T E' | εIf there are several alternatives, A -> Aα1 | Aα2 | β1 | β2, every β gets A' appended and every α becomes an A' alternative.
The following Python function does this rewrite. A production is a list of symbols, and an empty list stands for ε.
def eliminate_immediate(nt, prods):
recursive = [p[1:] for p in prods if p and p[0] == nt]
others = [p for p in prods if not p or p[0] != nt]
if not recursive:
return {nt: prods}
new = nt + "'"
return {
nt: [p + [new] for p in others],
new: [alpha + [new] for alpha in recursive] + [[]],
}
print(eliminate_immediate("E", [["E", "+", "T"], ["T"]]))
# {'E': [['T', "E'"]], "E'": [['+', 'T', "E'"], []]}Indirect left recursion
Left recursion can hide behind other nonterminals. In S -> Aa | b and A -> Sd | f, we have S => Aa => Sda, so S is left recursive even though no production starts with S on its own right side.
The standard algorithm orders the nonterminals A1, ..., An. It then does the following.
- For each
Aiin order, and for eachj < i, replace every productionAi -> AjγwithAi -> δ1γ | δ2γ | ..., whereAj -> δ1 | δ2 | ...are the current productions ofAj. - Eliminate the immediate left recursion in
Ai.
Worked example with order S, A:
S -> A a | b
A -> A c | S d | fS has no immediate left recursion. For A, substitute S in A -> S d:
A -> A c | A a d | b d | fNow eliminate the immediate left recursion in A:
S -> A a | b
A -> b d A' | f A'
A' -> c A' | a d A' | εThe algorithm is guaranteed to work only if the grammar has no cycles (A =>+ A) and no ε-productions. Remove those first. Different orderings give different, equally valid grammars, which matters in GATE questions that ask for a specific result.
Left factoring
If A -> αβ1 | αβ2 with a non-empty common prefix α, defer the decision until after α has been read:
A -> α A'
A' -> β1 | β2Apply this repeatedly until no two alternatives of any nonterminal share a prefix. A hidden prefix may only appear after you expand a nonterminal. For example, A -> B x | C y with B -> p q and C -> p r needs substitution before factoring.
Take the dangling-else grammar, where E -> b and S -> a are the expression and simple statement:
S -> i E t S | i E t S e S | aAfter factoring:
S -> i E t S S' | a
S' -> e S | εNow FIRST(S') = {e, ε}. Because S ends the production S -> i E t S S' and is followed by S', e is in FOLLOW(S). Since S' ends its productions, FOLLOW(S') = FOLLOW(S), so e is also in FOLLOW(S').
Effects on the parse tree and on LR parsers
Eliminating left recursion changes the parse tree. In the new grammar 1 + 2 + 3 yields a right-leaning tree, but + must still associate to the left. Restore this by passing the running value down as an inherited attribute, as the Ep(inh) method does in the recursive descent parser. Only top-down parsers need the rewrite. LR parsers handle left recursion well, and it keeps the stack shallow, so do not rewrite a grammar before an SLR, LALR, or CLR construction.
Exercise
Eliminate left recursion from A -> A x | A y | z | w. Then left factor B -> a b c | a b d | a e.
Show answer
For A: A -> z A' | w A' and A' -> x A' | y A' | ε. For B, first factor a: B -> a B' with B' -> b c | b d | e. Then factor b: B' -> b B'' | e with B'' -> c | d.
Exercise
Is S -> S a | b LL(1) as written? What does FIRST(S) look like, and what is the grammar after the rewrite?
Show answer
No. Both productions start with b in FIRST(S), so M[S, b] would hold two productions, and a recursive descent parser would loop forever. After the rewrite, S -> b S' and S' -> a S' | ε, which is LL(1) because FIRST(a S') = {a} and FOLLOW(S') = {$} do not overlap.