fix_xrange.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Fixer that changes xrange(...) into range(...)."""
  4. # Local imports
  5. from .. import fixer_base
  6. from ..fixer_util import Name, Call, consuming_calls
  7. from .. import patcomp
  8. class FixXrange(fixer_base.BaseFix):
  9. BM_compatible = True
  10. PATTERN = """
  11. power<
  12. (name='range'|name='xrange') trailer< '(' args=any ')' >
  13. rest=any* >
  14. """
  15. def start_tree(self, tree, filename):
  16. super(FixXrange, self).start_tree(tree, filename)
  17. self.transformed_xranges = set()
  18. def finish_tree(self, tree, filename):
  19. self.transformed_xranges = None
  20. def transform(self, node, results):
  21. name = results["name"]
  22. if name.value == "xrange":
  23. return self.transform_xrange(node, results)
  24. elif name.value == "range":
  25. return self.transform_range(node, results)
  26. else:
  27. raise ValueError(repr(name))
  28. def transform_xrange(self, node, results):
  29. name = results["name"]
  30. name.replace(Name("range", prefix=name.prefix))
  31. # This prevents the new range call from being wrapped in a list later.
  32. self.transformed_xranges.add(id(node))
  33. def transform_range(self, node, results):
  34. if (id(node) not in self.transformed_xranges and
  35. not self.in_special_context(node)):
  36. range_call = Call(Name("range"), [results["args"].clone()])
  37. # Encase the range call in list().
  38. list_call = Call(Name("list"), [range_call],
  39. prefix=node.prefix)
  40. # Put things that were after the range() call after the list call.
  41. for n in results["rest"]:
  42. list_call.append_child(n)
  43. return list_call
  44. P1 = "power< func=NAME trailer< '(' node=any ')' > any* >"
  45. p1 = patcomp.compile_pattern(P1)
  46. P2 = """for_stmt< 'for' any 'in' node=any ':' any* >
  47. | comp_for< 'for' any 'in' node=any any* >
  48. | comparison< any 'in' node=any any*>
  49. """
  50. p2 = patcomp.compile_pattern(P2)
  51. def in_special_context(self, node):
  52. if node.parent is None:
  53. return False
  54. results = {}
  55. if (node.parent.parent is not None and
  56. self.p1.match(node.parent.parent, results) and
  57. results["node"] is node):
  58. # list(d.keys()) -> list(d.keys()), etc.
  59. return results["func"].value in consuming_calls
  60. # for ... in d.iterkeys() -> for ... in d.keys(), etc.
  61. return self.p2.match(node.parent, results) and results["node"] is node