/Lib/lib2to3/fixer_util.py

http://unladen-swallow.googlecode.com/ · Python · 425 lines · 353 code · 25 blank · 47 comment · 25 complexity · 3be3ddd60790f7d3027f2a7c4ec63d61 MD5 · raw file

  1. """Utility functions, node construction macros, etc."""
  2. # Author: Collin Winter
  3. # Local imports
  4. from .pgen2 import token
  5. from .pytree import Leaf, Node
  6. from .pygram import python_symbols as syms
  7. from . import patcomp
  8. ###########################################################
  9. ### Common node-construction "macros"
  10. ###########################################################
  11. def KeywordArg(keyword, value):
  12. return Node(syms.argument,
  13. [keyword, Leaf(token.EQUAL, '='), value])
  14. def LParen():
  15. return Leaf(token.LPAR, "(")
  16. def RParen():
  17. return Leaf(token.RPAR, ")")
  18. def Assign(target, source):
  19. """Build an assignment statement"""
  20. if not isinstance(target, list):
  21. target = [target]
  22. if not isinstance(source, list):
  23. source.set_prefix(" ")
  24. source = [source]
  25. return Node(syms.atom,
  26. target + [Leaf(token.EQUAL, "=", prefix=" ")] + source)
  27. def Name(name, prefix=None):
  28. """Return a NAME leaf"""
  29. return Leaf(token.NAME, name, prefix=prefix)
  30. def Attr(obj, attr):
  31. """A node tuple for obj.attr"""
  32. return [obj, Node(syms.trailer, [Dot(), attr])]
  33. def Comma():
  34. """A comma leaf"""
  35. return Leaf(token.COMMA, ",")
  36. def Dot():
  37. """A period (.) leaf"""
  38. return Leaf(token.DOT, ".")
  39. def ArgList(args, lparen=LParen(), rparen=RParen()):
  40. """A parenthesised argument list, used by Call()"""
  41. node = Node(syms.trailer, [lparen.clone(), rparen.clone()])
  42. if args:
  43. node.insert_child(1, Node(syms.arglist, args))
  44. return node
  45. def Call(func_name, args=None, prefix=None):
  46. """A function call"""
  47. node = Node(syms.power, [func_name, ArgList(args)])
  48. if prefix is not None:
  49. node.set_prefix(prefix)
  50. return node
  51. def Newline():
  52. """A newline literal"""
  53. return Leaf(token.NEWLINE, "\n")
  54. def BlankLine():
  55. """A blank line"""
  56. return Leaf(token.NEWLINE, "")
  57. def Number(n, prefix=None):
  58. return Leaf(token.NUMBER, n, prefix=prefix)
  59. def Subscript(index_node):
  60. """A numeric or string subscript"""
  61. return Node(syms.trailer, [Leaf(token.LBRACE, '['),
  62. index_node,
  63. Leaf(token.RBRACE, ']')])
  64. def String(string, prefix=None):
  65. """A string leaf"""
  66. return Leaf(token.STRING, string, prefix=prefix)
  67. def ListComp(xp, fp, it, test=None):
  68. """A list comprehension of the form [xp for fp in it if test].
  69. If test is None, the "if test" part is omitted.
  70. """
  71. xp.set_prefix("")
  72. fp.set_prefix(" ")
  73. it.set_prefix(" ")
  74. for_leaf = Leaf(token.NAME, "for")
  75. for_leaf.set_prefix(" ")
  76. in_leaf = Leaf(token.NAME, "in")
  77. in_leaf.set_prefix(" ")
  78. inner_args = [for_leaf, fp, in_leaf, it]
  79. if test:
  80. test.set_prefix(" ")
  81. if_leaf = Leaf(token.NAME, "if")
  82. if_leaf.set_prefix(" ")
  83. inner_args.append(Node(syms.comp_if, [if_leaf, test]))
  84. inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)])
  85. return Node(syms.atom,
  86. [Leaf(token.LBRACE, "["),
  87. inner,
  88. Leaf(token.RBRACE, "]")])
  89. def FromImport(package_name, name_leafs):
  90. """ Return an import statement in the form:
  91. from package import name_leafs"""
  92. # XXX: May not handle dotted imports properly (eg, package_name='foo.bar')
  93. #assert package_name == '.' or '.' not in package_name, "FromImport has "\
  94. # "not been tested with dotted package names -- use at your own "\
  95. # "peril!"
  96. for leaf in name_leafs:
  97. # Pull the leaves out of their old tree
  98. leaf.remove()
  99. children = [Leaf(token.NAME, 'from'),
  100. Leaf(token.NAME, package_name, prefix=" "),
  101. Leaf(token.NAME, 'import', prefix=" "),
  102. Node(syms.import_as_names, name_leafs)]
  103. imp = Node(syms.import_from, children)
  104. return imp
  105. ###########################################################
  106. ### Determine whether a node represents a given literal
  107. ###########################################################
  108. def is_tuple(node):
  109. """Does the node represent a tuple literal?"""
  110. if isinstance(node, Node) and node.children == [LParen(), RParen()]:
  111. return True
  112. return (isinstance(node, Node)
  113. and len(node.children) == 3
  114. and isinstance(node.children[0], Leaf)
  115. and isinstance(node.children[1], Node)
  116. and isinstance(node.children[2], Leaf)
  117. and node.children[0].value == "("
  118. and node.children[2].value == ")")
  119. def is_list(node):
  120. """Does the node represent a list literal?"""
  121. return (isinstance(node, Node)
  122. and len(node.children) > 1
  123. and isinstance(node.children[0], Leaf)
  124. and isinstance(node.children[-1], Leaf)
  125. and node.children[0].value == "["
  126. and node.children[-1].value == "]")
  127. ###########################################################
  128. ### Misc
  129. ###########################################################
  130. def parenthesize(node):
  131. return Node(syms.atom, [LParen(), node, RParen()])
  132. consuming_calls = set(["sorted", "list", "set", "any", "all", "tuple", "sum",
  133. "min", "max"])
  134. def attr_chain(obj, attr):
  135. """Follow an attribute chain.
  136. If you have a chain of objects where a.foo -> b, b.foo-> c, etc,
  137. use this to iterate over all objects in the chain. Iteration is
  138. terminated by getattr(x, attr) is None.
  139. Args:
  140. obj: the starting object
  141. attr: the name of the chaining attribute
  142. Yields:
  143. Each successive object in the chain.
  144. """
  145. next = getattr(obj, attr)
  146. while next:
  147. yield next
  148. next = getattr(next, attr)
  149. p0 = """for_stmt< 'for' any 'in' node=any ':' any* >
  150. | comp_for< 'for' any 'in' node=any any* >
  151. """
  152. p1 = """
  153. power<
  154. ( 'iter' | 'list' | 'tuple' | 'sorted' | 'set' | 'sum' |
  155. 'any' | 'all' | (any* trailer< '.' 'join' >) )
  156. trailer< '(' node=any ')' >
  157. any*
  158. >
  159. """
  160. p2 = """
  161. power<
  162. 'sorted'
  163. trailer< '(' arglist<node=any any*> ')' >
  164. any*
  165. >
  166. """
  167. pats_built = False
  168. def in_special_context(node):
  169. """ Returns true if node is in an environment where all that is required
  170. of it is being itterable (ie, it doesn't matter if it returns a list
  171. or an itterator).
  172. See test_map_nochange in test_fixers.py for some examples and tests.
  173. """
  174. global p0, p1, p2, pats_built
  175. if not pats_built:
  176. p1 = patcomp.compile_pattern(p1)
  177. p0 = patcomp.compile_pattern(p0)
  178. p2 = patcomp.compile_pattern(p2)
  179. pats_built = True
  180. patterns = [p0, p1, p2]
  181. for pattern, parent in zip(patterns, attr_chain(node, "parent")):
  182. results = {}
  183. if pattern.match(parent, results) and results["node"] is node:
  184. return True
  185. return False
  186. def is_probably_builtin(node):
  187. """
  188. Check that something isn't an attribute or function name etc.
  189. """
  190. prev = node.get_prev_sibling()
  191. if prev is not None and prev.type == token.DOT:
  192. # Attribute lookup.
  193. return False
  194. parent = node.parent
  195. if parent.type in (syms.funcdef, syms.classdef):
  196. return False
  197. if parent.type == syms.expr_stmt and parent.children[0] is node:
  198. # Assignment.
  199. return False
  200. if parent.type == syms.parameters or \
  201. (parent.type == syms.typedargslist and (
  202. (prev is not None and prev.type == token.COMMA) or
  203. parent.children[0] is node
  204. )):
  205. # The name of an argument.
  206. return False
  207. return True
  208. ###########################################################
  209. ### The following functions are to find bindings in a suite
  210. ###########################################################
  211. def make_suite(node):
  212. if node.type == syms.suite:
  213. return node
  214. node = node.clone()
  215. parent, node.parent = node.parent, None
  216. suite = Node(syms.suite, [node])
  217. suite.parent = parent
  218. return suite
  219. def find_root(node):
  220. """Find the top level namespace."""
  221. # Scamper up to the top level namespace
  222. while node.type != syms.file_input:
  223. assert node.parent, "Tree is insane! root found before "\
  224. "file_input node was found."
  225. node = node.parent
  226. return node
  227. def does_tree_import(package, name, node):
  228. """ Returns true if name is imported from package at the
  229. top level of the tree which node belongs to.
  230. To cover the case of an import like 'import foo', use
  231. None for the package and 'foo' for the name. """
  232. binding = find_binding(name, find_root(node), package)
  233. return bool(binding)
  234. def is_import(node):
  235. """Returns true if the node is an import statement."""
  236. return node.type in (syms.import_name, syms.import_from)
  237. def touch_import(package, name, node):
  238. """ Works like `does_tree_import` but adds an import statement
  239. if it was not imported. """
  240. def is_import_stmt(node):
  241. return node.type == syms.simple_stmt and node.children and \
  242. is_import(node.children[0])
  243. root = find_root(node)
  244. if does_tree_import(package, name, root):
  245. return
  246. add_newline_before = False
  247. # figure out where to insert the new import. First try to find
  248. # the first import and then skip to the last one.
  249. insert_pos = offset = 0
  250. for idx, node in enumerate(root.children):
  251. if not is_import_stmt(node):
  252. continue
  253. for offset, node2 in enumerate(root.children[idx:]):
  254. if not is_import_stmt(node2):
  255. break
  256. insert_pos = idx + offset
  257. break
  258. # if there are no imports where we can insert, find the docstring.
  259. # if that also fails, we stick to the beginning of the file
  260. if insert_pos == 0:
  261. for idx, node in enumerate(root.children):
  262. if node.type == syms.simple_stmt and node.children and \
  263. node.children[0].type == token.STRING:
  264. insert_pos = idx + 1
  265. add_newline_before
  266. break
  267. if package is None:
  268. import_ = Node(syms.import_name, [
  269. Leaf(token.NAME, 'import'),
  270. Leaf(token.NAME, name, prefix=' ')
  271. ])
  272. else:
  273. import_ = FromImport(package, [Leaf(token.NAME, name, prefix=' ')])
  274. children = [import_, Newline()]
  275. if add_newline_before:
  276. children.insert(0, Newline())
  277. root.insert_child(insert_pos, Node(syms.simple_stmt, children))
  278. _def_syms = set([syms.classdef, syms.funcdef])
  279. def find_binding(name, node, package=None):
  280. """ Returns the node which binds variable name, otherwise None.
  281. If optional argument package is supplied, only imports will
  282. be returned.
  283. See test cases for examples."""
  284. for child in node.children:
  285. ret = None
  286. if child.type == syms.for_stmt:
  287. if _find(name, child.children[1]):
  288. return child
  289. n = find_binding(name, make_suite(child.children[-1]), package)
  290. if n: ret = n
  291. elif child.type in (syms.if_stmt, syms.while_stmt):
  292. n = find_binding(name, make_suite(child.children[-1]), package)
  293. if n: ret = n
  294. elif child.type == syms.try_stmt:
  295. n = find_binding(name, make_suite(child.children[2]), package)
  296. if n:
  297. ret = n
  298. else:
  299. for i, kid in enumerate(child.children[3:]):
  300. if kid.type == token.COLON and kid.value == ":":
  301. # i+3 is the colon, i+4 is the suite
  302. n = find_binding(name, make_suite(child.children[i+4]), package)
  303. if n: ret = n
  304. elif child.type in _def_syms and child.children[1].value == name:
  305. ret = child
  306. elif _is_import_binding(child, name, package):
  307. ret = child
  308. elif child.type == syms.simple_stmt:
  309. ret = find_binding(name, child, package)
  310. elif child.type == syms.expr_stmt:
  311. if _find(name, child.children[0]):
  312. ret = child
  313. if ret:
  314. if not package:
  315. return ret
  316. if is_import(ret):
  317. return ret
  318. return None
  319. _block_syms = set([syms.funcdef, syms.classdef, syms.trailer])
  320. def _find(name, node):
  321. nodes = [node]
  322. while nodes:
  323. node = nodes.pop()
  324. if node.type > 256 and node.type not in _block_syms:
  325. nodes.extend(node.children)
  326. elif node.type == token.NAME and node.value == name:
  327. return node
  328. return None
  329. def _is_import_binding(node, name, package=None):
  330. """ Will reuturn node if node will import name, or node
  331. will import * from package. None is returned otherwise.
  332. See test cases for examples. """
  333. if node.type == syms.import_name and not package:
  334. imp = node.children[1]
  335. if imp.type == syms.dotted_as_names:
  336. for child in imp.children:
  337. if child.type == syms.dotted_as_name:
  338. if child.children[2].value == name:
  339. return node
  340. elif child.type == token.NAME and child.value == name:
  341. return node
  342. elif imp.type == syms.dotted_as_name:
  343. last = imp.children[-1]
  344. if last.type == token.NAME and last.value == name:
  345. return node
  346. elif imp.type == token.NAME and imp.value == name:
  347. return node
  348. elif node.type == syms.import_from:
  349. # unicode(...) is used to make life easier here, because
  350. # from a.b import parses to ['import', ['a', '.', 'b'], ...]
  351. if package and unicode(node.children[1]).strip() != package:
  352. return None
  353. n = node.children[3]
  354. if package and _find('as', n):
  355. # See test_from_import_as for explanation
  356. return None
  357. elif n.type == syms.import_as_names and _find(name, n):
  358. return node
  359. elif n.type == syms.import_as_name:
  360. child = n.children[2]
  361. if child.type == token.NAME and child.value == name:
  362. return node
  363. elif n.type == token.NAME and n.value == name:
  364. return node
  365. elif package and n.type == token.STAR:
  366. return node
  367. return None