Indirect left recursion occurs as follows:
Suppose we have non-terminals
and that
are mixtures of terminals
and non-terminals, then the production rules:
could result in a leftmost derivation of the form:
Again, such a derivation would cause problems during a top-down parse.
If we have a grammar that does not have a derivation of the form
, for any non-terminal (ie. the grammar has no
cycles), and there are no -productions, then we can apply
the following algorithm to eliminate all left recursion.
Let represent any mixture of terminals and non-terminals. Then:
This algorithm is preventative in nature - it does not look for left
recursion and then eliminate it; instead, it rearranges the grammar so
that no left recursion can possibly occur. Thus, even
non-left-recursive grammars may be rewritten using this algorithm.
The effect of step 2(a) above is to eliminate all production rules of
the form
for every ; in
other words, if we have a chain of derivations of the form:
We can be sure that the index of is increasing all the time,
and so can never get back around to 0 at any stage in the derivation
(which would have caused recursion).