如何为集合编写访问者类? [英] How to write visitor classes for collections?

查看:28
本文介绍了如何为集合编写访问者类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

书中的示例 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
        ;

打印的visitor函数如下:

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类如何在visitor函数中访问?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆