简体   繁体   中英

compiler design - need help to eliminate indirect left recursion from a CFG

I have the following grammar which handles mathematical and logical expression:

A ==> B A'
A' ==> | B A'
A' ==> epsilon

B ==> C B'
B' ==> ^ C B'
B' ==> epsilon

C ==> D C'
C' ==> & D C'
C' ==> epsilon

D ==> E D'
D' ==> << E D' | >> E D'
D' ==> epsilon

E ==> F E'
E' ==> + F E' | - F E'
E' ==> epsilon

F ==> G F'
F' ==> * G F' | / G F' | % G F'
F' ==> epsilon

G ==> +H | -H | ++H | --H | ~H | !H | &H 
G ==> H

H ==> (A) | A T
T ==> -- | ++ | epsilon
H ==> number

The problem occurs when the following derivation happens:

A ==> B ==> C ==> D ==> E ==> F ==> G ==> H ==> A

And JavaCC won't compile the grammar file because of indirect left recursion .

So what steps should be done to eliminate this indirect left recursion from the previous grammar ?

So after i stared at this grammar for about a half an hour i realized that in a special case:

H ==> A

And the same special case yields:

A ==> H

So i rephrased the grammar in such a way that first production rule for the non-terminal H cause left-recursion and the second production rule doesn't cause any left recursion , so here's how the grammar looks like:

H ==> A T
T ==> -- | ++ | epsilon
H ==> (A) | number

As previously said , we replace A with H in the first production rule:

H ==> H T
H ==> (A) | number
T ==> -- | ++ | epsilon

Now it's trivial to eliminate the left recursion , and here's how does the final grammar looks like:

H ==> (A)H' | number H'
H' ==> T H' | epsilon
T ==> -- | ++ | epsilon

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM