Question

I am feeling quite nostalgic so I've decided to write an adventure game creator that allows complex sentences to be entered by the user.

I have hand rolled a lexer and parser that uses the visitor pattern and it works quite well, until I encountered a left-recursion issue with one of my BNF (Backus-Naur Form) rules:

object          ::= {adjective} noun 
                  | object AND {adjective} noun 

After removing the left-recursion by following this wiki entry does this look right?

object      ::= {adjective} noun object2
object2     ::= AND {adjective noun} 
              | !Empty

Edited:

I am hand rolling the lexer and parser using C# by following the guide given here. I an not using any parser generators for this exercise.

Also, I got the BNF rules for the parser from this website.

Était-ce utile?

La solution

Is there any reason to prefer left-recursion over right recursion in this case? Wouldn't this be simpler:

object ::= {adjective} noun |
           {adjective} noun AND object

If you really want to make your solution work, you need to make object2 right-recursive:

object      ::= {adjective} noun object2
object2     ::= AND {adjective noun} object2 |
                !Empty

Autres conseils

Usually when I have this rule (yours):

object          ::= {adjective} noun | 
                    object AND {adjective} noun 

I apply the following transformations:

Stage 1 (still left recursion) -

object          ::= ad_noun | 
                    object AND ad_noun

ad_noun         ::=  {adjective} noun 

Stage 2 (change to right recursion) -

object          ::= ad_noun | 
                    ad_noun AND object

ad_noun         ::=  {adjective} noun 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top