PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/python/Lib/ast.py

https://github.com/vesnican/play
Python | 301 lines | 190 code | 18 blank | 93 comment | 41 complexity | 224e6bd1aa78f94f4e77f868fdd9edc2 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(expr, filename='<unknown>', mode='exec'):
  25. """
  26. Parse an expression into an AST node.
  27. Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST).
  28. """
  29. return compile(expr, 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. raise ValueError('malformed string')
  58. return _convert(node_or_string)
  59. def dump(node, annotate_fields=True, include_attributes=False):
  60. """
  61. Return a formatted dump of the tree in *node*. This is mainly useful for
  62. debugging purposes. The returned string will show the names and the values
  63. for fields. This makes the code impossible to evaluate, so if evaluation is
  64. wanted *annotate_fields* must be set to False. Attributes such as line
  65. numbers and column offsets are not dumped by default. If this is wanted,
  66. *include_attributes* can be set to True.
  67. """
  68. def _format(node):
  69. if isinstance(node, AST):
  70. fields = [(a, _format(b)) for a, b in iter_fields(node)]
  71. rv = '%s(%s' % (node.__class__.__name__, ', '.join(
  72. ('%s=%s' % field for field in fields)
  73. if annotate_fields else
  74. (b for a, b in fields)
  75. ))
  76. if include_attributes and node._attributes:
  77. rv += fields and ', ' or ' '
  78. rv += ', '.join('%s=%s' % (a, _format(getattr(node, a)))
  79. for a in node._attributes)
  80. return rv + ')'
  81. elif isinstance(node, list):
  82. return '[%s]' % ', '.join(_format(x) for x in node)
  83. return repr(node)
  84. if not isinstance(node, AST):
  85. raise TypeError('expected AST, got %r' % node.__class__.__name__)
  86. return _format(node)
  87. def copy_location(new_node, old_node):
  88. """
  89. Copy source location (`lineno` and `col_offset` attributes) from
  90. *old_node* to *new_node* if possible, and return *new_node*.
  91. """
  92. for attr in 'lineno', 'col_offset':
  93. if attr in old_node._attributes and attr in new_node._attributes \
  94. and hasattr(old_node, attr):
  95. setattr(new_node, attr, getattr(old_node, attr))
  96. return new_node
  97. def fix_missing_locations(node):
  98. """
  99. When you compile a node tree with compile(), the compiler expects lineno and
  100. col_offset attributes for every node that supports them. This is rather
  101. tedious to fill in for generated nodes, so this helper adds these attributes
  102. recursively where not already set, by setting them to the values of the
  103. parent node. It works recursively starting at *node*.
  104. """
  105. def _fix(node, lineno, col_offset):
  106. if 'lineno' in node._attributes:
  107. if not hasattr(node, 'lineno'):
  108. node.lineno = lineno
  109. else:
  110. lineno = node.lineno
  111. if 'col_offset' in node._attributes:
  112. if not hasattr(node, 'col_offset'):
  113. node.col_offset = col_offset
  114. else:
  115. col_offset = node.col_offset
  116. for child in iter_child_nodes(node):
  117. _fix(child, lineno, col_offset)
  118. _fix(node, 1, 0)
  119. return node
  120. def increment_lineno(node, n=1):
  121. """
  122. Increment the line number of each node in the tree starting at *node* by *n*.
  123. This is useful to "move code" to a different location in a file.
  124. """
  125. if 'lineno' in node._attributes:
  126. node.lineno = getattr(node, 'lineno', 0) + n
  127. for child in walk(node):
  128. if 'lineno' in child._attributes:
  129. child.lineno = getattr(child, 'lineno', 0) + n
  130. return node
  131. def iter_fields(node):
  132. """
  133. Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
  134. that is present on *node*.
  135. """
  136. for field in node._fields:
  137. try:
  138. yield field, getattr(node, field)
  139. except AttributeError:
  140. pass
  141. def iter_child_nodes(node):
  142. """
  143. Yield all direct child nodes of *node*, that is, all fields that are nodes
  144. and all items of fields that are lists of nodes.
  145. """
  146. for name, field in iter_fields(node):
  147. if isinstance(field, AST):
  148. yield field
  149. elif isinstance(field, list):
  150. for item in field:
  151. if isinstance(item, AST):
  152. yield item
  153. def get_docstring(node, clean=True):
  154. """
  155. Return the docstring for the given node or None if no docstring can
  156. be found. If the node provided does not have docstrings a TypeError
  157. will be raised.
  158. """
  159. if not isinstance(node, (FunctionDef, ClassDef, Module)):
  160. raise TypeError("%r can't have docstrings" % node.__class__.__name__)
  161. if node.body and isinstance(node.body[0], Expr) and \
  162. isinstance(node.body[0].value, Str):
  163. if clean:
  164. import inspect
  165. return inspect.cleandoc(node.body[0].value.s)
  166. return node.body[0].value.s
  167. def walk(node):
  168. """
  169. Recursively yield all child nodes of *node*, in no specified order. This is
  170. useful if you only want to modify nodes in place and don't care about the
  171. context.
  172. """
  173. from collections import deque
  174. todo = deque([node])
  175. while todo:
  176. node = todo.popleft()
  177. todo.extend(iter_child_nodes(node))
  178. yield node
  179. class NodeVisitor(object):
  180. """
  181. A node visitor base class that walks the abstract syntax tree and calls a
  182. visitor function for every node found. This function may return a value
  183. which is forwarded by the `visit` method.
  184. This class is meant to be subclassed, with the subclass adding visitor
  185. methods.
  186. Per default the visitor functions for the nodes are ``'visit_'`` +
  187. class name of the node. So a `TryFinally` node visit function would
  188. be `visit_TryFinally`. This behavior can be changed by overriding
  189. the `visit` method. If no visitor function exists for a node
  190. (return value `None`) the `generic_visit` visitor is used instead.
  191. Don't use the `NodeVisitor` if you want to apply changes to nodes during
  192. traversing. For this a special visitor exists (`NodeTransformer`) that
  193. allows modifications.
  194. """
  195. def visit(self, node):
  196. """Visit a node."""
  197. method = 'visit_' + node.__class__.__name__
  198. visitor = getattr(self, method, self.generic_visit)
  199. return visitor(node)
  200. def generic_visit(self, node):
  201. """Called if no explicit visitor function exists for a node."""
  202. for field, value in iter_fields(node):
  203. if isinstance(value, list):
  204. for item in value:
  205. if isinstance(item, AST):
  206. self.visit(item)
  207. elif isinstance(value, AST):
  208. self.visit(value)
  209. class NodeTransformer(NodeVisitor):
  210. """
  211. A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
  212. allows modification of nodes.
  213. The `NodeTransformer` will walk the AST and use the return value of the
  214. visitor methods to replace or remove the old node. If the return value of
  215. the visitor method is ``None``, the node will be removed from its location,
  216. otherwise it is replaced with the return value. The return value may be the
  217. original node in which case no replacement takes place.
  218. Here is an example transformer that rewrites all occurrences of name lookups
  219. (``foo``) to ``data['foo']``::
  220. class RewriteName(NodeTransformer):
  221. def visit_Name(self, node):
  222. return copy_location(Subscript(
  223. value=Name(id='data', ctx=Load()),
  224. slice=Index(value=Str(s=node.id)),
  225. ctx=node.ctx
  226. ), node)
  227. Keep in mind that if the node you're operating on has child nodes you must
  228. either transform the child nodes yourself or call the :meth:`generic_visit`
  229. method for the node first.
  230. For nodes that were part of a collection of statements (that applies to all
  231. statement nodes), the visitor may also return a list of nodes rather than
  232. just a single node.
  233. Usually you use the transformer like this::
  234. node = YourTransformer().visit(node)
  235. """
  236. def generic_visit(self, node):
  237. for field, old_value in iter_fields(node):
  238. old_value = getattr(node, field, None)
  239. if isinstance(old_value, list):
  240. new_values = []
  241. for value in old_value:
  242. if isinstance(value, AST):
  243. value = self.visit(value)
  244. if value is None:
  245. continue
  246. elif not isinstance(value, AST):
  247. new_values.extend(value)
  248. continue
  249. new_values.append(value)
  250. old_value[:] = new_values
  251. elif isinstance(old_value, AST):
  252. new_node = self.visit(old_value)
  253. if new_node is None:
  254. delattr(node, field)
  255. else:
  256. setattr(node, field, new_node)
  257. return node