How to write visitor classes for collections?

僤鯓⒐⒋嵵緔 提交于 2019-12-08 10:05:06

问题


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);}
      ;

回答1:


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



来源:https://stackoverflow.com/questions/20121533/how-to-write-visitor-classes-for-collections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!