Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining whether string complies with ANTLR4 grammar

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.

like image 859
Brad Mace Avatar asked Feb 02 '26 04:02

Brad Mace


1 Answers

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);
like image 172
Sam Harwell Avatar answered Feb 04 '26 18:02

Sam Harwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!