Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 11

ELIMINATION OF LEFT

RECURSION AND
SOLVING NON-
DETERMINISTIC
GRAMMARS
Left and Right Recursion
 If the left most symbol of the right hand side is
equal to right hand side then it is left recursion
 A -> A α | β

 And if the Right most symbol of the right hand side


is equal to right hand side then it is right recursion
 A -> α A | β
Problem with Top Down Parsers
 Suppose the grammar were
E→E+T|T
T→T*F|F
F → (E) | id

Calculate first sets?


Eliminating Left Recursion
 Left recursion in a production may be removed by
transforming the grammar in the following way.
 Replace
A  A | 
with
A  A'
A'  A' | .
Example: Eliminating Left
Recursion
 Consider the left recursive grammar
EE+T|T
Apply the transformation to E:
E  T E'
E'  + T E' | .
Example:
 S->S0S1S | 01

 S  01S’
 S’  OS1SS’ / €
Example:
 A  AB / Aa / a

 A  a A’
 A’  B  A’ / €

 A  a A’
 A’  aA’ / €
 Eliminate repeated step for final answer.
Example:
 A  Ac/ Aad/bd/c

 A  bdA’/cA’
 A’ cA’/adA’/ €
Deterministic and Non Deterministic
Grammar
 Non Deterministic Grammar
 A -> α β1 | α β2 | α β3

 On seeing α, you have three options……. Which one


to choose?

 A -> α A’
 A’ -> β1 | β2 | β3
Examples
 A->aSSbS | aSaSb | abb
|b
 A->aSSbS | aSaSb |
abb | b
Equivalent to
 S-> aS’ | b
 S’ -> SSbS | SaSb | bb
 S-> aS’ | b
 Again same prefixes…..  S’ -> SS’’ | bb
 S’’ -> SbS|aSb
 S’ -> SS’’ | bb
 S’’ -> SbS|aSb
Exercise
 S -> bSSaaS | bSSaSb | bSb | a

 A  bSA’ / a
 A’  SaaS / SaSb / Sb
 A’  SaA’’ /Sb
 A’’  aS/Sb

You might also like