更新不可变AST的最简单方法是什么? [英] What is the easiest way to update an immutable AST?
问题描述
在使用宏时,我已经到达要努力更新AST中满足特定条件的那些节点的程度(我一直在努力避免这样做).例如,假设我要更新每个节点:
While working with macros, I have reached the point (I have been trying hard to avoid it) where I need to update those nodes in the AST which hold certain condition. For instance, let's say I would like to update each node:
Literal(Constant(1))
的值:
Literal(Constant(2))
那些AST节点可以在表达式树中的任何位置,因此我不能使用临时模式匹配器.显然,我要做的最后一件事是编写一个能够覆盖所有编译器原语的完整模式匹配器.我一直在 API 但我的印象是,诸如 collect 和 traversable 族之类的方法不足以满足我的需求,因为它们将树视为线性事物,并且我想要整个更新的树.那么,是否有可能以一种聪明的方式更新不可变的表达式树?为什么标准API中不存在这种更新"操作?
Those AST nodes could be anywhere in the expression tree, so I cannot use an ad-hoc pattern matcher. Obviously, the last thing I would like to do is to code a full pattern matcher which is able to cover all the compiler primitives. I have been searching in the API but I have the impression that methods such as collect and the traversable family are not good enough to fulfill my needs, since they treat the tree as a linear thing, and I want the whole updated tree as a result. So, is it possible to update an immutable expression tree in a smart way? Why doesn't exist such 'update' operation in the standard API?
推荐答案
下面是在Scala宏中使用AST转换器的示例:
Here's an example of using an AST transformer in a Scala macro:
这篇关于更新不可变AST的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!