Reputation: 27916
How can I test a string against my grammar just to see whether it's valid (i.e. that no errors were found, and no error recovery was necessary)?
I've tried this as well as a custom error strategy but I'm still getting messages like
line 1:2 token recognition error at: 'x'
on the console. So I need either a way to ensure all errors result in exceptions, or a way to validate input that doesn't rely on exceptions.
Upvotes: 3
Views: 2768
Reputation: 456
A quick and dirty solution...
Parser p = new MyParser(myTokenStream);
p.rootRule();
if (p.getNumberOfSyntaxErrors() > 0) {
throw new RuntimeException("Syntax error!");
}
This won't help you if there are lexical errors which don't cause the parser to get confused (e.g. extraneous input) because the number of syntax errors will still be zero.
This is a good solution if you don't want to mess around with the ErrorListeners and you don't care about certain lexer errors which the parser can get around.
Upvotes: 1
Reputation: 100029
Edit: What you are seeing is a lexer error, not a parser error. You need to update your lexer to ensure the lexer is incapable of failing to match an input character by adding the following as the last rule of your lexer. This will pass the erroneous character on to the parser for handling (reporting, recovery, etc.).
ERR_CHAR : . ;
In addition to this, you need to perform the general steps below which apply to configuring the parser for simple string recognition.
You need to do two things for this to work properly:
First, disable the default error reporting mechanism(s).
parser.removeErrorListeners();
Second, disable the default error recovery mechanism(s).
parser.setErrorStrategy(new BailErrorStrategy());
You'll get a ParseCancellationException
, and no other reporting, if your string does not match.
If you aren't using the output from the parse operation, you may also wish to improve the efficiency of the recognition process by disabling parse tree construction.
parser.setBuildParseTree(false);
Upvotes: 7