ยปCore Development>Code coverage>Lib/ast.py

Python code coverage for Lib/ast.py

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