Search code examples
javaccambiguity

JavaCC: apply LOOKAHEAD number to all choices in a single choice list


With JavaCC, I want to have a lookahead of 3 for all choices in a single choice list. That is, I could do:

LOOKAHEAD(3) A() | LOOKAHEAD(3) B | LOOKAHEAD(3) C

But I'd prefer to do something like:

LOOKAHEAD(3) ( (A) | B() | C() )

Looking in the examples/JavaGrammars/1.5/Java1.5.jj file in the JavaCC 5.0 examples/demos package, I see code* that's like:

( LOOKAHEAD(3) ( (A) | B() | C() ) )

However, that gets me the warning Encountered LOOKAHEAD(...) at a non-choice location. This will be ignored. and otherwise has no effect.

*: Specifically, the Modifiers rule, line 1104.


Solution

  • The way to do it is

    LOOKAHEAD(3) A() | LOOKAHEAD(3) B() | C()
    

    This means:

    if the next three tokens are compatible with A()
        A()
    else if the next three tokens are compatible with B()
        B()
    else if the next token is compatible with C()
        C()
    else error
    

    See the JavaCC lookahead tutorial.