fix_unpacking.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. u"""
  2. Fixer for:
  3. (a,)* *b (,c)* [,] = s
  4. for (a,)* *b (,c)* [,] in d: ...
  5. """
  6. from lib2to3 import fixer_base
  7. from itertools import count
  8. from lib2to3.fixer_util import (Assign, Comma, Call, Newline, Name,
  9. Number, token, syms, Node, Leaf)
  10. from libfuturize.fixer_util import indentation, suitify, commatize
  11. # from libfuturize.fixer_util import Assign, Comma, Call, Newline, Name, Number, indentation, suitify, commatize, token, syms, Node, Leaf
  12. def assignment_source(num_pre, num_post, LISTNAME, ITERNAME):
  13. u"""
  14. Accepts num_pre and num_post, which are counts of values
  15. before and after the starg (not including the starg)
  16. Returns a source fit for Assign() from fixer_util
  17. """
  18. children = []
  19. pre = unicode(num_pre)
  20. post = unicode(num_post)
  21. # This code builds the assignment source from lib2to3 tree primitives.
  22. # It's not very readable, but it seems like the most correct way to do it.
  23. if num_pre > 0:
  24. pre_part = Node(syms.power, [Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Leaf(token.COLON, u":"), Number(pre)]), Leaf(token.RSQB, u"]")])])
  25. children.append(pre_part)
  26. children.append(Leaf(token.PLUS, u"+", prefix=u" "))
  27. main_part = Node(syms.power, [Leaf(token.LSQB, u"[", prefix=u" "), Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Number(pre) if num_pre > 0 else Leaf(1, u""), Leaf(token.COLON, u":"), Node(syms.factor, [Leaf(token.MINUS, u"-"), Number(post)]) if num_post > 0 else Leaf(1, u"")]), Leaf(token.RSQB, u"]"), Leaf(token.RSQB, u"]")])])
  28. children.append(main_part)
  29. if num_post > 0:
  30. children.append(Leaf(token.PLUS, u"+", prefix=u" "))
  31. post_part = Node(syms.power, [Name(LISTNAME, prefix=u" "), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Node(syms.factor, [Leaf(token.MINUS, u"-"), Number(post)]), Leaf(token.COLON, u":")]), Leaf(token.RSQB, u"]")])])
  32. children.append(post_part)
  33. source = Node(syms.arith_expr, children)
  34. return source
  35. class FixUnpacking(fixer_base.BaseFix):
  36. PATTERN = u"""
  37. expl=expr_stmt< testlist_star_expr<
  38. pre=(any ',')*
  39. star_expr< '*' name=NAME >
  40. post=(',' any)* [','] > '=' source=any > |
  41. impl=for_stmt< 'for' lst=exprlist<
  42. pre=(any ',')*
  43. star_expr< '*' name=NAME >
  44. post=(',' any)* [','] > 'in' it=any ':' suite=any>"""
  45. def fix_explicit_context(self, node, results):
  46. pre, name, post, source = (results.get(n) for n in (u"pre", u"name", u"post", u"source"))
  47. pre = [n.clone() for n in pre if n.type == token.NAME]
  48. name.prefix = u" "
  49. post = [n.clone() for n in post if n.type == token.NAME]
  50. target = [n.clone() for n in commatize(pre + [name.clone()] + post)]
  51. # to make the special-case fix for "*z, = ..." correct with the least
  52. # amount of modification, make the left-side into a guaranteed tuple
  53. target.append(Comma())
  54. source.prefix = u""
  55. setup_line = Assign(Name(self.LISTNAME), Call(Name(u"list"), [source.clone()]))
  56. power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME))
  57. return setup_line, power_line
  58. def fix_implicit_context(self, node, results):
  59. u"""
  60. Only example of the implicit context is
  61. a for loop, so only fix that.
  62. """
  63. pre, name, post, it = (results.get(n) for n in (u"pre", u"name", u"post", u"it"))
  64. pre = [n.clone() for n in pre if n.type == token.NAME]
  65. name.prefix = u" "
  66. post = [n.clone() for n in post if n.type == token.NAME]
  67. target = [n.clone() for n in commatize(pre + [name.clone()] + post)]
  68. # to make the special-case fix for "*z, = ..." correct with the least
  69. # amount of modification, make the left-side into a guaranteed tuple
  70. target.append(Comma())
  71. source = it.clone()
  72. source.prefix = u""
  73. setup_line = Assign(Name(self.LISTNAME), Call(Name(u"list"), [Name(self.ITERNAME)]))
  74. power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME))
  75. return setup_line, power_line
  76. def transform(self, node, results):
  77. u"""
  78. a,b,c,d,e,f,*g,h,i = range(100) changes to
  79. _3to2list = list(range(100))
  80. a,b,c,d,e,f,g,h,i, = _3to2list[:6] + [_3to2list[6:-2]] + _3to2list[-2:]
  81. and
  82. for a,b,*c,d,e in iter_of_iters: do_stuff changes to
  83. for _3to2iter in iter_of_iters:
  84. _3to2list = list(_3to2iter)
  85. a,b,c,d,e, = _3to2list[:2] + [_3to2list[2:-2]] + _3to2list[-2:]
  86. do_stuff
  87. """
  88. self.LISTNAME = self.new_name(u"_3to2list")
  89. self.ITERNAME = self.new_name(u"_3to2iter")
  90. expl, impl = results.get(u"expl"), results.get(u"impl")
  91. if expl is not None:
  92. setup_line, power_line = self.fix_explicit_context(node, results)
  93. setup_line.prefix = expl.prefix
  94. power_line.prefix = indentation(expl.parent)
  95. setup_line.append_child(Newline())
  96. parent = node.parent
  97. i = node.remove()
  98. parent.insert_child(i, power_line)
  99. parent.insert_child(i, setup_line)
  100. elif impl is not None:
  101. setup_line, power_line = self.fix_implicit_context(node, results)
  102. suitify(node)
  103. suite = [k for k in node.children if k.type == syms.suite][0]
  104. setup_line.prefix = u""
  105. power_line.prefix = suite.children[1].value
  106. suite.children[2].prefix = indentation(suite.children[2])
  107. suite.insert_child(2, Newline())
  108. suite.insert_child(2, power_line)
  109. suite.insert_child(2, Newline())
  110. suite.insert_child(2, setup_line)
  111. results.get(u"lst").replace(Name(self.ITERNAME, prefix=u" "))