Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a particular ANTLR4 error recovery strategy?

Tags:

antlr4

In one context my grammar allows ... ID = expr; or ... ID = expr(expr [,expr]*);, i.e. expressions and function calls with a terminating semicolon. When there is an error in the argument list ANTLR decides the easiest solution is to replace the open parenthesis with a semicolon. That does match the rule, but then the rest of the input looks like garbage. The subsequent parse errors are misleading.

In this context I think it's the wrong way to recover. The odds are very good that the error is in the argument list, not a typo of ( for ;. I would like to tell ANTLR if it finds an open parenthesis there it has to consume it, not replace it. Then (in my dream) ANTLR will correctly diagnose the problem with the inner expression.

I read the book and tried some experiments, but none of them solved this problem. I tried making the lexer state-dependent, e.g. distinguishing top level from internal semicolons. The problem is, if ANTLR is willing to create a token it doesn't matter what the lexer produces.

like image 565
John F. Carr Avatar asked Dec 02 '25 11:12

John F. Carr


1 Answers

To provide non-default error handling, implement your own ANTLRErrorStrategy. Then use Parser.setErrorHandler(new YourErrorStrategy()) to add it.

Look at DefaultErrorStrategy in the same directory for a working definition of the methods.

like image 81
GRosenberg Avatar answered Dec 06 '25 10:12

GRosenberg



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!