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