0

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);}
      ;
R71
  • 4,283
  • 7
  • 32
  • 60

1 Answers1

0

The complete collection is returned by the generated ProgContext.stat() method. You can access it from within the visitProg method of the visitor.

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
  • Thanks. But now I have a different problem - the code works in eclipse, but not in command line (neither windows, nor unix). I have posted a different question for that because it looks like a bug of some sort - 20138858. – R71 Nov 22 '13 at 06:56