antlr is there any way to generate the visitor code(generic visitor)

南楼画角 提交于 2019-12-11 11:47:01

问题


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

Right now, we have this code

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

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?

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()

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

thanks, Dean


回答1:


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

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

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



来源:https://stackoverflow.com/questions/11364723/antlr-is-there-any-way-to-generate-the-visitor-codegeneric-visitor

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