ANTLR4 - Access token group in a sequence using context

265 views Asked by At

I have a grammar that includes this rule:

expr:
      unaryExpr '(' (stat | expr | constant) ')'                                        #labelUnaryExpr
    | binaryExpr '(' (stat | expr | constant) ',' (stat | expr | constant) ')'          #labelBinaryExpr
    | multipleExpr '(' (stat | expr | constant) (',' (stat | expr | constant))+ ')'     #labelMultipleExpr
    ;       

For expr, I can access the value of unaryExpr by calling ctx.unaryStat(). How can I access (stat | expr | constant) similarly? Is there a solution that doesn't require modifying my grammar by adding another rule for the group?

1

There are 1 answers

0
Bart Kiers On BEST ANSWER

Since you've labelled you alternatives, you can access the (stat | expr | constant) in its respective listener/visitor method:

@Override
public void enterLabelUnaryExpr(@NotNull ExprParser.LabelUnaryExprContext ctx) {

  // one of these will return something other than null
  System.out.println(ctx.stat());
  System.out.println(ctx.expr());
  System.out.println(ctx.constant());
}