antlr 有没有办法生成访问者代码(通用访问者) [英] antlr is there any way to generate the visitor code(generic visitor)

查看:33
本文介绍了antlr 有没有办法生成访问者代码(通用访问者)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望 CommonTree 有一个 visit(OurVisitorvisitor) 方法,但 CommonTree 不是一个生成的类.

We would like to have the CommonTree have a visit(OurVisitor visitor) method but CommonTree is not a generated class.

现在,我们有这个代码

    ANTLRStringStream stream = new ANTLRStringStream(sql);
    NoSqlLexer lexer = new NoSqlLexer(stream);
    CommonTokenStream tokenStream = new CommonTokenStream(lexer);
    NoSqlParser parser = new NoSqlParser(tokenStream);  
    CommonTree tree = (CommonTree) parser.statement().getTree();

我总是可以外部化遍历树,但在这种情况下,只调用 tree.visit(myVisitor) 并让它为树中的每个节点调用 OurVisitor.visitNode(Node node) 是很好的.有没有办法做到这一点?

I can always externalize walking the tree, but it is nice to just call tree.visit(myVisitor) in this case and have it call OurVisitor.visitNode(Node node) for each node in the tree. Is there a way to do this?

另外,如果我有 expr = exprType1 | 我期待一棵树出口类型2 |exprType3*,我会有一棵树有

Also, I was expecting a tree where if I had expr = exprType1 | exprtType2 | exprType3*, I would have a tree that had

ExprType1 exp1 = expr.getExprType1();
ExprType2 exp2 = expr.getExprType2();
List<ExprType3> exp3List = expr.getExprType3()

但是 CommonTree 不是这种情况.有办法吗?

but this is not the case with CommonTree. Is there a way to have that?

谢谢,院长

推荐答案

是的,您可以让 ANTLR 生成您自己的 AST 类(它必须扩展 ANTLR 的 Tree 类!),您可以在其中添加自定义方法.

Yes, you can let ANTLR produce your own AST class (which must extend ANTLR's Tree class!) in which you can add custom methods.

请参阅这篇 ANTLR Wiki 文章,尤其是段落使用自定义 AST 节点类型.

See this ANTLR Wiki article, especially the paragraph Using custom AST node types.

ANTLR 的下一个主要版本,第 4 版,将具有自动 AST 构造,使其易于行走/迭代它.

The next major release of ANTLR, version 4, will have automatic AST construction making it easy to walk/iterate over it.

这篇关于antlr 有没有办法生成访问者代码(通用访问者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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