问题
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