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