简体   繁体   中英

Left recursion elimination

I have this grammar

S->S+S|SS|(S)|S*|a

I want to know how to eliminate the left recursion from this grammar because the S+S is really confusing...

Let's see if we can simplify the given grammar.

S -> S*|S+S|SS|(S)|a

We can write it as;

S -> S*|SQ|SS|B|a
Q -> +S
B -> (S)

Now, you can eliminate left recursion in familiar territory.

S  ->  BS'|aS'
S' ->  *S'|QS'|SS'|e
Q  ->  +S
B  ->  (S)

Note that e is epsilon/lambda.

We have removed the left recursion, so we no longer have need of Q and B.

S  ->  (S)S'|aS'
S' ->  *S'|+SS'|SS'|e

You'll find this useful when dealing with left recursion elimination .

My answer using theory from this reference

How to Eliminate Left recursion in Context-Free-Grammar.

S -->  S+S | SS | S*    |        a | (S)
      --------------            -------   
      Sα form                   β form    
      Left-Recursive-Rules      Non-Left-Recursive-Rules       

We can write like

S ---> Sα 1 | 2 | 3 | β 1 | β 2

Rules to convert in equivalent Non-recursive grammar:

S ---> β 1 | β 2
Z ---> α 1 | α 2 | α 3
Z ---> α 1 Z | α 2 Z | α 3 Z
S ---> β 1 Z | β 2 Z

Where

α 1 = +S
α 2 = S
α 3 = *

And β -productions not start starts with S :

β 1 = a
β 2 = (S)

Grammar without left-recursion:

Non- left recursive Productions S --> β n

S -->  a | (S)   

Introduce new variable Z with following productions: Z ---> α n and Z --> α n Z

Z --> +S | S | * 

and 

Z --> +SZ | SZ | *Z  

And new S productions: S --> β n Z

S -->  aZ | (S)Z     

Second form (answer)

Productions Z --> +S | S | * Z --> +S | S | * Z --> +S | S | * and Z --> +SZ | SZ | *Z Z --> +SZ | SZ | *Z Z --> +SZ | SZ | *Z can be combine as Z --> +SZ | SZ | *Z| ^ Z --> +SZ | SZ | *Z| ^ Z --> +SZ | SZ | *Z| ^ where ^ is null-symbol.

Z --> ^ use to remove Z from production rules.

So second answer :

S --> aZ | (S)Z S --> aZ | (S)Z and Z --> +SZ | SZ | *Z| ^ Z --> +SZ | SZ | *Z| ^

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