访客节点不适合被访客替换?
在我的小型编译器中,我目前有一个手工制作的 AST。
我正在考虑让访问者照顾某种类型 X
的节点,并用 X'
类型的节点替换它们。问题在于,用访问者模式来实现似乎并不容易。
我认为实现这项工作的唯一方法是对所有类型的节点使用访问()方法,这些节点可能有一个 X
类型的节点作为子节点,并将我的节点替换逻辑放在那里,但是可能有很多这样的节点。另外,如果我后来决定添加一种新类型的节点,我就会面临忘记检查该访问者中新的特殊情况的风险。
我要解决的问题是什么:
对于当前情况,我的树节点中的 FunctionCall 类型仅传达操作的名称及其参数。
我想用 MethodInspiration
替换它们,并进行适当的 OOish 转换:
m(A, B) -> A.m(B)
m(n(A, B), C) -> (A.n(B)).m(C)
当然,这可以通过一千种不同的方式来完成,这是最简单的一种方式,只需尝试仅考虑 调用
类,其中可能存在也可能不存在目标,但我希望尽可能明确(即使用不同类型的节点),以表达不同的事物(如果可能)。
In my small compiler I currently have a hand-made AST.
I was considering the idea of having a visitor that would look after nodes of a certain type X
and would replace them by nodes of type X'
. The trouble is that it seems that it isn't something easy to implement with the visitor pattern.
The only way I can see to make this work would be to have visit() methods to all kinds of nodes that could possibility have a node of type X
as child and put my node replacing logic there, but there may be lots of those nodes. Plus, if I later decide to add a new kind of node, I incur the risk of not remembering to check for that new special case in this visitor.
What's the problem I'm trying to solve:
For the current case I have in my tree nodes of type FunctionCall
that convey only the name of a operation as well as its parameters.
I'd like to substitute those with a MethodInvocation
, with the appropriate OOish transformation:
m(A, B) -> A.m(B)
m(n(A, B), C) -> (A.n(B)).m(C)
Of course this can be done in a thousand of different ways, being the easiest one to simply try to consider only a Call
class in which there may or may not exist a target, but I'd like to be as explicit as possible (that is, using different kinds of nodes), to express different things, if possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论