antlr有什么方法可以生成访客代码(通用访客) [英] antlr is there any way to generate the visitor code(generic visitor)

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

问题描述

我们希望CommonTree拥有一个visit(OurVisitor visitor)方法,但是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 | exprtType2 | 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天全站免登陆