Currenlty I'm working on my own grammar and I would like to have specific error messages on NoViableAlternative
, InputMismatch
, UnwantedToken
, MissingToken
and LexerNoViableAltException
.
I already extended the Lexer.class
and have overridden the notifyListeners
to change the default error message token recognition error at:
to my own one. As well I extended the DefaultErrorStrategy
and have overridden all report methods, like reportNoViableAlternative
, reportInputMismatch
, reportUnwantedToken
, reportMissingToken
.
The purpose of all that is to change the messages, which will be passed to the syntaxError()
method of the listener ANTLRErrorListener
.
Here's a small example of the extended Lexer.class
:
@Override
public void notifyListeners(LexerNoViableAltException lexerNoViableAltException) {
String text = this._input.getText(Interval.of(this._tokenStartCharIndex, this._input.index()));
String msg = "Operator " + this.getErrorDisplay(text) + " is unkown.";
ANTLRErrorListener listener = this.getErrorListenerDispatch();
listener.syntaxError(this, null, this._tokenStartLine, this._tokenStartCharPositionInLine, msg,
lexerNoViableAltException);
}
Or for the DefaultErrorStrategy
:
@Override
protected void reportNoViableAlternative(Parser recognizer, NoViableAltException noViableAltException) {
TokenStream tokens = recognizer.getInputStream();
String input;
if (tokens != null) {
if (noViableAltException.getStartToken().getType() == -1) {
input = "<EOF>";
} else {
input = tokens.getText(noViableAltException.getStartToken(), noViableAltException.getOffendingToken());
}
} else {
input = "<unknown input>";
}
String msg = "Invalid operation " + input + ".";
recognizer.notifyErrorListeners(noViableAltException.getOffendingToken(), msg, noViableAltException);
}
So I read this thread Handling errors in ANTLR4 and was wondering if there's no easier solution when it comes to the point of customising?