基于 ANTLR 的翻译器的结构(最佳实践)
我想使用 ANTLR 编写一个从 DSL 到 Java 的转换器。因此,我使用两种不同的语法编写了词法分析器和解析器。现在我必须编写树语法,我想知道哪些是获得结果的最佳实践(或推荐实践)。更准确地说,我想知道哪些是执行以下操作的最佳方法:使用属性(例如,添加类型)和优化来丰富树。
我是否应该编写不同的树语法来识别类型和优化,然后在解析器之后和最终代码生成树语法之前串行调用 then ?还有其他更容易维护的方法吗?我还考虑手动解析解析器生成的树以识别类型。但这是相当值得维护的。
感谢您。
I want to write a translator from a DSL to Java using ANTLR. So, I wrote the lexer and the parser using two different grammars. Now I have to write the tree grammar and I want to know which are the best practices (or recommended practices) for obtaining my result. More exactly, I would like to know which are the best ways to do stuff like: enrich the tree with attributes (for example, adding types) and optimizations.
Should I write different tree grammars for identifying types and for optimizations and then call then serially after the parser and before the final code generation tree grammar? Is there another way which is easier to maintain? I also though about manually parsing the tree generated by the parser in order to identify the types. But this is quite to maintain.
Thanks you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有真正的最佳实践:只有常识和个人偏好。
然而,将向节点添加某些属性与优化操作(将
^(* 0 ^(...))
重写为0
)分开是更合乎逻辑的。跳过 AST。不要太担心性能:树行走非常快:大部分时间通常花在解析期间。 ANTLR 3.2 添加了树模式匹配,您可以编写非常小的树语法来对 AST 执行非常具体的操作(易于维护!)。另请参阅之前的问答,其中涉及手动遍历 AST 或使用树语法:
生成 ANTLR 树语法的系统方法?
There are no real best practices: just common sense and personal preference.
However, it is more logical to separate the adding of certain attributes to nodes from optimization actions (rewrite
^(* 0 ^(...))
to0
) in separate passes over the AST. Don't worry too much about performance: tree walking is pretty fast: most of the time is usually spent during parsing. And with ANTLR 3.2's addition of tree pattern matching, you can write pretty small tree grammars to perform a very specific operation on your AST (easy to maintain!).Also see this previous Q&A that is about manually walking the AST or using a tree grammar for it:
Systematic way to generate ANTLR tree grammar?