0
votes

I have a grammar (antlr4) file with both lexer and parser rules. I have extended the generated *BaseListener class and overridden

public void visitErrorNode(@NotNull ErrorNode node) {}

method. Inside the method body I am trying to get the next possible parser rule (in this case I need to know that 'op' is the rule which is expected as next rule for the given input). visitErrorNode is the right method to get this or any other ways to get the desired information.

combined grammar:-

ratingCriteria        :   'rating' op NUMBER
op: '>' | '>=' | '<' ;

Input Text:

rating

actual error I got:

no viable alternative at input 'rating'
1

1 Answers

0
votes

If you don't yet have "The Definitive ANTLR 4 Reference" by Terence Parr, you should get it from The Pragmatic Bookshelf. It has an entire chapter that provides a great amount of detail on managing parser errors - much more so that I can provide here. (And, no, the fearless BDFL does not give me any kickbacks.)

The error you are getting is actually from the parser, not the parse tree walker (which fires on the BaseListener interface). You will need to extend the parser's BaseErrorListener to catch the error when it actually occurs. That will give you an instance of the parser at the point of the error. If memory serves, getRuleInvocationStack() will give you the symbols the parser was expecting.

   List<String> stack = ((Parser)recognizer).getRuleInvocationStack();
   Collections.reverse(stack);

Update: the Parser method getExpectedTokens() will give you the symbols forward.