0

Here is my token table:

TOKEN :
{
  < A : "A" >
| < B : "B" >
| < C : "C" >
}

I have this code that contains 2 choice conflicts.

void Start() : {} {
    < A> [ Bs() ] "-" < A>
}
void Bs() : {} {
    ( "-" < B> )+
}

In order to remove the choice conflicts warning, I need to add 2 LOOKAHEAD statements like so...

void Start() : {} {
    < A> [ LOOKAHEAD(2) Bs() ] "-" < A>
}
void Bs() : {} {
    ( LOOKAHEAD(1) "-" < B> )+
}

I understand why the first LOOKAHEAD(2) is needed but I have no idea why the second LOOKAHEAD(1) is needed. Can someone please explain?

Similarly for this example...

void Start() :{} {
    one()
    |
    two()
    |
    three()
    |
    four()
}
void one() : {} {
    [ <B> ] ( <A> )* <C>
}
void two() : {} {
    <B> <A> < A> <B>
}
void three() : {} {
    <B> <B> <A> [ <B> ] <A>
}
void four() : {} {
    <A> [ <B><C> ] two()
}

In order to remove the choice conflicts, I need to add LOOKAHEADS like so...

void Start() :{} {
    LOOKAHEAD(1) one()
    |
    LOOKAHEAD(1) two()
    |
    three()
    |
    four()
}
void one() : {} {
    [ <B> ] ( <A> )* <C>
}
void two() : {} {
    <B> <A> < A> <B>
}
void three() : {} {
    <B> <B> <A> [ <B> ] <A>
}
void four() : {} {
    <A> [ LOOKAHEAD(1) <B><C> ] two()
}

I have no idea why these LOOKAHEADS remove the warnings. Any help understanding would be appreciated.

Ogen
  • 6,499
  • 7
  • 58
  • 124

1 Answers1

2

For your first example, because of the way you defined Start, Bs can be followed by a "-" token. Now say the input is A - B - .... Should the ( "-" < B> )+ loop be executed once or twice? It depend on the next item of input. If it's an A, once, if it's a B, at least twice. So the parser needs to look past the "-".

For your second example: JavaCC does not give warnings when you put in LOOKAHEAD specifications, even if the LOOKAHEAD specifications are not sufficient to deal with the problem. In this case you could use

void Start() :{} {
    LOOKAHEAD([ <B> ] ( <A> )* <C>) one()
    |
    LOOKAHEAD(<B> <A>) two()
    |
    three()
    |
    four()
}
Theodore Norvell
  • 15,366
  • 6
  • 31
  • 45