1 | # Copyright 2006 Google, Inc. All Rights Reserved.
|
---|
2 | # Licensed to PSF under a Contributor Agreement.
|
---|
3 |
|
---|
4 | """Fixer for apply().
|
---|
5 |
|
---|
6 | This converts apply(func, v, k) into (func)(*v, **k)."""
|
---|
7 |
|
---|
8 | # Local imports
|
---|
9 | from .. import pytree
|
---|
10 | from ..pgen2 import token
|
---|
11 | from .. import fixer_base
|
---|
12 | from ..fixer_util import Call, Comma, parenthesize
|
---|
13 |
|
---|
14 | class FixApply(fixer_base.BaseFix):
|
---|
15 | BM_compatible = True
|
---|
16 |
|
---|
17 | PATTERN = """
|
---|
18 | power< 'apply'
|
---|
19 | trailer<
|
---|
20 | '('
|
---|
21 | arglist<
|
---|
22 | (not argument<NAME '=' any>) func=any ','
|
---|
23 | (not argument<NAME '=' any>) args=any [','
|
---|
24 | (not argument<NAME '=' any>) kwds=any] [',']
|
---|
25 | >
|
---|
26 | ')'
|
---|
27 | >
|
---|
28 | >
|
---|
29 | """
|
---|
30 |
|
---|
31 | def transform(self, node, results):
|
---|
32 | syms = self.syms
|
---|
33 | assert results
|
---|
34 | func = results["func"]
|
---|
35 | args = results["args"]
|
---|
36 | kwds = results.get("kwds")
|
---|
37 | prefix = node.prefix
|
---|
38 | func = func.clone()
|
---|
39 | if (func.type not in (token.NAME, syms.atom) and
|
---|
40 | (func.type != syms.power or
|
---|
41 | func.children[-2].type == token.DOUBLESTAR)):
|
---|
42 | # Need to parenthesize
|
---|
43 | func = parenthesize(func)
|
---|
44 | func.prefix = ""
|
---|
45 | args = args.clone()
|
---|
46 | args.prefix = ""
|
---|
47 | if kwds is not None:
|
---|
48 | kwds = kwds.clone()
|
---|
49 | kwds.prefix = ""
|
---|
50 | l_newargs = [pytree.Leaf(token.STAR, u"*"), args]
|
---|
51 | if kwds is not None:
|
---|
52 | l_newargs.extend([Comma(),
|
---|
53 | pytree.Leaf(token.DOUBLESTAR, u"**"),
|
---|
54 | kwds])
|
---|
55 | l_newargs[-2].prefix = u" " # that's the ** token
|
---|
56 | # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t)
|
---|
57 | # can be translated into f(x, y, *t) instead of f(*(x, y) + t)
|
---|
58 | #new = pytree.Node(syms.power, (func, ArgList(l_newargs)))
|
---|
59 | return Call(func, l_newargs, prefix=prefix)
|
---|