Sub topic 8
Removing Left Recursion and Left Factoring
Assume you know context-free grammars, derivations, parse trees, and the basic idea of predictive parsing. This chapter prepares a grammar for top-down parsing, especially LL(1) parsing.
Why grammar transformation is needed
A recursive-descent parser usually has one procedure for each nonterminal. A procedure must decide which production to use from the next input token. Two grammar patterns make this difficult:
- Left recursion can make a recursive-descent procedure call itself forever.
- Common prefixes can prevent the parser from choosing a production using limited lookahead.
These transformations change the grammar's form while preserving its language. They may change parse-tree shape, so semantic actions sometimes need adjustment.
Removing immediate left recursion
A nonterminal has immediate left recursion when it has a production of the form:
A -> A α | βThe production beginning with A is recursive before the parser consumes any input. Replace it with:
A -> β A'
A' -> α A' | εHere, A' is a new nonterminal and ε means the empty string.
For example, the expression grammar:
E -> E + T | Tbecomes:
E -> T E'
E' -> + T E' | εThe original grammar describes one or more terms separated by plus signs. The new grammar describes the first term followed by zero or more + T parts.
The same transformation handles several recursive alternatives:
A -> A α1 | A α2 | β1 | β2becomes:
A -> β1 A' | β2 A'
A' -> α1 A' | α2 A' | εIndirect left recursion
Left recursion can pass through another nonterminal:
A -> B a | c
B -> A b | dTo remove it, order the nonterminals, substitute earlier productions into later ones, and then remove any immediate left recursion that appears. The order matters for the procedure, although different valid transformed grammars may result.
A common error is to remove only visible patterns such as A -> A α. Always check whether a chain of productions can return to the same nonterminal on the left.
Left factoring
Left factoring postpones a choice when alternatives begin with the same symbols. For:
A -> α β1 | α β2use:
A -> α A'
A' -> β1 | β2For example:
S -> if E then S else S | if E then Scan be factored as:
S -> if E then S S'
S' -> else S | εThe parser now consumes the shared prefix before choosing whether an else follows. Factoring does not by itself resolve the traditional dangling-else ambiguity. That requires a language rule or a grammar designed to distinguish matched and unmatched statements.
How to choose the transformation
| Problem | Transformation | Main purpose |
|---|---|---|
| `A` begins an alternative for `A` | Remove left recursion | Prevent infinite top-down recursion |
| Alternatives share a prefix | Left factor | Delay a parsing decision |
| Both problems occur | Apply both carefully | Prepare the grammar for FIRST/FOLLOW analysis |
Exercise
Transform A -> A - B | B to remove immediate left recursion.
Show answer
A -> B A' and A' -> - B A' | ε.