0
votes

I'm unsure how to finish the left recursion removal algorithm for this grammar.

S ::= a B | B S b | S a | S B A | b
B ::= S b A | B B | A S B | a
D ::= b a | S b
A ::= b S A | b | a b

Here is my working.

using the order S, B, D, A.

S ::= a B M | B S b M | b M
M ::= a M | B A M | ε

B ::= a B M b A | B S b M b A | b M b A | B B | A S B | a

B ::= a B M b A N | b M b A N | A S B b A N | a N
N ::= S b M N | B N | ε

How should I progress from here?

1

1 Answers

2
votes

From the Dragon Book.

Given the following rule:

A → Aα1 | ... | Aαm | β1 | ... | βn

where the βi are the non left-recursive right sides, write:

A → β1 A' | ... | βn A'
A' → α1 A' | ... | αm A' | ε

To remove all left-recursion, use this algorithm, assign a number to each non terminal, A1...An, and:

for(int i = 1; i <= n; i++)
    for(int j = 1; j < i; j++)
        foreach(Ai → Ajα && Aj → β1 | ... | βn)
            replace with Ai → β1α |... | βnα
   remove left recursion from Ai