I\'m using ANTLR to parse logical expressions in a Java tool I\'m writing, and I\'m having issues because passing invalid input strings to the generated ANTLR lexer and pars
An easy fix would be to override your lexer's and parser's reportError(...)
and throw an exception of your own instead of letting ANTLR trying to recover from the incorrect syntax/input:
grammar YourGrammar;
// options/header/tokens
@parser::members {
@Override
public void reportError(RecognitionException e) {
throw new RuntimeException("I quit!\n" + e.getMessage());
}
}
@lexer::members {
@Override
public void reportError(RecognitionException e) {
throw new RuntimeException("I quit!\n" + e.getMessage());
}
}
// lexer & parser rules
More on error reporting (and recovery): https://theantlrguy.atlassian.net/wiki/display/ANTLR3/Error+reporting+and+recovery
You should use an error listener as suggested in this answer
However, for a quick migration from antlr3 to antlr4 / antlr v4, you could use this as your grammer:
@parser::members
{
private final Logger log = LogManager.getLogger(this.getClass().getName());
public java.util.HashMap<String, Double> memory = new java.util.HashMap<String, Double>();
@Override
public void notifyErrorListeners(Token offendingToken, String msg, RecognitionException ex)
{
throw new RuntimeException(msg);
}
}
@lexer::members
{
@Override
public void recover(RecognitionException ex)
{
throw new RuntimeException(ex.getMessage());
}
}