问题描述
我的同事建议我写一个访问者模式来导航AST。
据我所知,AST中的每个节点都会有 visit()
方法(?)会不知何故被调用(从哪里?)。
为了简化一切,假设我有节点 Root
,表达式
,数字
, Op
,树状结构如下:
根
|
Op(+)
/ \
/ \
数字(5)\
Op(*)
/ \
/ \
/ \
数字(2)数字(444)
任何人都可以想象访问者模式如何访问这棵树来产生输出:
5 + 2 * 444
解决方案 / div> 维基百科有的完整概述,尽管他们使用的示例实现是在Java中。
基本上,你想实现一个。 AST中的每个节点都需要实现 accept()
方法(不是 visit()
方法)。该方法将一个访问者对象作为参数。在执行 accept()
方法时,您可以调用访问者对象的 visit()
方法对于每个AST节点类型;在Java中,您将使用参数重载,在Python中我假设您可以使用不同的 visit _ *()
方法)。然后将使用正确的节点类型作为参数分派正确的访问者。
My collegue suggested me to write a visitor pattern to navigate the AST. Can anyone tell me more how would I start writing it?
As far as I understand, each Node in AST would have visit()
method (?) that would somehow get called (from where?). That about concludes my understanding.
To simplify everything, suppose I have nodes Root
, Expression
, Number
, Op
and the tree looks like this:
Root
|
Op(+)
/ \
/ \
Number(5) \
Op(*)
/ \
/ \
/ \
Number(2) Number(444)
Can anyone think of how the visitor pattern would visit this tree to produce output:
5 + 2 * 444
Thanks, Boda Cydo.
解决方案 Wikipedia has a great overview of how the Visitor pattern works, although the sample implementation that they use is in Java. You can easily port that to Python, though, no?
Basically, you want to implement a mechanism for double dispatch. Each node in your AST would need to implement an accept()
method (NOT a visit()
method). The method takes, as an argument, a visitor object. In the implementation of this accept()
method, you call a visit()
method of the visitor object (there will be one for each AST node type; in Java, you'll use parameter overloading, in Python I suppose you can use different visit_*()
methods). The correct visitor will then be dispatched with the correct Node type as argument.
这篇关于如何在Python中编写抽象语法树的访问模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-06 09:05