Title: LEFT RECURSION
1LEFT RECURSION
2LEFT RECURSION
A grammar is said to be left recursive if it has
a non-terminal A such that there is a derivation
A gtAa, for some string a.
Consider the grammar (i) A -gt Aab
Corresponding grammar without left recursion A
-gtbR R-gtaRe
3We can eliminate immediate left recursion from
them by the following technique . First we group
the A-productions as
A -gt Aa1 Aa2 Aa3 ... Aam b1 b2 b3
.... bn where no bi begins with an A.
Then we replace the A-productions by A -gt b1T
b2T b3T ...... bnT T -gt a1T a2T a3T
...... amT e
4The above process removes all immediate left
recursions but does not remove recursions
involving derivations of two or more steps.
Consider the grammar S -gt Aa A -gt Sb c..
Here the grammar does not have immediate left
recursion .. but has a left recursion because S
gtAa gt Sba
5In such cases we set a hierarchy among
non-terminals and implement the following
algorithm.
- Arrange the non-terminals n some order
A1,A2, An (setting the hierarchy)
62. for i1 to n for j1 to i-1
Replace each production of the form Ai -gt
Ajg by the production Ai-gtd1g d2g ....
dkg where, Aj -gt d1 d2 d3 ..... dk
are all the current Aj positions
Eliminate the immediate left recursion among the
Ai productions
7For the above grammar, S-gtAa A-gtAabc
After removing immediate left recursion
S-gtAa A-gtcT T-gtabTe
8LEFT FACTORING
Left factoring is a grammar transformation that
is useful for producing a grammar suitable for
predictive parsing.
Basi Idea When it is not clear which of two
alternative productions to use to expand a
non-terminal A, we may be able to rewrite the
A-productions to defer the decision until we have
seen enough of the input to make the right
choice.
9For example, A-gtab1 ab2
are two A-productions
If the input begins with a non-empty string
derived from a we do not know whether to expand
A to ab1 or ab2 .
However , we may defer the decision by expanding
A to aB .
10Now, we may expand B to b1 or b2
The left factored original expression
becomes A-gtaB B-gtb1b2
11END