Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | """ |
| 3 | ast |
| 4 | ~~~ |
| 5 | |
| 6 | The `ast` module helps Python applications to process trees of the Python |
| 7 | abstract syntax grammar. The abstract syntax itself might change with |
| 8 | each Python release; this module helps to find out programmatically what |
| 9 | the current grammar looks like and allows modifications of it. |
| 10 | |
| 11 | An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as |
| 12 | a flag to the `compile()` builtin function or by using the `parse()` |
| 13 | function from this module. The result will be a tree of objects whose |
| 14 | classes all inherit from `ast.AST`. |
| 15 | |
| 16 | A modified abstract syntax tree can be compiled into a Python code object |
| 17 | using the built-in `compile()` function. |
| 18 | |
| 19 | Additionally various helper functions are provided that make working with |
| 20 | the trees simpler. The main intention of the helper functions and this |
| 21 | module in general is to provide an easy to use interface for libraries |
| 22 | that work tightly with the python syntax (template engines for example). |
| 23 | |
| 24 | |
| 25 | :copyright: Copyright 2008 by Armin Ronacher. |
| 26 | :license: Python License. |
| 27 | """ |
| 28 | from _ast import * |
| 29 | |
| 30 | |
| 31 | def parse(expr, filename='<unknown>', mode='exec'): |
| 32 | """ |
| 33 | Parse an expression into an AST node. |
| 34 | Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST). |
| 35 | """ |
| 36 | return compile(expr, filename, mode, PyCF_ONLY_AST) |
| 37 | |
| 38 | |
| 39 | def literal_eval(node_or_string): |
| 40 | """ |
| 41 | Safely evaluate an expression node or a string containing a Python |
| 42 | expression. The string or node provided may only consist of the following |
| 43 | Python literal structures: strings, numbers, tuples, lists, dicts, booleans, |
| 44 | and None. |
| 45 | """ |
| 46 | _safe_names = {'None': None, 'True': True, 'False': False} |
| 47 | if isinstance(node_or_string, str): |
| 48 | node_or_string = parse(node_or_string, mode='eval') |
| 49 | if isinstance(node_or_string, Expression): |
| 50 | node_or_string = node_or_string.body |
| 51 | def _convert(node): |
| 52 | if isinstance(node, Str): |
| 53 | return node.s |
| 54 | elif isinstance(node, Num): |
| 55 | return node.n |
| 56 | elif isinstance(node, Tuple): |
| 57 | return tuple(map(_convert, node.elts)) |
| 58 | elif isinstance(node, List): |
| 59 | return list(map(_convert, node.elts)) |
| 60 | elif isinstance(node, Dict): |
| 61 | return dict((_convert(k), _convert(v)) for k, v |
| 62 | in zip(node.keys, node.values)) |
| 63 | elif isinstance(node, Name): |
| 64 | if node.id in _safe_names: |
| 65 | return _safe_names[node.id] |
| 66 | raise ValueError('malformed string') |
| 67 | return _convert(node_or_string) |
| 68 | |
| 69 | |
| 70 | def dump(node, annotate_fields=True, include_attributes=False): |
| 71 | """ |
| 72 | Return a formatted dump of the tree in *node*. This is mainly useful for |
| 73 | debugging purposes. The returned string will show the names and the values |
| 74 | for fields. This makes the code impossible to evaluate, so if evaluation is |
| 75 | wanted *annotate_fields* must be set to False. Attributes such as line |
Benjamin Peterson | dcf97b9 | 2008-07-02 17:30:14 +0000 | [diff] [blame] | 76 | numbers and column offsets are not dumped by default. If this is wanted, |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame] | 77 | *include_attributes* can be set to True. |
| 78 | """ |
| 79 | def _format(node): |
| 80 | if isinstance(node, AST): |
| 81 | fields = [(a, _format(b)) for a, b in iter_fields(node)] |
| 82 | rv = '%s(%s' % (node.__class__.__name__, ', '.join( |
| 83 | ('%s=%s' % field for field in fields) |
| 84 | if annotate_fields else |
| 85 | (b for a, b in fields) |
| 86 | )) |
| 87 | if include_attributes and node._attributes: |
| 88 | rv += fields and ', ' or ' ' |
| 89 | rv += ', '.join('%s=%s' % (a, _format(getattr(node, a))) |
| 90 | for a in node._attributes) |
| 91 | return rv + ')' |
| 92 | elif isinstance(node, list): |
| 93 | return '[%s]' % ', '.join(_format(x) for x in node) |
| 94 | return repr(node) |
| 95 | if not isinstance(node, AST): |
| 96 | raise TypeError('expected AST, got %r' % node.__class__.__name__) |
| 97 | return _format(node) |
| 98 | |
| 99 | |
| 100 | def copy_location(new_node, old_node): |
| 101 | """ |
| 102 | Copy source location (`lineno` and `col_offset` attributes) from |
| 103 | *old_node* to *new_node* if possible, and return *new_node*. |
| 104 | """ |
| 105 | for attr in 'lineno', 'col_offset': |
| 106 | if attr in old_node._attributes and attr in new_node._attributes \ |
| 107 | and hasattr(old_node, attr): |
| 108 | setattr(new_node, attr, getattr(old_node, attr)) |
| 109 | return new_node |
| 110 | |
| 111 | |
| 112 | def fix_missing_locations(node): |
| 113 | """ |
| 114 | When you compile a node tree with compile(), the compiler expects lineno and |
| 115 | col_offset attributes for every node that supports them. This is rather |
| 116 | tedious to fill in for generated nodes, so this helper adds these attributes |
| 117 | recursively where not already set, by setting them to the values of the |
| 118 | parent node. It works recursively starting at *node*. |
| 119 | """ |
| 120 | def _fix(node, lineno, col_offset): |
| 121 | if 'lineno' in node._attributes: |
| 122 | if not hasattr(node, 'lineno'): |
| 123 | node.lineno = lineno |
| 124 | else: |
| 125 | lineno = node.lineno |
| 126 | if 'col_offset' in node._attributes: |
| 127 | if not hasattr(node, 'col_offset'): |
| 128 | node.col_offset = col_offset |
| 129 | else: |
| 130 | col_offset = node.col_offset |
| 131 | for child in iter_child_nodes(node): |
| 132 | _fix(child, lineno, col_offset) |
| 133 | _fix(node, 1, 0) |
| 134 | return node |
| 135 | |
| 136 | |
| 137 | def increment_lineno(node, n=1): |
| 138 | """ |
| 139 | Increment the line number of each node in the tree starting at *node* by *n*. |
| 140 | This is useful to "move code" to a different location in a file. |
| 141 | """ |
| 142 | if 'lineno' in node._attributes: |
| 143 | node.lineno = getattr(node, 'lineno', 0) + n |
| 144 | for child in walk(node): |
| 145 | if 'lineno' in child._attributes: |
| 146 | child.lineno = getattr(child, 'lineno', 0) + n |
| 147 | return node |
| 148 | |
| 149 | |
| 150 | def iter_fields(node): |
| 151 | """ |
| 152 | Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` |
| 153 | that is present on *node*. |
| 154 | """ |
| 155 | for field in node._fields: |
| 156 | try: |
| 157 | yield field, getattr(node, field) |
| 158 | except AttributeError: |
| 159 | pass |
| 160 | |
| 161 | |
| 162 | def iter_child_nodes(node): |
| 163 | """ |
| 164 | Yield all direct child nodes of *node*, that is, all fields that are nodes |
| 165 | and all items of fields that are lists of nodes. |
| 166 | """ |
| 167 | for name, field in iter_fields(node): |
| 168 | if isinstance(field, AST): |
| 169 | yield field |
| 170 | elif isinstance(field, list): |
| 171 | for item in field: |
| 172 | if isinstance(item, AST): |
| 173 | yield item |
| 174 | |
| 175 | |
| 176 | def get_docstring(node, clean=True): |
| 177 | """ |
| 178 | Return the docstring for the given node or None if no docstring can |
| 179 | be found. If the node provided does not have docstrings a TypeError |
| 180 | will be raised. |
| 181 | """ |
| 182 | if not isinstance(node, (FunctionDef, ClassDef, Module)): |
| 183 | raise TypeError("%r can't have docstrings" % node.__class__.__name__) |
| 184 | if node.body and isinstance(node.body[0], Expr) and \ |
| 185 | isinstance(node.body[0].value, Str): |
| 186 | if clean: |
| 187 | import inspect |
| 188 | return inspect.cleandoc(node.body[0].value.s) |
| 189 | return node.body[0].value.s |
| 190 | |
| 191 | |
| 192 | def walk(node): |
| 193 | """ |
| 194 | Recursively yield all child nodes of *node*, in no specified order. This is |
| 195 | useful if you only want to modify nodes in place and don't care about the |
| 196 | context. |
| 197 | """ |
| 198 | from collections import deque |
| 199 | todo = deque([node]) |
| 200 | while todo: |
| 201 | node = todo.popleft() |
| 202 | todo.extend(iter_child_nodes(node)) |
| 203 | yield node |
| 204 | |
| 205 | |
| 206 | class NodeVisitor(object): |
| 207 | """ |
| 208 | A node visitor base class that walks the abstract syntax tree and calls a |
| 209 | visitor function for every node found. This function may return a value |
| 210 | which is forwarded by the `visit` method. |
| 211 | |
| 212 | This class is meant to be subclassed, with the subclass adding visitor |
| 213 | methods. |
| 214 | |
| 215 | Per default the visitor functions for the nodes are ``'visit_'`` + |
| 216 | class name of the node. So a `TryFinally` node visit function would |
| 217 | be `visit_TryFinally`. This behavior can be changed by overriding |
| 218 | the `visit` method. If no visitor function exists for a node |
| 219 | (return value `None`) the `generic_visit` visitor is used instead. |
| 220 | |
| 221 | Don't use the `NodeVisitor` if you want to apply changes to nodes during |
| 222 | traversing. For this a special visitor exists (`NodeTransformer`) that |
| 223 | allows modifications. |
| 224 | """ |
| 225 | |
| 226 | def visit(self, node): |
| 227 | """Visit a node.""" |
| 228 | method = 'visit_' + node.__class__.__name__ |
| 229 | visitor = getattr(self, method, self.generic_visit) |
| 230 | return visitor(node) |
| 231 | |
| 232 | def generic_visit(self, node): |
| 233 | """Called if no explicit visitor function exists for a node.""" |
| 234 | for field, value in iter_fields(node): |
| 235 | if isinstance(value, list): |
| 236 | for item in value: |
| 237 | if isinstance(item, AST): |
| 238 | self.visit(item) |
| 239 | elif isinstance(value, AST): |
| 240 | self.visit(value) |
| 241 | |
| 242 | |
| 243 | class NodeTransformer(NodeVisitor): |
| 244 | """ |
| 245 | A :class:`NodeVisitor` subclass that walks the abstract syntax tree and |
| 246 | allows modification of nodes. |
| 247 | |
| 248 | The `NodeTransformer` will walk the AST and use the return value of the |
| 249 | visitor methods to replace or remove the old node. If the return value of |
| 250 | the visitor method is ``None``, the node will be removed from its location, |
| 251 | otherwise it is replaced with the return value. The return value may be the |
| 252 | original node in which case no replacement takes place. |
| 253 | |
| 254 | Here is an example transformer that rewrites all occurrences of name lookups |
| 255 | (``foo``) to ``data['foo']``:: |
| 256 | |
| 257 | class RewriteName(NodeTransformer): |
| 258 | |
| 259 | def visit_Name(self, node): |
| 260 | return copy_location(Subscript( |
| 261 | value=Name(id='data', ctx=Load()), |
| 262 | slice=Index(value=Str(s=node.id)), |
| 263 | ctx=node.ctx |
| 264 | ), node) |
| 265 | |
| 266 | Keep in mind that if the node you're operating on has child nodes you must |
| 267 | either transform the child nodes yourself or call the :meth:`generic_visit` |
| 268 | method for the node first. |
| 269 | |
| 270 | For nodes that were part of a collection of statements (that applies to all |
| 271 | statement nodes), the visitor may also return a list of nodes rather than |
| 272 | just a single node. |
| 273 | |
| 274 | Usually you use the transformer like this:: |
| 275 | |
| 276 | node = YourTransformer().visit(node) |
| 277 | """ |
| 278 | |
| 279 | def generic_visit(self, node): |
| 280 | for field, old_value in iter_fields(node): |
| 281 | old_value = getattr(node, field, None) |
| 282 | if isinstance(old_value, list): |
| 283 | new_values = [] |
| 284 | for value in old_value: |
| 285 | if isinstance(value, AST): |
| 286 | value = self.visit(value) |
| 287 | if value is None: |
| 288 | continue |
| 289 | elif not isinstance(value, AST): |
| 290 | new_values.extend(value) |
| 291 | continue |
| 292 | new_values.append(value) |
| 293 | old_value[:] = new_values |
| 294 | elif isinstance(old_value, AST): |
| 295 | new_node = self.visit(old_value) |
| 296 | if new_node is None: |
| 297 | delattr(node, field) |
| 298 | else: |
| 299 | setattr(node, field, new_node) |
| 300 | return node |