'Syntax error recovery in ANTLR to produce valid parse tree

My simplified grammar is similar to the following:

parseExpression: expression EOF;
identifier: IDENT;
expression
    : identifier
    | identifier (+|-) identifier
    ;

When I try to parse an expression like abc +, a NoViableAlternativeException is thrown and ANTLR will recover by producing a ExpressionContext containing ErrorNode children.

I would like to recover from such a syntax error by ignoring the + token or by generating a synthetic token that is valid based on the expected tokens.

The error reporting will still be done through other means, but I need a valid parse tree that I can walk.

Any idea how this can be done in a custom ANTLRErrorListener or ANTLRErrorStrategy? I was trying to understand what happens in these classes when errors are encountered, but I couldn't figure out so far how to do this recovery.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source