G52MAL: Lecture 18: Recursive-Descent Parsing: Elimination of Left Recursion
G52MAL: Lecture 18: Recursive-Descent Parsing: Elimination of Left Recursion
G52MAL: Lecture 18: Recursive-Descent Parsing: Elimination of Left Recursion
This Lecture
The problem of recursive-descent parsing and left recursive grammars. Elimination of left recursion.
Left Recursion
Consider: A Aa |
Left Recursion
Consider: A Aa | Parsing function: parseA ts = case parseA ts of Just (a : ts) -> Just ts _ -> Just ts
Left Recursion
Consider: A Aa | Parsing function: parseA ts = case parseA ts of Just (a : ts) -> Just ts _ -> Just ts Any problem?
Left Recursion
Consider: A Aa | Parsing function: parseA ts = case parseA ts of Just (a : ts) -> Just ts _ -> Just ts Any problem? Would loop! Recursive-descent parsers cannot deal with left-recursive grammars.
A grammar is left-recursive if there is some + non-terminal A such that A A. Certain parsing methods cannot handle left-recursive grammars.
A grammar is left-recursive if there is some + non-terminal A such that A A. Certain parsing methods cannot handle left-recursive grammars. If we want to use such a parsing method for parsing a language L = L(G) given by a left-recursive grammar G, then the grammar rst has to be transformed into an equivalent grammar G that is not left-recursive.
G2 :
S A A | Aa
We will rst consider immediate left recursion; i.e., productions of the form A A where cannot derive .
We will rst consider immediate left recursion; i.e., productions of the form A A where cannot derive . Key idea: A | A and A () are equivalent.
We will rst consider immediate left recursion; i.e., productions of the form A A where cannot derive . Key idea: A | A and A () are equivalent. The latter can be expressed as: A A A A |
G52MAL: Lecture 18 p. 6/17
Exercise
The following grammar G1 is immediately left-recursive: A b | Aa Draw the derivation tree for baa using G1 .
The following is a non-left-recursive grammar G1 equivalent to G1 : A bA A aA | Draw the derivation tree for baa using G1 .
G52MAL: Lecture 18 p. 7/17
rst transform the grammar into an immediately left-recursive grammar through systematic substitution then proceed as before.
Substitution
An occurrence of a non-terminal in a right-hand side may be replaced by the right-hand sides of the productions for that non-terminal if done in all possible ways. All productions for non-terminals that, as a result, cannot be reached from the start symbol, can be eliminated.
Exercise
Transform the following generally left-recursive grammar A BaB B Cb | C Ab | Ac into an equivalent immediately left-recursive grammar.
Solution
First: A BaB B Abb |Acb | A AbbaB | AcbaB | aB B Abb |Acb |
Then:
Or, eliminating B completely: A AbbaAbb | AcbaAbb | aAbb | AbbaAcb | AcbaAcb | aAcb | Abba | Acba | a
G52MAL: Lecture 18 p. 17/17