# Copyright (c) 2014-2021, Simon Percivall and Spack Project Developers.
#
# SPDX-License-Identifier: Python-2.0
"Usage: unparse.py <path to source file>"
from __future__ import print_function, unicode_literals
import ast
import sys
from contextlib import contextmanager
import six
from six import StringIO
# TODO: if we require Python 3.7, use its `nullcontext()`
[docs]@contextmanager
def nullcontext():
yield
# Large float and imaginary literals get turned into infinities in the AST.
# We unparse those infinities to INFSTR.
INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1)
class _Precedence:
"""Precedence table that originated from python grammar."""
TUPLE = 0
YIELD = 1 # 'yield', 'yield from'
TEST = 2 # 'if'-'else', 'lambda'
OR = 3 # 'or'
AND = 4 # 'and'
NOT = 5 # 'not'
CMP = 6 # '<', '>', '==', '>=', '<=', '!=', 'in', 'not in', 'is', 'is not'
EXPR = 7
BOR = EXPR # '|'
BXOR = 8 # '^'
BAND = 9 # '&'
SHIFT = 10 # '<<', '>>'
ARITH = 11 # '+', '-'
TERM = 12 # '*', '@', '/', '%', '//'
FACTOR = 13 # unary '+', '-', '~'
POWER = 14 # '**'
AWAIT = 15 # 'await'
ATOM = 16
[docs]def pnext(precedence):
return min(precedence + 1, _Precedence.ATOM)
[docs]def interleave(inter, f, seq):
"""Call f on each item in seq, calling inter() in between.
"""
seq = iter(seq)
try:
f(next(seq))
except StopIteration:
pass
else:
for x in seq:
inter()
f(x)
_SINGLE_QUOTES = ("'", '"')
_MULTI_QUOTES = ('"""', "'''")
_ALL_QUOTES = _SINGLE_QUOTES + _MULTI_QUOTES
[docs]def is_simple_tuple(slice_value):
# when unparsing a non-empty tuple, the parantheses can be safely
# omitted if there aren't any elements that explicitly requires
# parantheses (such as starred expressions).
return (
isinstance(slice_value, ast.Tuple)
and slice_value.elts
and (
# Python 2 doesn't allow starred elements in tuples like Python 3
six.PY2 or not any(
isinstance(elt, ast.Starred) for elt in slice_value.elts
)
)
)
[docs]class Unparser:
"""Methods in this class recursively traverse an AST and
output source code for the abstract syntax; original formatting
is disregarded. """
def __init__(self, py_ver_consistent=False, _avoid_backslashes=False):
"""Traverse an AST and generate its source.
Arguments:
py_ver_consistent (bool): if True, generate unparsed code that is
consistent between Python 2.7 and 3.5-3.10.
Consistency is achieved by:
1. Ensuring that *args and **kwargs are always the last arguments,
regardless of the python version, because Python 2's AST does not
have sufficient information to reconstruct star-arg order.
2. Always unparsing print as a function.
3. Unparsing Python3 unicode literals the way Python 2 would.
Without these changes, the same source can generate different code for Python 2
and Python 3, depending on subtle AST differences. The first of these two
causes this module to behave differently from Python 3.8+'s `ast.unparse()`
One place where single source will generate an inconsistent AST is with
multi-argument print statements, e.g.::
print("foo", "bar", "baz")
In Python 2, this prints a tuple; in Python 3, it is the print function with
multiple arguments. Use ``from __future__ import print_function`` to avoid
this inconsistency.
"""
self.future_imports = []
self._indent = 0
self._py_ver_consistent = py_ver_consistent
self._precedences = {}
self._avoid_backslashes = _avoid_backslashes
[docs] def items_view(self, traverser, items):
"""Traverse and separate the given *items* with a comma and append it to
the buffer. If *items* is a single item sequence, a trailing comma
will be added."""
if len(items) == 1:
traverser(items[0])
self.write(",")
else:
interleave(lambda: self.write(", "), traverser, items)
[docs] def visit(self, tree, output_file):
"""Traverse tree and write source code to output_file."""
self.f = output_file
self.dispatch(tree)
self.f.flush()
[docs] def fill(self, text=""):
"Indent a piece of text, according to the current indentation level"
self.f.write("\n" + " " * self._indent + text)
[docs] def write(self, text):
"Append a piece of text to the current line."
self.f.write(six.text_type(text))
class _Block:
"""A context manager for preparing the source for blocks. It adds
the character ':', increases the indentation on enter and decreases
the indentation on exit."""
def __init__(self, unparser):
self.unparser = unparser
def __enter__(self):
self.unparser.write(":")
self.unparser._indent += 1
def __exit__(self, exc_type, exc_value, traceback):
self.unparser._indent -= 1
[docs] def block(self):
return self._Block(self)
[docs] @contextmanager
def delimit(self, start, end):
"""A context manager for preparing the source for expressions. It adds
*start* to the buffer and enters, after exit it adds *end*."""
self.write(start)
yield
self.write(end)
[docs] def delimit_if(self, start, end, condition):
if condition:
return self.delimit(start, end)
else:
return nullcontext()
[docs] def require_parens(self, precedence, node):
"""Shortcut to adding precedence related parens"""
return self.delimit_if("(", ")", self.get_precedence(node) > precedence)
[docs] def get_precedence(self, node):
return self._precedences.get(node, _Precedence.TEST)
[docs] def set_precedence(self, precedence, *nodes):
for node in nodes:
self._precedences[node] = precedence
[docs] def dispatch(self, tree):
"Dispatcher function, dispatching tree type T to method _T."
if isinstance(tree, list):
for node in tree:
self.dispatch(node)
return
meth = getattr(self, "visit_" + tree.__class__.__name__)
meth(tree)
#
# Unparsing methods
#
# There should be one method per concrete grammar type Constructors
# should be # grouped by sum type. Ideally, this would follow the order
# in the grammar, but currently doesn't.
[docs] def visit_Module(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
[docs] def visit_Interactive(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
[docs] def visit_Expression(self, tree):
self.dispatch(tree.body)
# stmt
[docs] def visit_Expr(self, tree):
self.fill()
self.set_precedence(_Precedence.YIELD, tree.value)
self.dispatch(tree.value)
[docs] def visit_NamedExpr(self, tree):
with self.require_parens(_Precedence.TUPLE, tree):
self.set_precedence(_Precedence.ATOM, tree.target, tree.value)
self.dispatch(tree.target)
self.write(" := ")
self.dispatch(tree.value)
[docs] def visit_Import(self, node):
self.fill("import ")
interleave(lambda: self.write(", "), self.dispatch, node.names)
[docs] def visit_ImportFrom(self, node):
# A from __future__ import may affect unparsing, so record it.
if node.module and node.module == '__future__':
self.future_imports.extend(n.name for n in node.names)
self.fill("from ")
self.write("." * node.level)
if node.module:
self.write(node.module)
self.write(" import ")
interleave(lambda: self.write(", "), self.dispatch, node.names)
[docs] def visit_Assign(self, node):
self.fill()
for target in node.targets:
self.dispatch(target)
self.write(" = ")
self.dispatch(node.value)
[docs] def visit_AugAssign(self, node):
self.fill()
self.dispatch(node.target)
self.write(" " + self.binop[node.op.__class__.__name__] + "= ")
self.dispatch(node.value)
[docs] def visit_AnnAssign(self, node):
self.fill()
with self.delimit_if(
"(", ")", not node.simple and isinstance(node.target, ast.Name)):
self.dispatch(node.target)
self.write(": ")
self.dispatch(node.annotation)
if node.value:
self.write(" = ")
self.dispatch(node.value)
[docs] def visit_Return(self, node):
self.fill("return")
if node.value:
self.write(" ")
self.dispatch(node.value)
[docs] def visit_Pass(self, node):
self.fill("pass")
[docs] def visit_Break(self, node):
self.fill("break")
[docs] def visit_Continue(self, node):
self.fill("continue")
[docs] def visit_Delete(self, node):
self.fill("del ")
interleave(lambda: self.write(", "), self.dispatch, node.targets)
[docs] def visit_Assert(self, node):
self.fill("assert ")
self.dispatch(node.test)
if node.msg:
self.write(", ")
self.dispatch(node.msg)
[docs] def visit_Exec(self, node):
self.fill("exec ")
self.dispatch(node.body)
if node.globals:
self.write(" in ")
self.dispatch(node.globals)
if node.locals:
self.write(", ")
self.dispatch(node.locals)
[docs] def visit_Print(self, node):
# Use print function so that python 2 unparsing is consistent with 3
if self._py_ver_consistent:
self.fill("print")
with self.delimit("(", ")"):
values = node.values
# Can't tell print(foo, bar, baz) and print((foo, bar, baz)) apart in
# python 2 and 3, so treat them the same to make hashes consistent.
# Single-tuple print are rare and unlikely to affect package hashes,
# esp. as they likely print to stdout.
if len(values) == 1 and isinstance(values[0], ast.Tuple):
values = node.values[0].elts
do_comma = False
for e in values:
if do_comma:
self.write(", ")
else:
do_comma = True
self.dispatch(e)
if not node.nl:
if do_comma:
self.write(", ")
else:
do_comma = True
self.write("end=''")
if node.dest:
if do_comma:
self.write(", ")
else:
do_comma = True
self.write("file=")
self.dispatch(node.dest)
else:
# unparse Python 2 print statements
self.fill("print ")
do_comma = False
if node.dest:
self.write(">>")
self.dispatch(node.dest)
do_comma = True
for e in node.values:
if do_comma:
self.write(", ")
else:
do_comma = True
self.dispatch(e)
if not node.nl:
self.write(",")
[docs] def visit_Global(self, node):
self.fill("global ")
interleave(lambda: self.write(", "), self.write, node.names)
[docs] def visit_Nonlocal(self, node):
self.fill("nonlocal ")
interleave(lambda: self.write(", "), self.write, node.names)
[docs] def visit_Await(self, node):
with self.require_parens(_Precedence.AWAIT, node):
self.write("await")
if node.value:
self.write(" ")
self.set_precedence(_Precedence.ATOM, node.value)
self.dispatch(node.value)
[docs] def visit_Yield(self, node):
with self.require_parens(_Precedence.YIELD, node):
self.write("yield")
if node.value:
self.write(" ")
self.set_precedence(_Precedence.ATOM, node.value)
self.dispatch(node.value)
[docs] def visit_YieldFrom(self, node):
with self.require_parens(_Precedence.YIELD, node):
self.write("yield from")
if node.value:
self.write(" ")
self.set_precedence(_Precedence.ATOM, node.value)
self.dispatch(node.value)
[docs] def visit_Raise(self, node):
self.fill("raise")
if six.PY3:
if not node.exc:
assert not node.cause
return
self.write(" ")
self.dispatch(node.exc)
if node.cause:
self.write(" from ")
self.dispatch(node.cause)
else:
self.write(" ")
if node.type:
self.dispatch(node.type)
if node.inst:
self.write(", ")
self.dispatch(node.inst)
if node.tback:
self.write(", ")
self.dispatch(node.tback)
[docs] def visit_Try(self, node):
self.fill("try")
with self.block():
self.dispatch(node.body)
for ex in node.handlers:
self.dispatch(ex)
if node.orelse:
self.fill("else")
with self.block():
self.dispatch(node.orelse)
if node.finalbody:
self.fill("finally")
with self.block():
self.dispatch(node.finalbody)
[docs] def visit_TryExcept(self, node):
self.fill("try")
with self.block():
self.dispatch(node.body)
for ex in node.handlers:
self.dispatch(ex)
if node.orelse:
self.fill("else")
with self.block():
self.dispatch(node.orelse)
[docs] def visit_TryFinally(self, node):
if len(node.body) == 1 and isinstance(node.body[0], ast.TryExcept):
# try-except-finally
self.dispatch(node.body)
else:
self.fill("try")
with self.block():
self.dispatch(node.body)
self.fill("finally")
with self.block():
self.dispatch(node.finalbody)
[docs] def visit_ExceptHandler(self, node):
self.fill("except")
if node.type:
self.write(" ")
self.dispatch(node.type)
if node.name:
self.write(" as ")
if six.PY3:
self.write(node.name)
else:
self.dispatch(node.name)
with self.block():
self.dispatch(node.body)
[docs] def visit_ClassDef(self, node):
self.write("\n")
for deco in node.decorator_list:
self.fill("@")
self.dispatch(deco)
self.fill("class " + node.name)
if six.PY3:
with self.delimit_if("(", ")", condition=node.bases or node.keywords):
comma = False
for e in node.bases:
if comma:
self.write(", ")
else:
comma = True
self.dispatch(e)
for e in node.keywords:
if comma:
self.write(", ")
else:
comma = True
self.dispatch(e)
if sys.version_info[:2] < (3, 5):
if node.starargs:
if comma:
self.write(", ")
else:
comma = True
self.write("*")
self.dispatch(node.starargs)
if node.kwargs:
if comma:
self.write(", ")
else:
comma = True
self.write("**")
self.dispatch(node.kwargs)
elif node.bases:
with self.delimit("(", ")"):
for a in node.bases[:-1]:
self.dispatch(a)
self.write(", ")
self.dispatch(node.bases[-1])
with self.block():
self.dispatch(node.body)
[docs] def visit_FunctionDef(self, node):
self.__FunctionDef_helper(node, "def")
[docs] def visit_AsyncFunctionDef(self, node):
self.__FunctionDef_helper(node, "async def")
def __FunctionDef_helper(self, node, fill_suffix):
self.write("\n")
for deco in node.decorator_list:
self.fill("@")
self.dispatch(deco)
def_str = fill_suffix + " " + node.name
self.fill(def_str)
with self.delimit("(", ")"):
self.dispatch(node.args)
if getattr(node, "returns", False):
self.write(" -> ")
self.dispatch(node.returns)
with self.block():
self.dispatch(node.body)
[docs] def visit_For(self, node):
self.__For_helper("for ", node)
[docs] def visit_AsyncFor(self, node):
self.__For_helper("async for ", node)
def __For_helper(self, fill, node):
self.fill(fill)
self.dispatch(node.target)
self.write(" in ")
self.dispatch(node.iter)
with self.block():
self.dispatch(node.body)
if node.orelse:
self.fill("else")
with self.block():
self.dispatch(node.orelse)
[docs] def visit_If(self, node):
self.fill("if ")
self.dispatch(node.test)
with self.block():
self.dispatch(node.body)
# collapse nested ifs into equivalent elifs.
while (node.orelse and len(node.orelse) == 1 and
isinstance(node.orelse[0], ast.If)):
node = node.orelse[0]
self.fill("elif ")
self.dispatch(node.test)
with self.block():
self.dispatch(node.body)
# final else
if node.orelse:
self.fill("else")
with self.block():
self.dispatch(node.orelse)
[docs] def visit_While(self, node):
self.fill("while ")
self.dispatch(node.test)
with self.block():
self.dispatch(node.body)
if node.orelse:
self.fill("else")
with self.block():
self.dispatch(node.orelse)
def _generic_With(self, node, async_=False):
self.fill("async with " if async_ else "with ")
if hasattr(node, 'items'):
interleave(lambda: self.write(", "), self.dispatch, node.items)
else:
self.dispatch(node.context_expr)
if node.optional_vars:
self.write(" as ")
self.dispatch(node.optional_vars)
with self.block():
self.dispatch(node.body)
[docs] def visit_With(self, node):
self._generic_With(node)
[docs] def visit_AsyncWith(self, node):
self._generic_With(node, async_=True)
def _str_literal_helper(
self, string, quote_types=_ALL_QUOTES, escape_special_whitespace=False
):
"""Helper for writing string literals, minimizing escapes.
Returns the tuple (string literal to write, possible quote types).
"""
def escape_char(c):
# \n and \t are non-printable, but we only escape them if
# escape_special_whitespace is True
if not escape_special_whitespace and c in "\n\t":
return c
# Always escape backslashes and other non-printable characters
if c == "\\" or not c.isprintable():
return c.encode("unicode_escape").decode("ascii")
return c
escaped_string = "".join(map(escape_char, string))
possible_quotes = quote_types
if "\n" in escaped_string:
possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES]
possible_quotes = [q for q in possible_quotes if q not in escaped_string]
if not possible_quotes:
# If there aren't any possible_quotes, fallback to using repr
# on the original string. Try to use a quote from quote_types,
# e.g., so that we use triple quotes for docstrings.
string = repr(string)
quote = next((q for q in quote_types if string[0] in q), string[0])
return string[1:-1], [quote]
if escaped_string:
# Sort so that we prefer '''"''' over """\""""
possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1])
# If we're using triple quotes and we'd need to escape a final
# quote, escape it
if possible_quotes[0][0] == escaped_string[-1]:
assert len(possible_quotes[0]) == 3
escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1]
return escaped_string, possible_quotes
def _write_str_avoiding_backslashes(self, string, quote_types=_ALL_QUOTES):
"""Write string literal value w/a best effort attempt to avoid backslashes."""
string, quote_types = self._str_literal_helper(string, quote_types=quote_types)
quote_type = quote_types[0]
self.write("{quote_type}{string}{quote_type}".format(
quote_type=quote_type,
string=string,
))
# expr
[docs] def visit_Bytes(self, node):
self.write(repr(node.s))
[docs] def visit_Str(self, tree):
if six.PY3:
# Python 3.5, 3.6, and 3.7 can't tell if something was written as a
# unicode constant. Try to make that consistent with 'u' for '\u- literals
if self._py_ver_consistent and repr(tree.s).startswith("'\\u"):
self.write("u")
self._write_constant(tree.s)
elif self._py_ver_consistent:
self.write(repr(tree.s)) # just do a python 2 repr for consistency
else:
# if from __future__ import unicode_literals is in effect,
# then we want to output string literals using a 'b' prefix
# and unicode literals with no prefix.
if "unicode_literals" not in self.future_imports:
self.write(repr(tree.s))
elif isinstance(tree.s, str):
self.write("b" + repr(tree.s))
elif isinstance(tree.s, unicode): # noqa
self.write(repr(tree.s).lstrip("u"))
else:
assert False, "shouldn't get here"
[docs] def visit_JoinedStr(self, node):
# JoinedStr(expr* values)
self.write("f")
if self._avoid_backslashes:
string = StringIO()
self._fstring_JoinedStr(node, string.write)
self._write_str_avoiding_backslashes(string.getvalue())
return
# If we don't need to avoid backslashes globally (i.e., we only need
# to avoid them inside FormattedValues), it's cosmetically preferred
# to use escaped whitespace. That is, it's preferred to use backslashes
# for cases like: f"{x}\n". To accomplish this, we keep track of what
# in our buffer corresponds to FormattedValues and what corresponds to
# Constant parts of the f-string, and allow escapes accordingly.
buffer = []
for value in node.values:
meth = getattr(self, "_fstring_" + type(value).__name__)
string = StringIO()
meth(value, string.write)
buffer.append((string.getvalue(), isinstance(value, ast.Constant)))
new_buffer = []
quote_types = _ALL_QUOTES
for value, is_constant in buffer:
# Repeatedly narrow down the list of possible quote_types
value, quote_types = self._str_literal_helper(
value, quote_types=quote_types,
escape_special_whitespace=is_constant
)
new_buffer.append(value)
value = "".join(new_buffer)
quote_type = quote_types[0]
self.write("{quote_type}{value}{quote_type}".format(
quote_type=quote_type,
value=value,
))
def _fstring_JoinedStr(self, node, write):
for value in node.values:
print(" ", value)
meth = getattr(self, "_fstring_" + type(value).__name__)
print(meth)
meth(value, write)
def _fstring_Str(self, node, write):
value = node.s.replace("{", "{{").replace("}", "}}")
write(value)
def _fstring_Constant(self, node, write):
assert isinstance(node.value, str)
value = node.value.replace("{", "{{").replace("}", "}}")
write(value)
def _fstring_FormattedValue(self, node, write):
write("{")
expr = StringIO()
unparser = type(self)(
py_ver_consistent=self._py_ver_consistent,
_avoid_backslashes=True,
)
unparser.set_precedence(pnext(_Precedence.TEST), node.value)
unparser.visit(node.value, expr)
expr = expr.getvalue().rstrip("\n")
if expr.startswith("{"):
write(" ") # Separate pair of opening brackets as "{ {"
if "\\" in expr:
raise ValueError("Unable to avoid backslash in f-string expression part")
write(expr)
if node.conversion != -1:
conversion = chr(node.conversion)
assert conversion in "sra"
write("!{conversion}".format(conversion=conversion))
if node.format_spec:
write(":")
meth = getattr(self, "_fstring_" + type(node.format_spec).__name__)
meth(node.format_spec, write)
write("}")
[docs] def visit_Name(self, node):
self.write(node.id)
[docs] def visit_NameConstant(self, node):
self.write(repr(node.value))
[docs] def visit_Repr(self, node):
self.write("`")
self.dispatch(node.value)
self.write("`")
def _write_constant(self, value):
if isinstance(value, (float, complex)):
# Substitute overflowing decimal literal for AST infinities.
self.write(repr(value).replace("inf", INFSTR))
elif isinstance(value, str) and self._py_ver_consistent:
# emulate a python 2 repr with raw unicode escapes
# see _Str for python 2 counterpart
raw = repr(value.encode("raw_unicode_escape")).lstrip('b')
if raw.startswith(r"'\\u"):
raw = "'\\" + raw[3:]
self.write(raw)
elif self._avoid_backslashes and isinstance(value, str):
self._write_str_avoiding_backslashes(value)
else:
self.write(repr(value))
[docs] def visit_Constant(self, node):
value = node.value
if isinstance(value, tuple):
with self.delimit("(", ")"):
self.items_view(self._write_constant, value)
elif value is Ellipsis: # instead of `...` for Py2 compatibility
self.write("...")
else:
if node.kind == "u":
self.write("u")
self._write_constant(node.value)
[docs] def visit_Num(self, node):
repr_n = repr(node.n)
if six.PY3:
self.write(repr_n.replace("inf", INFSTR))
else:
# Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2.
with self.require_parens(pnext(_Precedence.FACTOR), node):
if "inf" in repr_n and repr_n.endswith("*j"):
repr_n = repr_n.replace("*j", "j")
# Substitute overflowing decimal literal for AST infinities.
self.write(repr_n.replace("inf", INFSTR))
[docs] def visit_List(self, node):
with self.delimit("[", "]"):
interleave(lambda: self.write(", "), self.dispatch, node.elts)
[docs] def visit_ListComp(self, node):
with self.delimit("[", "]"):
self.dispatch(node.elt)
for gen in node.generators:
self.dispatch(gen)
[docs] def visit_GeneratorExp(self, node):
with self.delimit("(", ")"):
self.dispatch(node.elt)
for gen in node.generators:
self.dispatch(gen)
[docs] def visit_SetComp(self, node):
with self.delimit("{", "}"):
self.dispatch(node.elt)
for gen in node.generators:
self.dispatch(gen)
[docs] def visit_DictComp(self, node):
with self.delimit("{", "}"):
self.dispatch(node.key)
self.write(": ")
self.dispatch(node.value)
for gen in node.generators:
self.dispatch(gen)
[docs] def visit_comprehension(self, node):
if getattr(node, 'is_async', False):
self.write(" async for ")
else:
self.write(" for ")
self.set_precedence(_Precedence.TUPLE, node.target)
self.dispatch(node.target)
self.write(" in ")
self.set_precedence(pnext(_Precedence.TEST), node.iter, *node.ifs)
self.dispatch(node.iter)
for if_clause in node.ifs:
self.write(" if ")
self.dispatch(if_clause)
[docs] def visit_IfExp(self, node):
with self.require_parens(_Precedence.TEST, node):
self.set_precedence(pnext(_Precedence.TEST), node.body, node.test)
self.dispatch(node.body)
self.write(" if ")
self.dispatch(node.test)
self.write(" else ")
self.set_precedence(_Precedence.TEST, node.orelse)
self.dispatch(node.orelse)
[docs] def visit_Set(self, node):
assert(node.elts) # should be at least one element
with self.delimit("{", "}"):
interleave(lambda: self.write(", "), self.dispatch, node.elts)
[docs] def visit_Dict(self, node):
def write_key_value_pair(k, v):
self.dispatch(k)
self.write(": ")
self.dispatch(v)
def write_item(item):
k, v = item
if k is None:
# for dictionary unpacking operator in dicts {**{'y': 2}}
# see PEP 448 for details
self.write("**")
self.set_precedence(_Precedence.EXPR, v)
self.dispatch(v)
else:
write_key_value_pair(k, v)
with self.delimit("{", "}"):
interleave(
lambda: self.write(", "),
write_item,
zip(node.keys, node.values)
)
[docs] def visit_Tuple(self, node):
with self.delimit("(", ")"):
self.items_view(self.dispatch, node.elts)
unop = {
"Invert": "~",
"Not": "not",
"UAdd": "+",
"USub": "-"
}
unop_precedence = {
"~": _Precedence.FACTOR,
"not": _Precedence.NOT,
"+": _Precedence.FACTOR,
"-": _Precedence.FACTOR,
}
[docs] def visit_UnaryOp(self, node):
operator = self.unop[node.op.__class__.__name__]
operator_precedence = self.unop_precedence[operator]
with self.require_parens(operator_precedence, node):
self.write(operator)
# factor prefixes (+, -, ~) shouldn't be separated
# from the value they belong, (e.g: +1 instead of + 1)
if operator_precedence != _Precedence.FACTOR:
self.write(" ")
self.set_precedence(operator_precedence, node.operand)
if (six.PY2 and
isinstance(node.op, ast.USub) and isinstance(node.operand, ast.Num)):
# If we're applying unary minus to a number, parenthesize the number.
# This is necessary: -2147483648 is different from -(2147483648) on
# a 32-bit machine (the first is an int, the second a long), and
# -7j is different from -(7j). (The first has real part 0.0, the second
# has real part -0.0.)
with self.delimit("(", ")"):
self.dispatch(node.operand)
else:
self.dispatch(node.operand)
binop = {
"Add": "+",
"Sub": "-",
"Mult": "*",
"MatMult": "@",
"Div": "/",
"Mod": "%",
"LShift": "<<",
"RShift": ">>",
"BitOr": "|",
"BitXor": "^",
"BitAnd": "&",
"FloorDiv": "//",
"Pow": "**",
}
binop_precedence = {
"+": _Precedence.ARITH,
"-": _Precedence.ARITH,
"*": _Precedence.TERM,
"@": _Precedence.TERM,
"/": _Precedence.TERM,
"%": _Precedence.TERM,
"<<": _Precedence.SHIFT,
">>": _Precedence.SHIFT,
"|": _Precedence.BOR,
"^": _Precedence.BXOR,
"&": _Precedence.BAND,
"//": _Precedence.TERM,
"**": _Precedence.POWER,
}
binop_rassoc = frozenset(("**",))
[docs] def visit_BinOp(self, node):
operator = self.binop[node.op.__class__.__name__]
operator_precedence = self.binop_precedence[operator]
with self.require_parens(operator_precedence, node):
if operator in self.binop_rassoc:
left_precedence = pnext(operator_precedence)
right_precedence = operator_precedence
else:
left_precedence = operator_precedence
right_precedence = pnext(operator_precedence)
self.set_precedence(left_precedence, node.left)
self.dispatch(node.left)
self.write(" %s " % operator)
self.set_precedence(right_precedence, node.right)
self.dispatch(node.right)
cmpops = {
"Eq": "==",
"NotEq": "!=",
"Lt": "<",
"LtE": "<=",
"Gt": ">",
"GtE": ">=",
"Is": "is",
"IsNot": "is not",
"In": "in",
"NotIn": "not in",
}
[docs] def visit_Compare(self, node):
with self.require_parens(_Precedence.CMP, node):
self.set_precedence(pnext(_Precedence.CMP), node.left, *node.comparators)
self.dispatch(node.left)
for o, e in zip(node.ops, node.comparators):
self.write(" " + self.cmpops[o.__class__.__name__] + " ")
self.dispatch(e)
boolops = {
"And": "and",
"Or": "or",
}
boolop_precedence = {
"and": _Precedence.AND,
"or": _Precedence.OR,
}
[docs] def visit_BoolOp(self, node):
operator = self.boolops[node.op.__class__.__name__]
# use a dict instead of nonlocal for Python 2 compatibility
op = {"precedence": self.boolop_precedence[operator]}
def increasing_level_dispatch(node):
op["precedence"] = pnext(op["precedence"])
self.set_precedence(op["precedence"], node)
self.dispatch(node)
with self.require_parens(op["precedence"], node):
s = " %s " % operator
interleave(lambda: self.write(s), increasing_level_dispatch, node.values)
[docs] def visit_Attribute(self, node):
self.set_precedence(_Precedence.ATOM, node.value)
self.dispatch(node.value)
# Special case: 3.__abs__() is a syntax error, so if node.value
# is an integer literal then we need to either parenthesize
# it or add an extra space to get 3 .__abs__().
num_type = getattr(ast, 'Constant', getattr(ast, 'Num', None))
if isinstance(node.value, num_type) and isinstance(node.value.n, int):
self.write(" ")
self.write(".")
self.write(node.attr)
[docs] def visit_Call(self, node):
self.set_precedence(_Precedence.ATOM, node.func)
args = node.args
if self._py_ver_consistent:
# make print(a, b, c) and print((a, b, c)) equivalent, since you can't
# tell them apart between Python 2 and 3. See _Print() for more details.
if getattr(node.func, "id", None) == "print":
if len(node.args) == 1 and isinstance(node.args[0], ast.Tuple):
args = node.args[0].elts
self.dispatch(node.func)
with self.delimit("(", ")"):
comma = False
# starred arguments last in Python 3.5+, for consistency w/earlier versions
star_and_kwargs = []
move_stars_last = sys.version_info[:2] >= (3, 5)
for e in args:
if move_stars_last and isinstance(e, ast.Starred):
star_and_kwargs.append(e)
else:
if comma:
self.write(", ")
else:
comma = True
self.dispatch(e)
for e in node.keywords:
# starting from Python 3.5 this denotes a kwargs part of the invocation
if e.arg is None and move_stars_last:
star_and_kwargs.append(e)
else:
if comma:
self.write(", ")
else:
comma = True
self.dispatch(e)
if move_stars_last:
for e in star_and_kwargs:
if comma:
self.write(", ")
else:
comma = True
self.dispatch(e)
if sys.version_info[:2] < (3, 5):
if node.starargs:
if comma:
self.write(", ")
else:
comma = True
self.write("*")
self.dispatch(node.starargs)
if node.kwargs:
if comma:
self.write(", ")
else:
comma = True
self.write("**")
self.dispatch(node.kwargs)
[docs] def visit_Subscript(self, node):
self.set_precedence(_Precedence.ATOM, node.value)
self.dispatch(node.value)
with self.delimit("[", "]"):
if is_simple_tuple(node.slice):
self.items_view(self.dispatch, node.slice.elts)
else:
self.dispatch(node.slice)
[docs] def visit_Starred(self, node):
self.write("*")
self.set_precedence(_Precedence.EXPR, node.value)
self.dispatch(node.value)
# slice
[docs] def visit_Ellipsis(self, node):
self.write("...")
# used in Python <= 3.8 -- see _Subscript for 3.9+
[docs] def visit_Index(self, node):
if is_simple_tuple(node.value):
self.set_precedence(_Precedence.ATOM, node.value)
self.items_view(self.dispatch, node.value.elts)
else:
self.set_precedence(_Precedence.TUPLE, node.value)
self.dispatch(node.value)
[docs] def visit_Slice(self, node):
if node.lower:
self.dispatch(node.lower)
self.write(":")
if node.upper:
self.dispatch(node.upper)
if node.step:
self.write(":")
self.dispatch(node.step)
[docs] def visit_ExtSlice(self, node):
interleave(lambda: self.write(', '), self.dispatch, node.dims)
# argument
[docs] def visit_arg(self, node):
self.write(node.arg)
if node.annotation:
self.write(": ")
self.dispatch(node.annotation)
# others
[docs] def visit_arguments(self, node):
first = True
# normal arguments
all_args = getattr(node, 'posonlyargs', []) + node.args
defaults = [None] * (len(all_args) - len(node.defaults)) + node.defaults
for index, elements in enumerate(zip(all_args, defaults), 1):
a, d = elements
if first:
first = False
else:
self.write(", ")
self.dispatch(a)
if d:
self.write("=")
self.dispatch(d)
if index == len(getattr(node, 'posonlyargs', ())):
self.write(", /")
# varargs, or bare '*' if no varargs but keyword-only arguments present
if node.vararg or getattr(node, "kwonlyargs", False):
if first:
first = False
else:
self.write(", ")
self.write("*")
if node.vararg:
if hasattr(node.vararg, 'arg'):
self.write(node.vararg.arg)
if node.vararg.annotation:
self.write(": ")
self.dispatch(node.vararg.annotation)
else:
self.write(node.vararg)
if getattr(node, 'varargannotation', None):
self.write(": ")
self.dispatch(node.varargannotation)
# keyword-only arguments
if getattr(node, "kwonlyargs", False):
for a, d in zip(node.kwonlyargs, node.kw_defaults):
if first:
first = False
else:
self.write(", ")
self.dispatch(a),
if d:
self.write("=")
self.dispatch(d)
# kwargs
if node.kwarg:
if first:
first = False
else:
self.write(", ")
if hasattr(node.kwarg, 'arg'):
self.write("**" + node.kwarg.arg)
if node.kwarg.annotation:
self.write(": ")
self.dispatch(node.kwarg.annotation)
else:
self.write("**" + node.kwarg)
if getattr(node, 'kwargannotation', None):
self.write(": ")
self.dispatch(node.kwargannotation)
[docs] def visit_keyword(self, node):
if node.arg is None:
# starting from Python 3.5 this denotes a kwargs part of the invocation
self.write("**")
else:
self.write(node.arg)
self.write("=")
self.dispatch(node.value)
[docs] def visit_Lambda(self, node):
with self.require_parens(_Precedence.TEST, node):
self.write("lambda ")
self.dispatch(node.args)
self.write(": ")
self.set_precedence(_Precedence.TEST, node.body)
self.dispatch(node.body)
[docs] def visit_alias(self, node):
self.write(node.name)
if node.asname:
self.write(" as " + node.asname)
[docs] def visit_withitem(self, node):
self.dispatch(node.context_expr)
if node.optional_vars:
self.write(" as ")
self.dispatch(node.optional_vars)