clang
is its specific and helpful error messages.The following algorithm will eliminate immediate & non-immediate left-recursive productions.
arrange the nonterminals in some order A1, A2, ..., An
for i ← 1 to n do {
for j ← 1 to i-1 do {
replace each production of the form Ai → Aj γ by
Ai → δ1 γ | δ2 γ | ... | δk γ, where
Aj → δ1 | δ2 | ... | δk are all current Aj-productions
}
eliminate immediate left-recursion among the Ai-productions
}
Given the grammar
S → A a | b
A → A c | S d | ε
we may order the nonterminals as S, A and apply the algorithm above. When i = 1, nothing happens. When i = 2, we substitute for S in A → S d to obtain the following A-productions
A → A c | A a d | b d | ε
Eliminating the immediate left-recursion for the A-productions gives the grammar
S → A a | b
A → b d A' | A'
A' → c A' | a d A' | ε
Exercise. Redo this example with the ordering A, S.
The grammar
S → i E t S | i E t S e S | a
E → b
can be left-factered to
S → i E t S S' | a
S' → e S | ε
E → b