The example LabeledExpr.g4 in the book describes how to use the visitor classes for singletons. But if I want to visit a class which is a collection, how do I do it? e.g. for the grammar:
prog: stat+ ;
stat: expr NEWLINE # printExpr
;
The visitor function for print is shown as:
public Integer visitPrintExpr(LabeledExprParser.PrintExprContext ctx) {
Integer value = visit(ctx.expr()); // evaluate the expr child
System.out.println(value); // print the result
return 0; // return dummy value
}
What would be the corresponding visitor function for 'stat+', so that I can traverse the list of 'stat'?
The reason I am looking for this is, I may want to parse and store the entire object model in memory first, and then do several passes of visiting and analysis on it (instead of on-the-fly evaluating/printing as the book example shows).
A related question is, if I create some data structures within the grammar file (as shown in ActionExpr.g4 in the book), how do I access these data structures in the visitor functions? e.g. how can the Expr class created below be accessed in the visitor function?
stat [Expr e]
: expr NEWLINE # printExpr
{$e = new Expr($expr);}
;