elimination of indirect left recursion

给你一囗甜甜゛ 提交于 2020-01-06 06:06:34

问题


I'm having problems understanding an online explanation of how to remove the left recursion in this grammar. I know how to remove direct recursion, but I'm not clear how to handle the indirect. Could anyone explain it?

A --> B x y | x 
B --> C D
C --> A | c
D --> d

回答1:


The way I learned to do this is to replace one of the offending non-terminal symbols with each of its expansions. In this case, we first replace B with its expansions:

A --> B x y | x
B --> C D

becomes

A --> C x y | D x y | x

Now, we do the same for non-terminal symbol C:

A --> C x y | D x y | x
C --> A | c

becomes

A --> A x y | c x y | D x y | x

The only other remaining grammar rule is

D --> d

so you can also make that replacement, leaving your entire grammar as

A --> A x y | c x y | d x y | x

There is no indirect left recursion now, since there is nothing indirect at all.

Also see here.


To eliminate left recursion altogether (not merely indirect left recursion), introduce the A' symbol from your own materials (credit to OP for this clarification and completion):

A -> x A' 
A' -> xyA' | cxyA' | dxyA' | epsilon

Response to naomik's comments

Yes, grammars have interesting properties, and you can characterize certain semantic capabilities in terms of constraints on grammar rules. There are transformation algorithms to handle certain types of parsing problems.

In this case, we want to remove left-recursion: one desirable property of a grammar is that the use of any rule must consume at least one input token (terminal symbol). Left-recursion opens a door to infinite recursion in the parser.

I learned these things in my "Foundations of Computing" and "Compiler Construction" classes many years ago. Instead of writing a parser to adapt to a particular grammar, we'd transform the grammar to fit the parser style we wanted.



来源:https://stackoverflow.com/questions/46085501/elimination-of-indirect-left-recursion

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