fixer_util.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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.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.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.prefix = ""
  72. fp.prefix = " "
  73. it.prefix = " "
  74. for_leaf = Leaf(token.NAME, "for")
  75. for_leaf.prefix = " "
  76. in_leaf = Leaf(token.NAME, "in")
  77. in_leaf.prefix = " "
  78. inner_args = [for_leaf, fp, in_leaf, it]
  79. if test:
  80. test.prefix = " "
  81. if_leaf = Leaf(token.NAME, "if")
  82. if_leaf.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. def ImportAndCall(node, results, names):
  106. """Returns an import statement and calls a method
  107. of the module:
  108. import module
  109. module.name()"""
  110. obj = results["obj"].clone()
  111. if obj.type == syms.arglist:
  112. newarglist = obj.clone()
  113. else:
  114. newarglist = Node(syms.arglist, [obj.clone()])
  115. after = results["after"]
  116. if after:
  117. after = [n.clone() for n in after]
  118. new = Node(syms.power,
  119. Attr(Name(names[0]), Name(names[1])) +
  120. [Node(syms.trailer,
  121. [results["lpar"].clone(),
  122. newarglist,
  123. results["rpar"].clone()])] + after)
  124. new.prefix = node.prefix
  125. return new
  126. ###########################################################
  127. ### Determine whether a node represents a given literal
  128. ###########################################################
  129. def is_tuple(node):
  130. """Does the node represent a tuple literal?"""
  131. if isinstance(node, Node) and node.children == [LParen(), RParen()]:
  132. return True
  133. return (isinstance(node, Node)
  134. and len(node.children) == 3
  135. and isinstance(node.children[0], Leaf)
  136. and isinstance(node.children[1], Node)
  137. and isinstance(node.children[2], Leaf)
  138. and node.children[0].value == "("
  139. and node.children[2].value == ")")
  140. def is_list(node):
  141. """Does the node represent a list literal?"""
  142. return (isinstance(node, Node)
  143. and len(node.children) > 1
  144. and isinstance(node.children[0], Leaf)
  145. and isinstance(node.children[-1], Leaf)
  146. and node.children[0].value == "["
  147. and node.children[-1].value == "]")
  148. ###########################################################
  149. ### Misc
  150. ###########################################################
  151. def parenthesize(node):
  152. return Node(syms.atom, [LParen(), node, RParen()])
  153. consuming_calls = {"sorted", "list", "set", "any", "all", "tuple", "sum",
  154. "min", "max", "enumerate"}
  155. def attr_chain(obj, attr):
  156. """Follow an attribute chain.
  157. If you have a chain of objects where a.foo -> b, b.foo-> c, etc,
  158. use this to iterate over all objects in the chain. Iteration is
  159. terminated by getattr(x, attr) is None.
  160. Args:
  161. obj: the starting object
  162. attr: the name of the chaining attribute
  163. Yields:
  164. Each successive object in the chain.
  165. """
  166. next = getattr(obj, attr)
  167. while next:
  168. yield next
  169. next = getattr(next, attr)
  170. p0 = """for_stmt< 'for' any 'in' node=any ':' any* >
  171. | comp_for< 'for' any 'in' node=any any* >
  172. """
  173. p1 = """
  174. power<
  175. ( 'iter' | 'list' | 'tuple' | 'sorted' | 'set' | 'sum' |
  176. 'any' | 'all' | 'enumerate' | (any* trailer< '.' 'join' >) )
  177. trailer< '(' node=any ')' >
  178. any*
  179. >
  180. """
  181. p2 = """
  182. power<
  183. ( 'sorted' | 'enumerate' )
  184. trailer< '(' arglist<node=any any*> ')' >
  185. any*
  186. >
  187. """
  188. pats_built = False
  189. def in_special_context(node):
  190. """ Returns true if node is in an environment where all that is required
  191. of it is being iterable (ie, it doesn't matter if it returns a list
  192. or an iterator).
  193. See test_map_nochange in test_fixers.py for some examples and tests.
  194. """
  195. global p0, p1, p2, pats_built
  196. if not pats_built:
  197. p0 = patcomp.compile_pattern(p0)
  198. p1 = patcomp.compile_pattern(p1)
  199. p2 = patcomp.compile_pattern(p2)
  200. pats_built = True
  201. patterns = [p0, p1, p2]
  202. for pattern, parent in zip(patterns, attr_chain(node, "parent")):
  203. results = {}
  204. if pattern.match(parent, results) and results["node"] is node:
  205. return True
  206. return False
  207. def is_probably_builtin(node):
  208. """
  209. Check that something isn't an attribute or function name etc.
  210. """
  211. prev = node.prev_sibling
  212. if prev is not None and prev.type == token.DOT:
  213. # Attribute lookup.
  214. return False
  215. parent = node.parent
  216. if parent.type in (syms.funcdef, syms.classdef):
  217. return False
  218. if parent.type == syms.expr_stmt and parent.children[0] is node:
  219. # Assignment.
  220. return False
  221. if parent.type == syms.parameters or \
  222. (parent.type == syms.typedargslist and (
  223. (prev is not None and prev.type == token.COMMA) or
  224. parent.children[0] is node
  225. )):
  226. # The name of an argument.
  227. return False
  228. return True
  229. def find_indentation(node):
  230. """Find the indentation of *node*."""
  231. while node is not None:
  232. if node.type == syms.suite and len(node.children) > 2:
  233. indent = node.children[1]
  234. if indent.type == token.INDENT:
  235. return indent.value
  236. node = node.parent
  237. return ""
  238. ###########################################################
  239. ### The following functions are to find bindings in a suite
  240. ###########################################################
  241. def make_suite(node):
  242. if node.type == syms.suite:
  243. return node
  244. node = node.clone()
  245. parent, node.parent = node.parent, None
  246. suite = Node(syms.suite, [node])
  247. suite.parent = parent
  248. return suite
  249. def find_root(node):
  250. """Find the top level namespace."""
  251. # Scamper up to the top level namespace
  252. while node.type != syms.file_input:
  253. node = node.parent
  254. if not node:
  255. raise ValueError("root found before file_input node was found.")
  256. return node
  257. def does_tree_import(package, name, node):
  258. """ Returns true if name is imported from package at the
  259. top level of the tree which node belongs to.
  260. To cover the case of an import like 'import foo', use
  261. None for the package and 'foo' for the name. """
  262. binding = find_binding(name, find_root(node), package)
  263. return bool(binding)
  264. def is_import(node):
  265. """Returns true if the node is an import statement."""
  266. return node.type in (syms.import_name, syms.import_from)
  267. def touch_import(package, name, node):
  268. """ Works like `does_tree_import` but adds an import statement
  269. if it was not imported. """
  270. def is_import_stmt(node):
  271. return (node.type == syms.simple_stmt and node.children and
  272. is_import(node.children[0]))
  273. root = find_root(node)
  274. if does_tree_import(package, name, root):
  275. return
  276. # figure out where to insert the new import. First try to find
  277. # the first import and then skip to the last one.
  278. insert_pos = offset = 0
  279. for idx, node in enumerate(root.children):
  280. if not is_import_stmt(node):
  281. continue
  282. for offset, node2 in enumerate(root.children[idx:]):
  283. if not is_import_stmt(node2):
  284. break
  285. insert_pos = idx + offset
  286. break
  287. # if there are no imports where we can insert, find the docstring.
  288. # if that also fails, we stick to the beginning of the file
  289. if insert_pos == 0:
  290. for idx, node in enumerate(root.children):
  291. if (node.type == syms.simple_stmt and node.children and
  292. node.children[0].type == token.STRING):
  293. insert_pos = idx + 1
  294. break
  295. if package is None:
  296. import_ = Node(syms.import_name, [
  297. Leaf(token.NAME, "import"),
  298. Leaf(token.NAME, name, prefix=" ")
  299. ])
  300. else:
  301. import_ = FromImport(package, [Leaf(token.NAME, name, prefix=" ")])
  302. children = [import_, Newline()]
  303. root.insert_child(insert_pos, Node(syms.simple_stmt, children))
  304. _def_syms = {syms.classdef, syms.funcdef}
  305. def find_binding(name, node, package=None):
  306. """ Returns the node which binds variable name, otherwise None.
  307. If optional argument package is supplied, only imports will
  308. be returned.
  309. See test cases for examples."""
  310. for child in node.children:
  311. ret = None
  312. if child.type == syms.for_stmt:
  313. if _find(name, child.children[1]):
  314. return child
  315. n = find_binding(name, make_suite(child.children[-1]), package)
  316. if n: ret = n
  317. elif child.type in (syms.if_stmt, syms.while_stmt):
  318. n = find_binding(name, make_suite(child.children[-1]), package)
  319. if n: ret = n
  320. elif child.type == syms.try_stmt:
  321. n = find_binding(name, make_suite(child.children[2]), package)
  322. if n:
  323. ret = n
  324. else:
  325. for i, kid in enumerate(child.children[3:]):
  326. if kid.type == token.COLON and kid.value == ":":
  327. # i+3 is the colon, i+4 is the suite
  328. n = find_binding(name, make_suite(child.children[i+4]), package)
  329. if n: ret = n
  330. elif child.type in _def_syms and child.children[1].value == name:
  331. ret = child
  332. elif _is_import_binding(child, name, package):
  333. ret = child
  334. elif child.type == syms.simple_stmt:
  335. ret = find_binding(name, child, package)
  336. elif child.type == syms.expr_stmt:
  337. if _find(name, child.children[0]):
  338. ret = child
  339. if ret:
  340. if not package:
  341. return ret
  342. if is_import(ret):
  343. return ret
  344. return None
  345. _block_syms = {syms.funcdef, syms.classdef, syms.trailer}
  346. def _find(name, node):
  347. nodes = [node]
  348. while nodes:
  349. node = nodes.pop()
  350. if node.type > 256 and node.type not in _block_syms:
  351. nodes.extend(node.children)
  352. elif node.type == token.NAME and node.value == name:
  353. return node
  354. return None
  355. def _is_import_binding(node, name, package=None):
  356. """ Will return node if node will import name, or node
  357. will import * from package. None is returned otherwise.
  358. See test cases for examples. """
  359. if node.type == syms.import_name and not package:
  360. imp = node.children[1]
  361. if imp.type == syms.dotted_as_names:
  362. for child in imp.children:
  363. if child.type == syms.dotted_as_name:
  364. if child.children[2].value == name:
  365. return node
  366. elif child.type == token.NAME and child.value == name:
  367. return node
  368. elif imp.type == syms.dotted_as_name:
  369. last = imp.children[-1]
  370. if last.type == token.NAME and last.value == name:
  371. return node
  372. elif imp.type == token.NAME and imp.value == name:
  373. return node
  374. elif node.type == syms.import_from:
  375. # str(...) is used to make life easier here, because
  376. # from a.b import parses to ['import', ['a', '.', 'b'], ...]
  377. if package and str(node.children[1]).strip() != package:
  378. return None
  379. n = node.children[3]
  380. if package and _find("as", n):
  381. # See test_from_import_as for explanation
  382. return None
  383. elif n.type == syms.import_as_names and _find(name, n):
  384. return node
  385. elif n.type == syms.import_as_name:
  386. child = n.children[2]
  387. if child.type == token.NAME and child.value == name:
  388. return node
  389. elif n.type == token.NAME and n.value == name:
  390. return node
  391. elif package and n.type == token.STAR:
  392. return node
  393. return None