+++ /dev/null
-# Copyright 2006 Google, Inc. All Rights Reserved.\r
-# Licensed to PSF under a Contributor Agreement.\r
-\r
-"""Fixer for print.\r
-\r
-Change:\r
- 'print' into 'print()'\r
- 'print ...' into 'print(...)'\r
- 'print ... ,' into 'print(..., end=" ")'\r
- 'print >>x, ...' into 'print(..., file=x)'\r
-\r
-No changes are applied if print_function is imported from __future__\r
-\r
-"""\r
-\r
-# Local imports\r
-from .. import patcomp\r
-from .. import pytree\r
-from ..pgen2 import token\r
-from .. import fixer_base\r
-from ..fixer_util import Name, Call, Comma, String, is_tuple\r
-\r
-\r
-parend_expr = patcomp.compile_pattern(\r
- """atom< '(' [atom|STRING|NAME] ')' >"""\r
- )\r
-\r
-\r
-class FixPrint(fixer_base.BaseFix):\r
-\r
- BM_compatible = True\r
-\r
- PATTERN = """\r
- simple_stmt< any* bare='print' any* > | print_stmt\r
- """\r
-\r
- def transform(self, node, results):\r
- assert results\r
-\r
- bare_print = results.get("bare")\r
-\r
- if bare_print:\r
- # Special-case print all by itself\r
- bare_print.replace(Call(Name(u"print"), [],\r
- prefix=bare_print.prefix))\r
- return\r
- assert node.children[0] == Name(u"print")\r
- args = node.children[1:]\r
- if len(args) == 1 and parend_expr.match(args[0]):\r
- # We don't want to keep sticking parens around an\r
- # already-parenthesised expression.\r
- return\r
-\r
- sep = end = file = None\r
- if args and args[-1] == Comma():\r
- args = args[:-1]\r
- end = " "\r
- if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, u">>"):\r
- assert len(args) >= 2\r
- file = args[1].clone()\r
- args = args[3:] # Strip a possible comma after the file expression\r
- # Now synthesize a print(args, sep=..., end=..., file=...) node.\r
- l_args = [arg.clone() for arg in args]\r
- if l_args:\r
- l_args[0].prefix = u""\r
- if sep is not None or end is not None or file is not None:\r
- if sep is not None:\r
- self.add_kwarg(l_args, u"sep", String(repr(sep)))\r
- if end is not None:\r
- self.add_kwarg(l_args, u"end", String(repr(end)))\r
- if file is not None:\r
- self.add_kwarg(l_args, u"file", file)\r
- n_stmt = Call(Name(u"print"), l_args)\r
- n_stmt.prefix = node.prefix\r
- return n_stmt\r
-\r
- def add_kwarg(self, l_nodes, s_kwd, n_expr):\r
- # XXX All this prefix-setting may lose comments (though rarely)\r
- n_expr.prefix = u""\r
- n_argument = pytree.Node(self.syms.argument,\r
- (Name(s_kwd),\r
- pytree.Leaf(token.EQUAL, u"="),\r
- n_expr))\r
- if l_nodes:\r
- l_nodes.append(Comma())\r
- n_argument.prefix = u" "\r
- l_nodes.append(n_argument)\r