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