fix_throw.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Fixer for generator.throw(E, V, T).
  2. g.throw(E) -> g.throw(E)
  3. g.throw(E, V) -> g.throw(E(V))
  4. g.throw(E, V, T) -> g.throw(E(V).with_traceback(T))
  5. g.throw("foo"[, V[, T]]) will warn about string exceptions."""
  6. # Author: Collin Winter
  7. # Local imports
  8. from .. import pytree
  9. from ..pgen2 import token
  10. from .. import fixer_base
  11. from ..fixer_util import Name, Call, ArgList, Attr, is_tuple
  12. class FixThrow(fixer_base.BaseFix):
  13. BM_compatible = True
  14. PATTERN = """
  15. power< any trailer< '.' 'throw' >
  16. trailer< '(' args=arglist< exc=any ',' val=any [',' tb=any] > ')' >
  17. >
  18. |
  19. power< any trailer< '.' 'throw' > trailer< '(' exc=any ')' > >
  20. """
  21. def transform(self, node, results):
  22. syms = self.syms
  23. exc = results["exc"].clone()
  24. if exc.type is token.STRING:
  25. self.cannot_convert(node, "Python 3 does not support string exceptions")
  26. return
  27. # Leave "g.throw(E)" alone
  28. val = results.get("val")
  29. if val is None:
  30. return
  31. val = val.clone()
  32. if is_tuple(val):
  33. args = [c.clone() for c in val.children[1:-1]]
  34. else:
  35. val.prefix = ""
  36. args = [val]
  37. throw_args = results["args"]
  38. if "tb" in results:
  39. tb = results["tb"].clone()
  40. tb.prefix = ""
  41. e = Call(exc, args)
  42. with_tb = Attr(e, Name('with_traceback')) + [ArgList([tb])]
  43. throw_args.replace(pytree.Node(syms.power, with_tb))
  44. else:
  45. throw_args.replace(Call(exc, args))