1# Copyright 2006 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Fixer for execfile.
5
6This converts usages of the execfile function into calls to the built-in
7exec() function.
8"""
9
10from .. import fixer_base
11from ..fixer_util import (Comma, Name, Call, LParen, RParen, Dot, Node,
12                          ArgList, String, syms)
13
14
15class FixExecfile(fixer_base.BaseFix):
16    BM_compatible = True
17
18    PATTERN = """
19    power< 'execfile' trailer< '(' arglist< filename=any [',' globals=any [',' locals=any ] ] > ')' > >
20    |
21    power< 'execfile' trailer< '(' filename=any ')' > >
22    """
23
24    def transform(self, node, results):
25        assert results
26        filename = results["filename"]
27        globals = results.get("globals")
28        locals = results.get("locals")
29
30        # Copy over the prefix from the right parentheses end of the execfile
31        # call.
32        execfile_paren = node.children[-1].children[-1].clone()
33        # Construct open().read().
34        open_args = ArgList([filename.clone()], rparen=execfile_paren)
35        open_call = Node(syms.power, [Name(u"open"), open_args])
36        read = [Node(syms.trailer, [Dot(), Name(u'read')]),
37                Node(syms.trailer, [LParen(), RParen()])]
38        open_expr = [open_call] + read
39        # Wrap the open call in a compile call. This is so the filename will be
40        # preserved in the execed code.
41        filename_arg = filename.clone()
42        filename_arg.prefix = u" "
43        exec_str = String(u"'exec'", u" ")
44        compile_args = open_expr + [Comma(), filename_arg, Comma(), exec_str]
45        compile_call = Call(Name(u"compile"), compile_args, u"")
46        # Finally, replace the execfile call with an exec call.
47        args = [compile_call]
48        if globals is not None:
49            args.extend([Comma(), globals.clone()])
50        if locals is not None:
51            args.extend([Comma(), locals.clone()])
52        return Call(Name(u"exec"), args, prefix=node.prefix)
53