Consider:
my_rule: a_thing 'as' zoot
| a_different_thing 'as' blurfl zoot
;
In my listener, how do I distinguish the particular production that was matched? Am I reduced to checking for the presence of blurfl, or is there a more elegant way?
Label the alternatives like this:
grammar T;
my_rule
: a_thing 'as' zoot #AltWithoutBlurfl
| a_different_thing 'as' blurfl zoot #AltWithBlurfl
;
...
That way, your listener will contain methods like these:
public interface TListener extends ParseTreeListener {
void enterAltWithoutBlurfl(TParser.AltWithoutBlurflContext ctx);
void exitAltWithoutBlurfl(TParser.AltWithoutBlurflContext ctx);
void enterAltWithBlurfl(TParser.AltWithBlurflContext ctx);
void exitAltWithBlurfl(TParser.AltWithBlurflContext ctx);
...
}
Note that there is no more enterMy_rule
and exitMy_rule
anymore.