简体   繁体   中英

Difference between: 'Eliminate left-recursion' and 'construct an equivalent unambiguous grammar'

For example:

R → R bar R|RR|R star|(R)|a|b

construct an equivalent unambiguous grammar:

R → S|RbarS S→T|ST
T → U|Tstar U→a|b|(R)

How about Eliminate left-recursion for R → R bar R|RR|R star|(R)|a|b ?

What's the different between Eliminate left-recursion and construct an equivalent unambiguous grammar ?

An unambiguous grammar is one where for each string in the language, there is exactly one way to derive it from the grammar. In the context of compiler construction the problem with ambiguous grammar is that it's not obvious from the grammar what the parse tree for a given input string should be. Some tools solve this using their rules for resolving ambiguities while other simply require the grammar to be unambiguous.

A left-recursive grammar is one where the derivation for a given non-terminal can produce that same non-terminal again without first producing a terminal. This leads to infinite loops in recursive-descent-style parsers, but is no problems for shift-reduce parsers.

Note that an unambiguous grammar can still be left-recursive and a grammar without left recursion can still be ambiguous. Also note that depending on your tools, you may need to only remove ambiguity, but not left-recursion, or you may need to remove left-recursion, but not ambiguity (though an unambiguous grammar is generally preferable).

So the difference is that eliminating left recursion and ambiguity solve different problems and are necessary in different situation.

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