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
Explaining recursive descent failure and eliminating immediate left recursion
Recursive descent parsers fail on left-recursive grammars because they call the same parsing function recursively without consuming input, causing infinite recursion. To eliminate immediate left recursion in productions like A → A α | β, we introduce a new non-terminal A′ and rewrite the rules as: A → β A′ and A′ → α A′ | ε. For example, E → E + T | T becomes E → T E′ and E′ → + T E′ | ε, which avoids left recursion and enables recursive descent parsing.
A hand‑written recursive–descent parser mirrors the grammar: for each non‑terminal (A) you write a routine that looks at the next token and calls other routines corresponding to the symbols on the right–hand side of one of (A)’s productions.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
If the grammar contains a left–recursive production of the form
A → A α
or, more generally, (A) can derive a sentential form starting with (A) again, then A() will call itself before having consumed any input. In the immediate case A() executes, matches no terminal, and recurses into A() again, and so on until the call stack overflows. That’s why naïve top‑down parsers “fail” on left recursion: they get into an infinite recursion without making progress through the input.
The standard way to deal with this is to rewrite the grammar to eliminate left recursion. For immediate left recursion on a single nonterminal (A), with productions split into the left‑recursive and non‑left‑recursive alternatives,
A → A α1 | A α2 | … | A αn | β1 | β2 | … | βm
where each (\beta_i) does not start with (A), you introduce a new non‑terminal, often written (A'), and transform the productions as follows:
Replace (A)’s productions with
A → β1 A' | β2 A' | … | βm A'
Add productions for (A'):
A' → α1 A' | α2 A' | … | αn A' | ε
Here (ε) denotes the empty string.
This grammar generates the same language but is no longer left–recursive, so a recursive descent parser can handle it. For example, for the classic arithmetic expression rule
E → E "+" T | T
we have (α₁) = "+" T and (β₁) = T. Applying the transformation yields
E → T E'
E' → "+" T E' | ε
Now E() can be implemented as “parse a T, then as long as there is a plus sign, parse another T,” which terminates and consumes input instead of recursing immediately on itself.