Is there a way to easily adapt the error messages of ANTLR4?

后端 未结 2 877
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 20:00

Currenlty I\'m working on my own grammar and I would like to have specific error messages on NoViableAlternative, InputMismatch, UnwantedToke

2条回答
  •  执念已碎
    2020-12-10 20:57

    After some research I came up with an another solution. In the book "The Definitive ANTLR4 Reference" in Chapter 9.4 they explain how to use error alternatives:

    fcall
    : ID '(' expr ')'
    | ID '(' expr ')' ')' {notifyErrorListeners("Too many parentheses");}
    | ID '(' expr         {notifyErrorListeners("Missing closing ')'");}
    ;
    

    These error alternatives can make an ANTLR-generated parser work a little harder to choose between alternatives, but they don't in any way confuse the parser.

    I adapted this to my grammar and extended the BaseErrorListener. The passed Exception to the notifyErrorListener are null (from Parser.class):

    public final void notifyErrorListeners(String msg) {
        this.notifyErrorListeners(this.getCurrentToken(), msg, (RecognitionException)null);
    }
    

    So handled it in the extension of BaseErrorListener, like that:

    if (recognitionException instanceof LexerNoViableAltException) {
        message = handleLexerNoViableAltException((Lexer) recognizer);
    } else if (recognitionException instanceof InputMismatchException) {
        message = handleInputMismatchException((CommonToken) offendingSymbol);
    } else if (recognitionException instanceof NoViableAltException) {
        message = handleNoViableAltException((CommonToken) offendingSymbol);
    } else if (Objects.isNull(recognitionException)) {
    // Handle Errors specified in my grammar
        message = msg;
    } else {
        message = "Can't be resolved";
    }
    

    I hope that helps a little bit

提交回复
热议问题