I'm new to ANTLR. I just discovered that it is possible to label each alternative in a production like so:
foo
: a # aLabel
| b # bLabel
| // ...
;
However, I find it unpleasant that all or none alternatives must be labeled. I needed to label just 2 alternatives of a production with 20+ branches recently, and I ended up labelling each of the others # stubLabel
. Is there any reason why all or none have to be labeled?
As soon as you add a label ANTLR4 will no longer generate a context class for that rule but instead individual context classes for each alt. This cannot be mixed (e.g. having a context for the entire rule and at the same time contexts for only some of the alts). Once you start using labels and the rule context is no longer generated you have to generate contexts for all alts or something would be missing.
OK, I believe I've figured this out. Presumably to save space, the node corresponding to each label is subclassed from the node corresponding to the production, rather than being a child of it.
expression
: // ...
| foo # namedMethodInvocation
;
becomes