ast.py 13 KB

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