Why does ANTLR generate an if-then-else for an optional subrule where the else-clause tests for what follows the subrule?

Terence Parr

Summary: ANTLR tries to detect errors as soon as possible.

To make the question more concrete, look at this grammar fragment:

r : (A)? B ;
For the optional subrule and B reference, ANTLR generates something like:
if ( LA(1)==A ) {
else if ( LA(1)==B ) {
else {

Why does generate the first else-clause? If B doesn't exist following the A, the final match(B) will catch the error. The answer is that one of ANTLR's design principles is to catch errors as soon as possible.  This simple case  makes the extra LA(1)==B test look stupid, but the sooner you detect errors, the better able you are to generate an intelligent error message (better context) and attempt recovery. If you delay error detection until the last possible moment, you might burrow down into 20 more rules before generating an error message. Typically, this will be a very low level rule (such as rule literal vs rule expr) and you will have much less context information. I can't think of a great example at the moment, sorry.