Why do recursive descent parsers fail on left recursive grammars? Demonstrate the algorithm to eliminate immediate left recursion by introducing a new non-terminal.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question about compiler design and parsing theory. Let me break this down thoroughly.
Why Recursive Descent Parsers Fail on Left Recursive Grammars
A recursive descent parser works by having each non-terminal map to a function/procedure. When parsing a non-terminal A, the function calls the appropriate production rules. The problem with left recursion is:
A production rule of the form: A → A α | β
When trying to parse A, the parser would:
Call function for A
This tries the first production: A → A α
Which immediately calls A again
This calls function for A again
This tries the first production: A → A α again
Which calls A again... infinitely
This creates infinite recursion - a stack overflow without ever consuming any input.
Why This Happens
The fundamental issue is that recursive descent parsers use top-down parsing and make decisions predictively:
They don't backtrack (usually, in LL(1) parsers)
They need to look at the first token to decide which production to use
With left recursion, the parser tries to derive the first symbol by calling the same non-terminal again
Before it can look at the input, it's already in an infinite loop
Eliminating Immediate Left Recursion
For immediate left recursion of the form:
code
A → A α₁ | A α₂ | ... | A αₙ | β₁ | β₂ | ... | βₘ
Where:
α₁, α₂, ..., αₙ are the left-recursive alternatives
β₁, β₂, ..., βₘ are the non-left-recursive alternatives
We transform it by introducing a new non-terminal (let's call it A'):
code
A → β₁ A' | β₂ A' | ... | βₘ A'
A' → α₁ A' | α₂ A' | ... | αₙ A' | ε
The key insight is that A starts with a base case, then A' handles zero or more repetitions of the recursive part in a right-recursive manner instead.
Example
Original (left-recursive):
code
E → E + T | T
Transformed (right-recursive):
code
E → T E'
E' → + T E' | ε
Now E begins by parsing T, then E' optionally matches additional + T sequences. This eliminates the infinite recursion since we consume input before recursing.
Parsing "a + b + c" with the transformed grammar works because E first matches T (consuming 'a'), then E' sees the '+' and recursively processes the remaining operations. Each recursive call in E' consumes at least one token before calling itself again, preventing infinite loops.
Why Recursive Descent Parsers Fail on Left Recursion
The Problem
Left recursion causes infinite recursion in top-down parsers because:
code
Grammar: A → A α | β
Parsing flow:
1. parse_A() called
2. Try first production: A → A α
3. Immediately calls parse_A() again (step 1)
4. ... to infinity (stack overflow)
The parser never consumes input before recursing, creating an infinite loop.
Why It Can't Work
code
A → A + T | T // Left-recursive expression
parse_A():
if next_token matches first alternative:
parse_A() // ← Stack overflow before looking at input!
// never gets here
Eliminating Immediate Left Recursion
The Algorithm
Original (left-recursive):
code
A → A α₁ | A α₂ | ... | A αₙ | β₁ | β₂ | ... | βₘ
Transform to (right-recursive):
code
A → β₁ A' | β₂ A' | ... | βₘ A'
A' → α₁ A' | α₂ A' | ... | αₙ A' | ε
Why This Works
A matches a base case (β) followed by the new non-terminal
A' handles repetition right-recursively instead of left-recursively
No immediate recursion means the parser can consume input before recursing
Concrete Example
Before: Expression Grammar (Left-Recursive)
rst
E → E + T | E - T | T
T → T * F | T / F | F
F → ( E ) | id
This fails on recursive descent:
python
def parse_E():
if lookahead in {'+', '-', 'id', '('}:
parse_E() # ← INFINITE LOOP!
# ... rest unreachable
After: Transformed Grammar (Right-Recursive)
rst
E → T E'
E' → + T E' | - T E' | ε
T → F T'
T' → * F T' | / F T' | ε
F → ( E ) | id
Implementation: Recursive Descent Parser
Python Code
python
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.pos = 0
def peek(self):
if self.pos < len(self.tokens):
return self.tokens[self.pos]
return None
def consume(self, expected=None):
token = self.peek()
if expected and token != expected:
raise SyntaxError(f"Expected {expected}, got {token}")
self.pos += 1
return token
# E → T E'
def parse_E(self):
return ('E', self.parse_T(), self.parse_E_prime())
# E' → + T E' | - T E' | ε
def parse_E_prime(self):
if self.peek() in ['+', '-']:
op = self.consume()
return (op, self.parse_T(), self.parse_E_prime())
return ('ε', None, None) # epsilon (empty)
# T → F T'
def parse_T(self):
return ('T', self.parse_F(), self.parse_T_prime())
# T' → * F T' | / F T' | ε
def parse_T_prime(self):
if self.peek() in ['*', '/']:
op = self.consume()
return (op, self.parse_F(), self.parse_T_prime())
return ('ε', None, None)
# F → ( E ) | id
def parse_F(self):
token = self.peek()
if token == '(':
self.consume('(')
result = self.parse_E()
self.consume(')')
return ('F', result)
elif token == 'id':
value = self.consume('id')
return ('id', value)
else:
raise SyntaxError(f"Unexpected token: {token}")
# Test
tokens = ['id', '+', 'id', '*', 'id']
parser = Parser(tokens)
ast = parser.parse_E()
print("✓ Parse successful!")
Visual Comparison
Left-Recursive (❌ FAILS)
code
E → E + T | T
Parse tree expansion for "a":
E
└─ E + T (rule chosen)
└─ E (recurse: stack grows infinitely)
└─ E + T (rule chosen again)
└─ E (recurse: infinite)
Right-Recursive (✓ WORKS)
code
E → T E'
E' → + T E' | ε
Parse tree for "a + b":
E
/ \
T E'
│ / \
F + T E'
│ │ / \ / \
a │ F ε ε ε
│ │
│ b
Key Differences
Aspect
Left-Recursive
Right-Recursive
Recursion Type
A → A α
A → α A'
Works with
LALR, LR parsers
LL, Recursive Descent
Associates
Left (correct for +,-)
Right (must compensate)
Parsing order
Bottom-up
Top-down
Handling Associativity
Right-recursive grammar associates right, but we need left:
2 - 3 - 4 should parse as (2 - 3) - 4, not 2 - (3 - 4)
Solution: Track operations during parsing and adjust: