ANTLR Java 8, odd behavior parsing with `returnStatement` as start rule,

Viewed 45

(This came up in Expression parsing with ANTLR)

Using the Java8Parser from the ANTLR grammars repository.

If I try to parse return a.b.c(); using the returnStatement parser rule, I get an error on the ( and ), though it's clearly a valid return statement.

parse tree for return a.b.c();

If, however, I just wrap it in braces ({return a.b.c();}) and use the block rule as the start rule, everything parses just fine:

parse tree for {return a.b.c();}

My best guess is that ANTLR needs the extra character of lookahead to manage this, but that just doesn't "seem right".

Can anyone explain why the first fails, and the second succeeds?

1 Answers

Odd, I'd expect ANTLR to backtrack from ALT 2 and match ALT 3. Could very well be a bug.

If I swap ALT 2 and ALT 3:

methodInvocation_lfno_primary
    :   methodName '(' argumentList? ')'
    |   typeName '.' typeArguments? Identifier '(' argumentList? ')'       // ALT 2
    |   expressionName '.' typeArguments? Identifier '(' argumentList? ')' // ALT 3
    |   'super' '.' typeArguments? Identifier '(' argumentList? ')'
    |   typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')'
    ;

to get this:

methodInvocation_lfno_primary
    :   methodName '(' argumentList? ')'
    |   expressionName '.' typeArguments? Identifier '(' argumentList? ')'
    |   typeName '.' typeArguments? Identifier '(' argumentList? ')'
    |   'super' '.' typeArguments? Identifier '(' argumentList? ')'
    |   typeName '.' 'super' '.' typeArguments? Identifier '(' argumentList? ')'
    ;

it gets properly parsed:

enter image description here

(no idea if that causes something else to break though...).

Related