1# Copyright 2006 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Fixer for apply().
5
6This converts apply(func, v, k) into (func)(*v, **k)."""
7
8# Local imports
9from .. import pytree
10from ..pgen2 import token
11from .. import fixer_base
12from ..fixer_util import Call, Comma, parenthesize
13
14class 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        # I feel like we should be able to express this logic in the
38        # PATTERN above but I don't know how to do it so...
39        if args:
40            if args.type == self.syms.star_expr:
41                return  # Make no change.
42            if (args.type == self.syms.argument and
43                args.children[0].value == '**'):
44                return  # Make no change.
45        if kwds and (kwds.type == self.syms.argument and
46                     kwds.children[0].value == '**'):
47            return  # Make no change.
48        prefix = node.prefix
49        func = func.clone()
50        if (func.type not in (token.NAME, syms.atom) and
51            (func.type != syms.power or
52             func.children[-2].type == token.DOUBLESTAR)):
53            # Need to parenthesize
54            func = parenthesize(func)
55        func.prefix = ""
56        args = args.clone()
57        args.prefix = ""
58        if kwds is not None:
59            kwds = kwds.clone()
60            kwds.prefix = ""
61        l_newargs = [pytree.Leaf(token.STAR, u"*"), args]
62        if kwds is not None:
63            l_newargs.extend([Comma(),
64                              pytree.Leaf(token.DOUBLESTAR, u"**"),
65                              kwds])
66            l_newargs[-2].prefix = u" " # that's the ** token
67        # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t)
68        # can be translated into f(x, y, *t) instead of f(*(x, y) + t)
69        #new = pytree.Node(syms.power, (func, ArgList(l_newargs)))
70        return Call(func, l_newargs, prefix=prefix)
71