Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/ExeBy/exe_root.../lib64/python2..../lib2to3
File: fixer_util.py
"""Utility functions, node construction macros, etc."""
[0] Fix | Delete
# Author: Collin Winter
[1] Fix | Delete
[2] Fix | Delete
from itertools import islice
[3] Fix | Delete
[4] Fix | Delete
# Local imports
[5] Fix | Delete
from .pgen2 import token
[6] Fix | Delete
from .pytree import Leaf, Node
[7] Fix | Delete
from .pygram import python_symbols as syms
[8] Fix | Delete
from . import patcomp
[9] Fix | Delete
[10] Fix | Delete
[11] Fix | Delete
###########################################################
[12] Fix | Delete
### Common node-construction "macros"
[13] Fix | Delete
###########################################################
[14] Fix | Delete
[15] Fix | Delete
def KeywordArg(keyword, value):
[16] Fix | Delete
return Node(syms.argument,
[17] Fix | Delete
[keyword, Leaf(token.EQUAL, u"="), value])
[18] Fix | Delete
[19] Fix | Delete
def LParen():
[20] Fix | Delete
return Leaf(token.LPAR, u"(")
[21] Fix | Delete
[22] Fix | Delete
def RParen():
[23] Fix | Delete
return Leaf(token.RPAR, u")")
[24] Fix | Delete
[25] Fix | Delete
def Assign(target, source):
[26] Fix | Delete
"""Build an assignment statement"""
[27] Fix | Delete
if not isinstance(target, list):
[28] Fix | Delete
target = [target]
[29] Fix | Delete
if not isinstance(source, list):
[30] Fix | Delete
source.prefix = u" "
[31] Fix | Delete
source = [source]
[32] Fix | Delete
[33] Fix | Delete
return Node(syms.atom,
[34] Fix | Delete
target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + source)
[35] Fix | Delete
[36] Fix | Delete
def Name(name, prefix=None):
[37] Fix | Delete
"""Return a NAME leaf"""
[38] Fix | Delete
return Leaf(token.NAME, name, prefix=prefix)
[39] Fix | Delete
[40] Fix | Delete
def Attr(obj, attr):
[41] Fix | Delete
"""A node tuple for obj.attr"""
[42] Fix | Delete
return [obj, Node(syms.trailer, [Dot(), attr])]
[43] Fix | Delete
[44] Fix | Delete
def Comma():
[45] Fix | Delete
"""A comma leaf"""
[46] Fix | Delete
return Leaf(token.COMMA, u",")
[47] Fix | Delete
[48] Fix | Delete
def Dot():
[49] Fix | Delete
"""A period (.) leaf"""
[50] Fix | Delete
return Leaf(token.DOT, u".")
[51] Fix | Delete
[52] Fix | Delete
def ArgList(args, lparen=LParen(), rparen=RParen()):
[53] Fix | Delete
"""A parenthesised argument list, used by Call()"""
[54] Fix | Delete
node = Node(syms.trailer, [lparen.clone(), rparen.clone()])
[55] Fix | Delete
if args:
[56] Fix | Delete
node.insert_child(1, Node(syms.arglist, args))
[57] Fix | Delete
return node
[58] Fix | Delete
[59] Fix | Delete
def Call(func_name, args=None, prefix=None):
[60] Fix | Delete
"""A function call"""
[61] Fix | Delete
node = Node(syms.power, [func_name, ArgList(args)])
[62] Fix | Delete
if prefix is not None:
[63] Fix | Delete
node.prefix = prefix
[64] Fix | Delete
return node
[65] Fix | Delete
[66] Fix | Delete
def Newline():
[67] Fix | Delete
"""A newline literal"""
[68] Fix | Delete
return Leaf(token.NEWLINE, u"\n")
[69] Fix | Delete
[70] Fix | Delete
def BlankLine():
[71] Fix | Delete
"""A blank line"""
[72] Fix | Delete
return Leaf(token.NEWLINE, u"")
[73] Fix | Delete
[74] Fix | Delete
def Number(n, prefix=None):
[75] Fix | Delete
return Leaf(token.NUMBER, n, prefix=prefix)
[76] Fix | Delete
[77] Fix | Delete
def Subscript(index_node):
[78] Fix | Delete
"""A numeric or string subscript"""
[79] Fix | Delete
return Node(syms.trailer, [Leaf(token.LBRACE, u"["),
[80] Fix | Delete
index_node,
[81] Fix | Delete
Leaf(token.RBRACE, u"]")])
[82] Fix | Delete
[83] Fix | Delete
def String(string, prefix=None):
[84] Fix | Delete
"""A string leaf"""
[85] Fix | Delete
return Leaf(token.STRING, string, prefix=prefix)
[86] Fix | Delete
[87] Fix | Delete
def ListComp(xp, fp, it, test=None):
[88] Fix | Delete
"""A list comprehension of the form [xp for fp in it if test].
[89] Fix | Delete
[90] Fix | Delete
If test is None, the "if test" part is omitted.
[91] Fix | Delete
"""
[92] Fix | Delete
xp.prefix = u""
[93] Fix | Delete
fp.prefix = u" "
[94] Fix | Delete
it.prefix = u" "
[95] Fix | Delete
for_leaf = Leaf(token.NAME, u"for")
[96] Fix | Delete
for_leaf.prefix = u" "
[97] Fix | Delete
in_leaf = Leaf(token.NAME, u"in")
[98] Fix | Delete
in_leaf.prefix = u" "
[99] Fix | Delete
inner_args = [for_leaf, fp, in_leaf, it]
[100] Fix | Delete
if test:
[101] Fix | Delete
test.prefix = u" "
[102] Fix | Delete
if_leaf = Leaf(token.NAME, u"if")
[103] Fix | Delete
if_leaf.prefix = u" "
[104] Fix | Delete
inner_args.append(Node(syms.comp_if, [if_leaf, test]))
[105] Fix | Delete
inner = Node(syms.listmaker, [xp, Node(syms.comp_for, inner_args)])
[106] Fix | Delete
return Node(syms.atom,
[107] Fix | Delete
[Leaf(token.LBRACE, u"["),
[108] Fix | Delete
inner,
[109] Fix | Delete
Leaf(token.RBRACE, u"]")])
[110] Fix | Delete
[111] Fix | Delete
def FromImport(package_name, name_leafs):
[112] Fix | Delete
""" Return an import statement in the form:
[113] Fix | Delete
from package import name_leafs"""
[114] Fix | Delete
# XXX: May not handle dotted imports properly (eg, package_name='foo.bar')
[115] Fix | Delete
#assert package_name == '.' or '.' not in package_name, "FromImport has "\
[116] Fix | Delete
# "not been tested with dotted package names -- use at your own "\
[117] Fix | Delete
# "peril!"
[118] Fix | Delete
[119] Fix | Delete
for leaf in name_leafs:
[120] Fix | Delete
# Pull the leaves out of their old tree
[121] Fix | Delete
leaf.remove()
[122] Fix | Delete
[123] Fix | Delete
children = [Leaf(token.NAME, u"from"),
[124] Fix | Delete
Leaf(token.NAME, package_name, prefix=u" "),
[125] Fix | Delete
Leaf(token.NAME, u"import", prefix=u" "),
[126] Fix | Delete
Node(syms.import_as_names, name_leafs)]
[127] Fix | Delete
imp = Node(syms.import_from, children)
[128] Fix | Delete
return imp
[129] Fix | Delete
[130] Fix | Delete
[131] Fix | Delete
###########################################################
[132] Fix | Delete
### Determine whether a node represents a given literal
[133] Fix | Delete
###########################################################
[134] Fix | Delete
[135] Fix | Delete
def is_tuple(node):
[136] Fix | Delete
"""Does the node represent a tuple literal?"""
[137] Fix | Delete
if isinstance(node, Node) and node.children == [LParen(), RParen()]:
[138] Fix | Delete
return True
[139] Fix | Delete
return (isinstance(node, Node)
[140] Fix | Delete
and len(node.children) == 3
[141] Fix | Delete
and isinstance(node.children[0], Leaf)
[142] Fix | Delete
and isinstance(node.children[1], Node)
[143] Fix | Delete
and isinstance(node.children[2], Leaf)
[144] Fix | Delete
and node.children[0].value == u"("
[145] Fix | Delete
and node.children[2].value == u")")
[146] Fix | Delete
[147] Fix | Delete
def is_list(node):
[148] Fix | Delete
"""Does the node represent a list literal?"""
[149] Fix | Delete
return (isinstance(node, Node)
[150] Fix | Delete
and len(node.children) > 1
[151] Fix | Delete
and isinstance(node.children[0], Leaf)
[152] Fix | Delete
and isinstance(node.children[-1], Leaf)
[153] Fix | Delete
and node.children[0].value == u"["
[154] Fix | Delete
and node.children[-1].value == u"]")
[155] Fix | Delete
[156] Fix | Delete
[157] Fix | Delete
###########################################################
[158] Fix | Delete
### Misc
[159] Fix | Delete
###########################################################
[160] Fix | Delete
[161] Fix | Delete
def parenthesize(node):
[162] Fix | Delete
return Node(syms.atom, [LParen(), node, RParen()])
[163] Fix | Delete
[164] Fix | Delete
[165] Fix | Delete
consuming_calls = set(["sorted", "list", "set", "any", "all", "tuple", "sum",
[166] Fix | Delete
"min", "max", "enumerate"])
[167] Fix | Delete
[168] Fix | Delete
def attr_chain(obj, attr):
[169] Fix | Delete
"""Follow an attribute chain.
[170] Fix | Delete
[171] Fix | Delete
If you have a chain of objects where a.foo -> b, b.foo-> c, etc,
[172] Fix | Delete
use this to iterate over all objects in the chain. Iteration is
[173] Fix | Delete
terminated by getattr(x, attr) is None.
[174] Fix | Delete
[175] Fix | Delete
Args:
[176] Fix | Delete
obj: the starting object
[177] Fix | Delete
attr: the name of the chaining attribute
[178] Fix | Delete
[179] Fix | Delete
Yields:
[180] Fix | Delete
Each successive object in the chain.
[181] Fix | Delete
"""
[182] Fix | Delete
next = getattr(obj, attr)
[183] Fix | Delete
while next:
[184] Fix | Delete
yield next
[185] Fix | Delete
next = getattr(next, attr)
[186] Fix | Delete
[187] Fix | Delete
p0 = """for_stmt< 'for' any 'in' node=any ':' any* >
[188] Fix | Delete
| comp_for< 'for' any 'in' node=any any* >
[189] Fix | Delete
"""
[190] Fix | Delete
p1 = """
[191] Fix | Delete
power<
[192] Fix | Delete
( 'iter' | 'list' | 'tuple' | 'sorted' | 'set' | 'sum' |
[193] Fix | Delete
'any' | 'all' | 'enumerate' | (any* trailer< '.' 'join' >) )
[194] Fix | Delete
trailer< '(' node=any ')' >
[195] Fix | Delete
any*
[196] Fix | Delete
>
[197] Fix | Delete
"""
[198] Fix | Delete
p2 = """
[199] Fix | Delete
power<
[200] Fix | Delete
( 'sorted' | 'enumerate' )
[201] Fix | Delete
trailer< '(' arglist<node=any any*> ')' >
[202] Fix | Delete
any*
[203] Fix | Delete
>
[204] Fix | Delete
"""
[205] Fix | Delete
pats_built = False
[206] Fix | Delete
def in_special_context(node):
[207] Fix | Delete
""" Returns true if node is in an environment where all that is required
[208] Fix | Delete
of it is being iterable (ie, it doesn't matter if it returns a list
[209] Fix | Delete
or an iterator).
[210] Fix | Delete
See test_map_nochange in test_fixers.py for some examples and tests.
[211] Fix | Delete
"""
[212] Fix | Delete
global p0, p1, p2, pats_built
[213] Fix | Delete
if not pats_built:
[214] Fix | Delete
p0 = patcomp.compile_pattern(p0)
[215] Fix | Delete
p1 = patcomp.compile_pattern(p1)
[216] Fix | Delete
p2 = patcomp.compile_pattern(p2)
[217] Fix | Delete
pats_built = True
[218] Fix | Delete
patterns = [p0, p1, p2]
[219] Fix | Delete
for pattern, parent in zip(patterns, attr_chain(node, "parent")):
[220] Fix | Delete
results = {}
[221] Fix | Delete
if pattern.match(parent, results) and results["node"] is node:
[222] Fix | Delete
return True
[223] Fix | Delete
return False
[224] Fix | Delete
[225] Fix | Delete
def is_probably_builtin(node):
[226] Fix | Delete
"""
[227] Fix | Delete
Check that something isn't an attribute or function name etc.
[228] Fix | Delete
"""
[229] Fix | Delete
prev = node.prev_sibling
[230] Fix | Delete
if prev is not None and prev.type == token.DOT:
[231] Fix | Delete
# Attribute lookup.
[232] Fix | Delete
return False
[233] Fix | Delete
parent = node.parent
[234] Fix | Delete
if parent.type in (syms.funcdef, syms.classdef):
[235] Fix | Delete
return False
[236] Fix | Delete
if parent.type == syms.expr_stmt and parent.children[0] is node:
[237] Fix | Delete
# Assignment.
[238] Fix | Delete
return False
[239] Fix | Delete
if parent.type == syms.parameters or \
[240] Fix | Delete
(parent.type == syms.typedargslist and (
[241] Fix | Delete
(prev is not None and prev.type == token.COMMA) or
[242] Fix | Delete
parent.children[0] is node
[243] Fix | Delete
)):
[244] Fix | Delete
# The name of an argument.
[245] Fix | Delete
return False
[246] Fix | Delete
return True
[247] Fix | Delete
[248] Fix | Delete
def find_indentation(node):
[249] Fix | Delete
"""Find the indentation of *node*."""
[250] Fix | Delete
while node is not None:
[251] Fix | Delete
if node.type == syms.suite and len(node.children) > 2:
[252] Fix | Delete
indent = node.children[1]
[253] Fix | Delete
if indent.type == token.INDENT:
[254] Fix | Delete
return indent.value
[255] Fix | Delete
node = node.parent
[256] Fix | Delete
return u""
[257] Fix | Delete
[258] Fix | Delete
###########################################################
[259] Fix | Delete
### The following functions are to find bindings in a suite
[260] Fix | Delete
###########################################################
[261] Fix | Delete
[262] Fix | Delete
def make_suite(node):
[263] Fix | Delete
if node.type == syms.suite:
[264] Fix | Delete
return node
[265] Fix | Delete
node = node.clone()
[266] Fix | Delete
parent, node.parent = node.parent, None
[267] Fix | Delete
suite = Node(syms.suite, [node])
[268] Fix | Delete
suite.parent = parent
[269] Fix | Delete
return suite
[270] Fix | Delete
[271] Fix | Delete
def find_root(node):
[272] Fix | Delete
"""Find the top level namespace."""
[273] Fix | Delete
# Scamper up to the top level namespace
[274] Fix | Delete
while node.type != syms.file_input:
[275] Fix | Delete
node = node.parent
[276] Fix | Delete
if not node:
[277] Fix | Delete
raise ValueError("root found before file_input node was found.")
[278] Fix | Delete
return node
[279] Fix | Delete
[280] Fix | Delete
def does_tree_import(package, name, node):
[281] Fix | Delete
""" Returns true if name is imported from package at the
[282] Fix | Delete
top level of the tree which node belongs to.
[283] Fix | Delete
To cover the case of an import like 'import foo', use
[284] Fix | Delete
None for the package and 'foo' for the name. """
[285] Fix | Delete
binding = find_binding(name, find_root(node), package)
[286] Fix | Delete
return bool(binding)
[287] Fix | Delete
[288] Fix | Delete
def is_import(node):
[289] Fix | Delete
"""Returns true if the node is an import statement."""
[290] Fix | Delete
return node.type in (syms.import_name, syms.import_from)
[291] Fix | Delete
[292] Fix | Delete
def touch_import(package, name, node):
[293] Fix | Delete
""" Works like `does_tree_import` but adds an import statement
[294] Fix | Delete
if it was not imported. """
[295] Fix | Delete
def is_import_stmt(node):
[296] Fix | Delete
return (node.type == syms.simple_stmt and node.children and
[297] Fix | Delete
is_import(node.children[0]))
[298] Fix | Delete
[299] Fix | Delete
root = find_root(node)
[300] Fix | Delete
[301] Fix | Delete
if does_tree_import(package, name, root):
[302] Fix | Delete
return
[303] Fix | Delete
[304] Fix | Delete
# figure out where to insert the new import. First try to find
[305] Fix | Delete
# the first import and then skip to the last one.
[306] Fix | Delete
insert_pos = offset = 0
[307] Fix | Delete
for idx, node in enumerate(root.children):
[308] Fix | Delete
if not is_import_stmt(node):
[309] Fix | Delete
continue
[310] Fix | Delete
for offset, node2 in enumerate(root.children[idx:]):
[311] Fix | Delete
if not is_import_stmt(node2):
[312] Fix | Delete
break
[313] Fix | Delete
insert_pos = idx + offset
[314] Fix | Delete
break
[315] Fix | Delete
[316] Fix | Delete
# if there are no imports where we can insert, find the docstring.
[317] Fix | Delete
# if that also fails, we stick to the beginning of the file
[318] Fix | Delete
if insert_pos == 0:
[319] Fix | Delete
for idx, node in enumerate(root.children):
[320] Fix | Delete
if (node.type == syms.simple_stmt and node.children and
[321] Fix | Delete
node.children[0].type == token.STRING):
[322] Fix | Delete
insert_pos = idx + 1
[323] Fix | Delete
break
[324] Fix | Delete
[325] Fix | Delete
if package is None:
[326] Fix | Delete
import_ = Node(syms.import_name, [
[327] Fix | Delete
Leaf(token.NAME, u"import"),
[328] Fix | Delete
Leaf(token.NAME, name, prefix=u" ")
[329] Fix | Delete
])
[330] Fix | Delete
else:
[331] Fix | Delete
import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")])
[332] Fix | Delete
[333] Fix | Delete
children = [import_, Newline()]
[334] Fix | Delete
root.insert_child(insert_pos, Node(syms.simple_stmt, children))
[335] Fix | Delete
[336] Fix | Delete
[337] Fix | Delete
_def_syms = set([syms.classdef, syms.funcdef])
[338] Fix | Delete
def find_binding(name, node, package=None):
[339] Fix | Delete
""" Returns the node which binds variable name, otherwise None.
[340] Fix | Delete
If optional argument package is supplied, only imports will
[341] Fix | Delete
be returned.
[342] Fix | Delete
See test cases for examples."""
[343] Fix | Delete
for child in node.children:
[344] Fix | Delete
ret = None
[345] Fix | Delete
if child.type == syms.for_stmt:
[346] Fix | Delete
if _find(name, child.children[1]):
[347] Fix | Delete
return child
[348] Fix | Delete
n = find_binding(name, make_suite(child.children[-1]), package)
[349] Fix | Delete
if n: ret = n
[350] Fix | Delete
elif child.type in (syms.if_stmt, syms.while_stmt):
[351] Fix | Delete
n = find_binding(name, make_suite(child.children[-1]), package)
[352] Fix | Delete
if n: ret = n
[353] Fix | Delete
elif child.type == syms.try_stmt:
[354] Fix | Delete
n = find_binding(name, make_suite(child.children[2]), package)
[355] Fix | Delete
if n:
[356] Fix | Delete
ret = n
[357] Fix | Delete
else:
[358] Fix | Delete
for i, kid in enumerate(child.children[3:]):
[359] Fix | Delete
if kid.type == token.COLON and kid.value == ":":
[360] Fix | Delete
# i+3 is the colon, i+4 is the suite
[361] Fix | Delete
n = find_binding(name, make_suite(child.children[i+4]), package)
[362] Fix | Delete
if n: ret = n
[363] Fix | Delete
elif child.type in _def_syms and child.children[1].value == name:
[364] Fix | Delete
ret = child
[365] Fix | Delete
elif _is_import_binding(child, name, package):
[366] Fix | Delete
ret = child
[367] Fix | Delete
elif child.type == syms.simple_stmt:
[368] Fix | Delete
ret = find_binding(name, child, package)
[369] Fix | Delete
elif child.type == syms.expr_stmt:
[370] Fix | Delete
if _find(name, child.children[0]):
[371] Fix | Delete
ret = child
[372] Fix | Delete
[373] Fix | Delete
if ret:
[374] Fix | Delete
if not package:
[375] Fix | Delete
return ret
[376] Fix | Delete
if is_import(ret):
[377] Fix | Delete
return ret
[378] Fix | Delete
return None
[379] Fix | Delete
[380] Fix | Delete
_block_syms = set([syms.funcdef, syms.classdef, syms.trailer])
[381] Fix | Delete
def _find(name, node):
[382] Fix | Delete
nodes = [node]
[383] Fix | Delete
while nodes:
[384] Fix | Delete
node = nodes.pop()
[385] Fix | Delete
if node.type > 256 and node.type not in _block_syms:
[386] Fix | Delete
nodes.extend(node.children)
[387] Fix | Delete
elif node.type == token.NAME and node.value == name:
[388] Fix | Delete
return node
[389] Fix | Delete
return None
[390] Fix | Delete
[391] Fix | Delete
def _is_import_binding(node, name, package=None):
[392] Fix | Delete
""" Will reuturn node if node will import name, or node
[393] Fix | Delete
will import * from package. None is returned otherwise.
[394] Fix | Delete
See test cases for examples. """
[395] Fix | Delete
[396] Fix | Delete
if node.type == syms.import_name and not package:
[397] Fix | Delete
imp = node.children[1]
[398] Fix | Delete
if imp.type == syms.dotted_as_names:
[399] Fix | Delete
for child in imp.children:
[400] Fix | Delete
if child.type == syms.dotted_as_name:
[401] Fix | Delete
if child.children[2].value == name:
[402] Fix | Delete
return node
[403] Fix | Delete
elif child.type == token.NAME and child.value == name:
[404] Fix | Delete
return node
[405] Fix | Delete
elif imp.type == syms.dotted_as_name:
[406] Fix | Delete
last = imp.children[-1]
[407] Fix | Delete
if last.type == token.NAME and last.value == name:
[408] Fix | Delete
return node
[409] Fix | Delete
elif imp.type == token.NAME and imp.value == name:
[410] Fix | Delete
return node
[411] Fix | Delete
elif node.type == syms.import_from:
[412] Fix | Delete
# unicode(...) is used to make life easier here, because
[413] Fix | Delete
# from a.b import parses to ['import', ['a', '.', 'b'], ...]
[414] Fix | Delete
if package and unicode(node.children[1]).strip() != package:
[415] Fix | Delete
return None
[416] Fix | Delete
n = node.children[3]
[417] Fix | Delete
if package and _find(u"as", n):
[418] Fix | Delete
# See test_from_import_as for explanation
[419] Fix | Delete
return None
[420] Fix | Delete
elif n.type == syms.import_as_names and _find(name, n):
[421] Fix | Delete
return node
[422] Fix | Delete
elif n.type == syms.import_as_name:
[423] Fix | Delete
child = n.children[2]
[424] Fix | Delete
if child.type == token.NAME and child.value == name:
[425] Fix | Delete
return node
[426] Fix | Delete
elif n.type == token.NAME and n.value == name:
[427] Fix | Delete
return node
[428] Fix | Delete
elif package and n.type == token.STAR:
[429] Fix | Delete
return node
[430] Fix | Delete
return None
[431] Fix | Delete
[432] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function