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