简体   繁体   中英

elimination of indirect left recursion

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

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.

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