1"""API for traversing the AST nodes. Implemented by the compiler and 2meta introspection. 3""" 4from .nodes import Node 5 6 7class NodeVisitor: 8 """Walks the abstract syntax tree and call visitor functions for every 9 node found. The visitor functions may return values which will be 10 forwarded by the `visit` method. 11 12 Per default the visitor functions for the nodes are ``'visit_'`` + 13 class name of the node. So a `TryFinally` node visit function would 14 be `visit_TryFinally`. This behavior can be changed by overriding 15 the `get_visitor` function. If no visitor function exists for a node 16 (return value `None`) the `generic_visit` visitor is used instead. 17 """ 18 19 def get_visitor(self, node): 20 """Return the visitor function for this node or `None` if no visitor 21 exists for this node. In that case the generic visit function is 22 used instead. 23 """ 24 return getattr(self, f"visit_{node.__class__.__name__}", None) 25 26 def visit(self, node, *args, **kwargs): 27 """Visit a node.""" 28 f = self.get_visitor(node) 29 if f is not None: 30 return f(node, *args, **kwargs) 31 return self.generic_visit(node, *args, **kwargs) 32 33 def generic_visit(self, node, *args, **kwargs): 34 """Called if no explicit visitor function exists for a node.""" 35 for node in node.iter_child_nodes(): 36 self.visit(node, *args, **kwargs) 37 38 39class NodeTransformer(NodeVisitor): 40 """Walks the abstract syntax tree and allows modifications of nodes. 41 42 The `NodeTransformer` will walk the AST and use the return value of the 43 visitor functions to replace or remove the old node. If the return 44 value of the visitor function is `None` the node will be removed 45 from the previous location otherwise it's replaced with the return 46 value. The return value may be the original node in which case no 47 replacement takes place. 48 """ 49 50 def generic_visit(self, node, *args, **kwargs): 51 for field, old_value in node.iter_fields(): 52 if isinstance(old_value, list): 53 new_values = [] 54 for value in old_value: 55 if isinstance(value, Node): 56 value = self.visit(value, *args, **kwargs) 57 if value is None: 58 continue 59 elif not isinstance(value, Node): 60 new_values.extend(value) 61 continue 62 new_values.append(value) 63 old_value[:] = new_values 64 elif isinstance(old_value, Node): 65 new_node = self.visit(old_value, *args, **kwargs) 66 if new_node is None: 67 delattr(node, field) 68 else: 69 setattr(node, field, new_node) 70 return node 71 72 def visit_list(self, node, *args, **kwargs): 73 """As transformers may return lists in some places this method 74 can be used to enforce a list as return value. 75 """ 76 rv = self.visit(node, *args, **kwargs) 77 if not isinstance(rv, list): 78 rv = [rv] 79 return rv 80