Jan Pierry
Jan Pierry

Reputation: 85

Is there a way to force JavaCC to accept ambiguous non-LL(1) grammar?

I'm trying to create a didactic parser in JavaCC to explain the use of lookahead for my homework. I was thinking about creating a ambiguous grammar on porpose to show the behavior of the parser in such situation. My grammar is below:

void s() : 
{}
{
    "a" ( bc() | bd() ) <EOF>   
}

void bc() :
{}
{
    "b" "c"
}

void bd() :
{}
{
    "b" "d"
}

Reading the JavaCC Tutorials about lookahead I understood that, in the parser creating, a warning about use of lookahead will be shown (Ok) and if ignored the parser will still work but choosing always the first option. I supposed the last part because the tutorial says "The generated parser will still work using the default lookahead algorithm, but it may not do what you expect of it."

However, when I try to create the parser this error is shown:

$ javac *.java
ExampleABCD.java:18: error: unreachable statement
        }{
         ^
1 error

And the cause is:

case 6:{
        bc();
        break;
        }{        //Here
        bd();
        break;
        }

I expected to the parser work but not properly. Shouldn't it be like that? If this error is expected, is there a way to make it work even with this ambiguous grammar?

note: I don't want to use lookahead yet, my goal is to use it later when I will explain how it can solve the problem.

Upvotes: 0

Views: 144

Answers (1)

Theodore Norvell
Theodore Norvell

Reputation: 16221

Now JavaCC has no issue with this. It produces warnings and .java code that correctly reflects the .jj file. The problem is that your Java compiler does not like unreachable code.

See Is there a way to ignore the 'Unreachable statement' error?

What you can do is this

void s() : 
{}
{
    "a" ( LOOKAHEAD({true})  // TODO fix the lookahead
          bc()
        | 
          bd() )
    <EOF>   
}

Upvotes: 2

Related Questions