结合使用antlr和DLR——AST转换

发布于 2024-08-22 15:08:01 字数 112 浏览 14 评论 0原文

我有一个通过 ANTLR 生成的 AST,我需要将其转换为与 DLR 兼容的 AST(表达式树)。但是,我似乎无法为此使用树模式匹配器,因为表达式树在实例化时需要其子树(我无法获得)。什么解决方案最适合我使用?

I have an AST generated via ANTLR, and I need to convert it to a DLR-compatible one (Expression Trees). However, it would seem that i can't use tree pattern matchers for this as expression trees need their subtrees at instantiation (which i can't get). What solution would be best for me to use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

ㄟ。诗瑗 2024-08-29 15:08:01

几年前我做了一些非常类似的事情 - 我没有构建 DLR 结构,但我构建了自己的表达式树结构,该结构在构建时也需要参数(以实现不变性)。

当时,我使用 ANTLR v2 - 我必须承认,我不熟悉新的 v3 语法,而且我不记得当时我是如何做的每一个细节 - 所以而不是为您提供完整的举个例子,我只是尝试告诉你我的故事(不确定,是否也适用于你的问题!):

首先,没有必要构建我的结构来自 AST。我只使用 ANLTR 的 AST 构建器作为工具:每个 AST 构建规则除了 AST 节点本身之外还可以返回一个对象。然后,返回值可以在外部规则中用作构造函数的参数,等等。因此,该结构会自动为您构建自下而上!

IOW,你在构建 AST 的同时构建了最终的结构(构建 AST 只是为了确保语法规则,可以扔掉。)这种方法非常可靠,甚至比第一次构建 AST 还要快,然后对其进行改造!但它仍然利用 AST 解析器的强大功能(而不是仅使用普通的解析器/词法分析器)。如果您也需要 AST - 只需将其保存在某个地方即可。

然而,如果您想遍历完成的 AST - 我想您可以使用任何编程例程来做到这一点 - 只要确保它自下而上地构建您的结果即可!

希望这能在某种程度上有所帮助!

I did something very similar some years ago - I didn't build a DLR structure, but I built my own expression tree structure, which also needed the arguments at construction time (to achieve immutability).

Back then, I worked with ANTLR v2 - and I must admit, that I'm not familiar with the new v3 syntax, plus I don't remember every detail about how I did it back then - so instead of providing you with a fully worked out example, I'll just try to tell you my story (not sure, if it applies to your problem, too!):

First of all, it wasn't necessary to build my structure from the AST. I only used ANLTR's AST builder as a vehicle: Every AST building rule can return an Object in addition to the AST node itself. The return value can then be used in the outer rule as an argument for the constructor, and so on. So that structure is automatically built bottom up for you!

IOW, you build the final structure at the same time that the AST is built (the AST is only built to ensure the syntax rules, and can be thrown away.) This approach is very solid, and it's even faster than first building the AST, and then transforming that! But it still utilizes the power of the AST parser (as opposed to just using the normal Parser/Lexer alone). And if you need the AST, too - just save it somewhere.

If, however you want to walk a finished AST - I imagine you can use any programmatic routine to do that - just make sure, that it works bottom up to construct your result!

Hope this helps in some way!

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