Skip to content

Instantly share code, notes, and snippets.

@pfmiles
Created December 27, 2011 05:18
Show Gist options
  • Save pfmiles/1522776 to your computer and use it in GitHub Desktop.
Save pfmiles/1522776 to your computer and use it in GitHub Desktop.
Flexible visitor interface for AST walking...
public class ComparingNode implements DataFilterNode {
public <P, R> R accept(DataFilterVisitor<P, R> visitor, P param) {
return visitor.visitComparingNode(this, param);
}
}
public interface DataFilterNode {
public <P, R> R accept(DataFilterVisitor<P, R> visitor, P param);
}
public interface DataFilterVisitor<P, R> {
R visitUnionNode(UnionNode node, P param);
R visitIntersectionNode(IntersectionNode node, P param);
R visitComparingNode(ComparingNode comparingNode, P param);
......
}
@pfmiles
Copy link
Author

pfmiles commented Dec 13, 2012

DataFilterVisitor.java is the interface for visitors,DataFilterNode.java is the interface for AST nodes;ComparingNode.java is an example of AST node implementation.
DataFilterVisitor.java是visitor接口,DataFilterNode.java是节点接口;ComparingNode.java是其中一种节点实现示例;
Note that the 'param' of type 'P' is passed by reference among the visitor methods. In other words, all methods of the visitor share the same 'param' object during one invocation. Which means the values in 'param' may be dirty in some cases, that is, modified by child nodes' visiting.So you may save these values you want to protect on the 'call stack'(that is, make a copy of the value as a variable in the method), and reset the values in 'param' every time when you start a new direct child node's visit.
请注意'P'类型的'param'是以引用的方式在visitor的各方法之间传递的。换句话说,在同一次调用过程中visitor的所有方法都共享同一个'param'对象。这就表示在某些情况下'param'中的值会脏掉(被子结点的访问所更改)。所以你可以将你想要保护的param中的变量保存在'调用栈'上(就是将它保存为方法中的一个变量拷贝),并且在每次开始一个新的、对本层子节点的遍历的时候都用这份拷贝重置param中的值。

@pfmiles
Copy link
Author

pfmiles commented Dec 24, 2012

Or pass a newly created 'param' every time you start a new child node's visit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment