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