[Compiler-sig] AST observations
Finn Bock
bckfnn@worldonline.dk
Thu, 18 Apr 2002 09:37:52 GMT
[Eric C. Newton]
>I gave up on trying to use recursion to figure out a Node's parents in
>an AST tree. Very often I need to know the parents of the Node I'm
>looking at, and using recursion to hold this information was becoming
>cumbersome.
If you only need the ancestry of the current node in the visitXXXX
methods, then the open_level(), close_level() visitor methods that I
suggested previously should work nicely:
class MyVisitor(ASTVisitor):
def __init__(self):
self.ancestry = []
def open_level(self, node):
self.ancestry.append(node)
def close_level(self, node):
self.ancestry.pop()
def visitFunctionDef(self, node):
print "parent is", self.ancestry[-2]
regards,
finn