Left Recursion and Left Factoring - 2024
Left Recursion and Left Factoring - 2024
Dr. R Guru
Associate Professor
Dept. of Computer Science and Engineering,
SJCE, JSSSTU, Mysuru
Writing Grammar
• Eliminating Ambiguity
• Eliminating of Left recursion
• Eliminating Left Factoring
Eliminating Ambiguity
• Ambiguous Grammar : A Grammar that produces more than
two parse tree for some sentence is said to be ambiguous.
• Ex:1 Consider the grammar EE + E│E * E│id
with A A'
A' A' │ .
• Suppose there are many number of production
A A1│A2│….. │Am│1│2│….. │ n
ETE’
E’ + TE’│Є
T FT’
T’ * FT’│ Є
F id│(E)
Examples:1
S Aa│b
A Ac│Sd │e
Examples:2
A BC│a
S CA│Ab
A AB│CC│a
Left factoring
• Left factoring is a grammar transformation that is useful for
producing a grammar suitable for predictive or top-down
parsing.
• Consider following grammar:
Stmt if expr stmt else stmt
| if expr stmt
• On seeing input if it is not clear for the parser which
production to use
• We can easily perform left factoring:
– If we have A αβ1 │ αβ2 then we replace it with
A αA’
A’ β1 │ β2
Left factoring elimination algorithm:
Input : Grammar G
Output: An equivalent left factored grammar.
Method
– For each non-terminal A, find the longest prefix α common
to two or more of its alternatives. If α≠ ɛ, then replace all
of A-productions
A αβ1 │ αβ2 │ … │ αβn │ γ
by
A αA’ │ γ
A’ β1 │ β2 │ … │ βn
Example:1
S iEtS│iEtSeS│ a
E b
Example:2
• S bSSaaS │ bSSaSb │ bSb │ a