使用Java遍历Antlr树
我有一个关于 Antlr 的问题,我正在用它构建一个简单的解析器,但我无法遍历树。我找到了很多在线教程,它们使用了 Parser 类的 getAst(); 函数。有人有这方面的经验吗?我感觉每个版本的执行方式都不同。
grammar SimpleCalc;
options
{
output=AST;
}
tokens {
PLUS = '+' ;
MINUS = '-' ;
MULT = '*' ;
DIV = '/' ;
SEMICOLON = ';';
EQUAL = '=';
COMMA = ',';
BRACKETL = '(';
BRACKETR = ')';
}
有人对如何以其他方式遍历树有任何想法或建议吗?
I have a question regarding Antlr, I am building a simple parser with it but I can't traverse the tree. I have found many online tutorials and they use a getAst();
function of the Parser class. Does anyone have any experience with this? I have the feeling that the way of doing this differs per version.
grammar SimpleCalc;
options
{
output=AST;
}
tokens {
PLUS = '+' ;
MINUS = '-' ;
MULT = '*' ;
DIV = '/' ;
SEMICOLON = ';';
EQUAL = '=';
COMMA = ',';
BRACKETL = '(';
BRACKETR = ')';
}
Anyone have any idea, or suggestions on how to traverse the tree in an alternative way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getAST()
是CommonAST
中的一个方法,用于 ANTLR v2.x。ANTLR v3.x 使用
CommonTree
代替。定义output=AST
时,所有解析器规则都会返回 的实例RuleReturnScope
其中有一个getTree()
方法,您可以使用该方法获取树。另请参阅之前的问答,其中显示了如何在解析某些输入后获取 AST:如何输出使用 ANTLR 构建的 AST?
getAST()
is a method fromCommonAST
which is used in ANTLR v2.x.ANTLR v3.x uses
CommonTree
instead. When definingoutput=AST
, all parser rules return an instance ofRuleReturnScope
which has agetTree()
method you can use the get the tree.Also see this previous Q&A that shows how the get hold of the AST after parsing some input: How to output the AST built using ANTLR?