PageRenderTime 48ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/ast.py

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