如何为集合编写访问者类? [英] How to write visitor classes for collections?
问题描述
本书中的示例LabeledExpr.g4描述了如何将访问者类用于单例.但是,如果我想参观一个属于收藏的课程,该怎么办?例如语法:
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
}
"stat +"对应的访问者函数是什么,以便我可以遍历"stat"列表?
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).
一个相关的问题是,如果我在语法文件中创建了一些数据结构(如书中的ActionExpr.g4所示),如何在访问者函数中访问这些数据结构?例如如何在访问者函数中访问下面创建的Expr类?
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);}
;
推荐答案
所生成的ProgContext.stat()
方法返回完整的集合.您可以从访问者的visitProg
方法中访问它.
The complete collection is returned by the generated ProgContext.stat()
method. You can access it from within the visitProg
method of the visitor.
这篇关于如何为集合编写访问者类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!