JavaCC get ParseException error when lookahead > 0

265 views Asked by At

I'm getting this error when I try to make a simple parser. The parser should be accepting (01|10|00|11)*(00|11). When I use lookahead = 0, 00100100 will trigger an error, even though its a correct input. Because JavaCC read it as 00 1 00 1 00, not 00 10 01 00. But when I add lookahead to fix it, I got

Exception in thread "main" ParseException: Encountered "" at line 1, column 6.
Was expecting one of:

    at GS.generateParseException(GS.java:453)
    at GS.jj_consume_token(GS.java:337)
    at GS.q3(GS.java:50)
    at GS.q0(GS.java:17)
    at GS.q1(GS.java:32)
    at GS.q0(GS.java:14)
    at GS.q3(GS.java:43)
    at GS.q0(GS.java:17)
    at GS.main(GS.java:8)

Can anyone help me to find the cause? Any help would be much appreciated. Thanks

options{
    LOOKAHEAD = 4;
}

PARSER_BEGIN(GS)
public class GS {
    public static void main(String args[]) throws ParseException {
        GS parser = new GS(System.in);
        parser.q0();
    }
}
PARSER_END(GS)

TOKEN:
{
    <END : (["\n", "\r", "\t"])+>
}


void q0():{}
{
    "1" q1() | "0" q2() | "00" q3() | "11" q3()
}

void q1():{}
{
    "0" q0()
}

void q2():{}
{
    "1" q0()
}

void q3():{}
{
    q0() | <END>
}
1

There are 1 answers

0
Joël V. On

I think that writing

void q3():{}
{
    <END> |q0()
}

instead of

void q3():{}
{
    q0() | <END>
}

may fix the problem : if you inline q3, you can see that q0 is left recursive, so you need an infinite look-ahead to choose the alternative production. Putting END first will give it a higher priority, and the production will become right recursive.