修订版 | e3791bff4c61fd47429b99c81916e410336609cc (tree) |
---|---|
时间 | 2013-11-04 07:44:23 |
作者 | Albert Mietus < albert AT ons-huis DOT net > |
Commiter | Albert Mietus < albert AT ons-huis DOT net > |
INTERMEZZO: added a new, beter tree-walker walk_ast(). Not yet used (outside IPNotebook)
@@ -33,7 +33,36 @@ | ||
33 | 33 | if len(DEBUG & set(('all', 'ALL', self.__class__.__name__, 'AST',' AST2', 'init'))): |
34 | 34 | logging.debug ('%s::super.init(%s;%s)' % (self.__class__.__name__, self._node_no(), ",".join(str(arg) for arg in args))) |
35 | 35 | |
36 | - def walk(self, topdown=True, _top=None): | |
36 | + def walk_ast(self, _env={}): | |
37 | + """Walk over the AST in an os.walk() style (Generator). _env is a private parameter. Do not use | |
38 | + | |
39 | + For each node a 3-tuple is returned: | |
40 | + . 1 path : A tuple of nodes from the top-node down (but) the current node: | |
41 | + . path[0] is the top-node; path[-1] is the parent | |
42 | + 2 node : The current node; each node is visited exactly once | |
43 | + 3 env : A dict with (virtual) attributes of the current node: | |
44 | + . - 'ns' : the current scope/namespace (Note: the NS is actually part of the SDG, but ...) | |
45 | + . - 'kids' : a tuple with all descendants | |
46 | + | |
47 | + The "top-node" is the node on which `walk_ast() is called; typically the root of the AST/SDG. It is not part of the returned nodes. | |
48 | + All returned values should be used as read-only!""" | |
49 | + | |
50 | + logging.debug("node=%s, type=%s _env['ns']=%s", self, type(self),_env.get('ns') if _env else None) | |
51 | + | |
52 | + | |
53 | + path, env = (self,), {} | |
54 | + env['ns'] = self.__dict__.get('namespace', _env.get('ns')) # Can be None | |
55 | + | |
56 | + for node in self._descendants(): | |
57 | + if not isinstance(node, ASTBase): | |
58 | + logging.warning("Skipping %s (type=%s) as it is a non-ASTBase'd kid of %s", node, type(node), self) | |
59 | + continue | |
60 | + yield path, node, env | |
61 | + for p,n,e in node.walk_ast(env): | |
62 | + yield path+p,n,e | |
63 | + | |
64 | + | |
65 | + def walk(self, topdown=True, _top=None): # OLD? XXX | |
37 | 66 | """Walk over the complete AST2, in an 'os.walk()' style (Generator) |
38 | 67 | For each node a 3-tuple is returned: |
39 | 68 | node, parent, descendants |