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