S
Aa | b
A
Ac | Sd | ε
there is a left recursion because
S
Aa
Sda
. In such cases, left recursion is removed systematically
- Starting from the first rule and replacing all the occurrences of the first non terminal symbol
- Removing left recursion from the modified grammar
What we saw earlier was an example of immediate left recursion but there may be subtle cases where left recursion occurs involving two or more productions. For example in the grammar
S
A a | b
A
A c | S d | e
there is a left recursion because
S
A a
S d a
More generally, for the non-terminals A 0, A 1,..., An , indirect left recursion can be defined as being of the form:
An
A1 a 1 | .
A1
A2 a2 |
.
.
A n
An a(n+1) | .
Where a 1 , a2 ,..., a n are sequences of non-terminals and terminals.
Following algorithm may be used for removal of left recursion in general case:
Input : Grammar G with no cycles or e -productions.
Output: An equivalent grammar with no left recursion .
Algorithm:
Arrange the non-terminals in some order A1 , A2 , A3 ..... An .
for i := 1 to n do begin
replace each production of the form Ai
Ajγ
by the productions A i
d1 γ | d2 γ | ...........| dkγ
where Aj
d1 | d2 | .........| dk are all the current Aj -productions;
end
eliminate the immediate left recursion among the Ai-productions.
end.