Search code examples
javaantlrgrammarantlr3antlrworks

Finding Next Expected token If error occures ANTLR 3


I am using ANTLR 3 , I have a question is that How can i find the next expected token if any error is occurred in input . I have tried to override getErrorMessage(RecognitionException e, String[] tokenNames) of the Parser, I can get the error but i am not able to get What is next expected token . If anyone can help . Thanks in Advance.


Solution

  • That's not as easy as it sounds. And quite often, such information is not available.

    For example, your grammar can match parenthesized expressions like this: (1+2).

    If your parser now tries to parse "(1+2", a MismatchedTokenException would be thrown, whose expecting attribute would be the type of ')'. So, that's an easy one.

    However, when it tries to parse "1+2)", a MismatchedTokenException would again be thrown, but now the parser would complain that it expects the EOF, because it expects to just parse an expression like 1+2. It will not tell you that somewhere in the "past", you forgot an '('.

    So, there will only be a couple of occasions that will let you extract an expected token from an exception raised by the parser. In the bulk of the cases, you will need to do (a lot of hard) work to extract this info yourself. Creating meaningful error messages in your parser is not a trivial task! (at least, not compared to simply writing a grammar for a not too complicated language)

    I recommend going through ANTLR's API docs to see which exceptions are being thrown by ANTLR and feed your parser invalid input by purpose, and overriding reportError(...) in your parser to see which exception gets thrown:

    @parser::members {
    
      @Override
      public void reportError(RecognitionException e) {
        // inspect 'e' and handle/report it
      }
    }