Left Recursion and Left Factoring - 2023
Left Recursion and Left Factoring - 2023
Dr. R Guru
Associate Professor
Dept. of Computer Science and Engineering,
SJCE, JSSSTU, Mysuru
Left recursion
• A grammar is left recursive if it has a non terminal A such that
there is derivation
A + A for some string
• Top down parsing methods cannot handle left-recursive grammars
so a transformation is needed to eliminate 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' │ .
• 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