Search code examples
compiler-constructionantlr4

EOF behaviour in ANTLR4


For given input:

hello hello

And grammar:

grammar test;

foo: bar ;
bar   : 'hello' bar | EOF;

WS  : [ \t\r\n]+ -> skip ;

I get a valid parse tree for rule bar.

But when I remove foo rule:

grammar test;

bar   : 'hello' bar | EOF;

WS  : [ \t\r\n]+ -> skip ;

I get an error "line 1:11 no viable alternative at input '< EOF>". What is going on here? I am using intellij plugin for ANTLR4 for rule testing.


Solution

  • As confirmed by the co-author of ANTLR4 Sam Harwell, it is bug in ANTLR4. It can be tracked here: https://github.com/antlr/antlr4/issues/118

    Workaround is as suggested in the question (use extra root rule foo).