使用Java遍历Antlr树

发布于 2024-12-27 02:04:05 字数 408 浏览 4 评论 0原文

我有一个关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

煮酒 2025-01-03 02:04:05

getAST()CommonAST 中的一个方法,用于 ANTLR v2.x。

ANTLR v3.x 使用 CommonTree 代替。定义 output=AST 时,所有解析器规则都会返回 的实例RuleReturnScope 其中有一个 getTree() 方法,您可以使用该方法获取树。

另请参阅之前的问答,其中显示了如何在解析某些输入后获取 AST:如何输出使用 ANTLR 构建的 AST?

getAST() is a method from CommonAST which is used in ANTLR v2.x.

ANTLR v3.x uses CommonTree instead. When defining output=AST, all parser rules return an instance of RuleReturnScope which has a getTree() 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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文