Left recursion elimination

一世执手 提交于 2019-12-02 08:35:30

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 | Sα2 | Sα3 | β1 | β2

Rules to convert in equivalent Non-recursive grammar:

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

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 --> αnZ

Z --> +S | S | * 

and 

Z --> +SZ | SZ | *Z  

And new S productions: S --> βnZ

S -->  aZ | (S)Z     

Second form (answer)

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

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

So second answer:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!