after_merge
stringlengths 28
79.6k
| before_merge
stringlengths 20
79.6k
| url
stringlengths 38
71
| full_traceback
stringlengths 43
922k
| traceback_type
stringclasses 555
values |
|---|---|---|---|---|
def __init__(self, contract_name, lvalue):
assert isinstance(contract_name, Constant)
assert is_valid_lvalue(lvalue)
super(NewContract, self).__init__()
self._contract_name = contract_name
# todo create analyze to add the contract instance
self._lvalue = lvalue
self._callid = None # only used if gas/value != 0
self._call_value = None
self._call_salt = None
|
def __init__(self, contract_name, lvalue):
assert isinstance(contract_name, Constant)
assert is_valid_lvalue(lvalue)
super(NewContract, self).__init__()
self._contract_name = contract_name
# todo create analyze to add the contract instance
self._lvalue = lvalue
self._callid = None # only used if gas/value != 0
self._call_value = None
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def __str__(self):
options = ""
if self.call_value:
options = "value:{} ".format(self.call_value)
if self.call_salt:
options += "salt:{} ".format(self.call_salt)
args = [str(a) for a in self.arguments]
return "{} = new {}({}) {}".format(
self.lvalue, self.contract_name, ",".join(args), options
)
|
def __str__(self):
value = ""
if self.call_value:
value = "value:{}".format(self.call_value)
args = [str(a) for a in self.arguments]
return "{} = new {}({}) {}".format(
self.lvalue, self.contract_name, ",".join(args), value
)
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def __init__(self, called, nbr_arguments, result, type_call):
assert isinstance(
called,
(
Contract,
Variable,
SolidityVariableComposed,
SolidityFunction,
Structure,
Event,
),
)
super(TmpCall, self).__init__()
self._called = called
self._nbr_arguments = nbr_arguments
self._type_call = type_call
self._lvalue = result
self._ori = None #
self._callid = None
self._gas = None
self._value = None
self._salt = None
|
def __init__(self, called, nbr_arguments, result, type_call):
assert isinstance(
called,
(
Contract,
Variable,
SolidityVariableComposed,
SolidityFunction,
Structure,
Event,
),
)
super(TmpCall, self).__init__()
self._called = called
self._nbr_arguments = nbr_arguments
self._type_call = type_call
self._lvalue = result
self._ori = None #
self._callid = None
self._gas = None
self._value = None
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def __init__(self, contract_name, lvalue):
super(TmpNewContract, self).__init__()
self._contract_name = contract_name
self._lvalue = lvalue
self._call_value = None
self._call_salt = None
|
def __init__(self, contract_name, lvalue):
super(TmpNewContract, self).__init__()
self._contract_name = contract_name
self._lvalue = lvalue
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def copy_ir(ir, *instances):
"""
Args:
ir (Operation)
local_variables_instances(dict(str -> LocalVariable))
state_variables_instances(dict(str -> StateVariable))
temporary_variables_instances(dict(int -> Variable))
reference_variables_instances(dict(int -> Variable))
Note: temporary and reference can be indexed by int, as they dont need phi functions
"""
if isinstance(ir, Assignment):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
rvalue = get_variable(ir, lambda x: x.rvalue, *instances)
variable_return_type = ir.variable_return_type
return Assignment(lvalue, rvalue, variable_return_type)
elif isinstance(ir, Balance):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
value = get_variable(ir, lambda x: x.value, *instances)
return Balance(value, lvalue)
elif isinstance(ir, Binary):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable_left = get_variable(ir, lambda x: x.variable_left, *instances)
variable_right = get_variable(ir, lambda x: x.variable_right, *instances)
operation_type = ir.type
return Binary(lvalue, variable_left, variable_right, operation_type)
elif isinstance(ir, Condition):
val = get_variable(ir, lambda x: x.value, *instances)
return Condition(val)
elif isinstance(ir, Delete):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable = get_variable(ir, lambda x: x.variable, *instances)
return Delete(lvalue, variable)
elif isinstance(ir, EventCall):
name = ir.name
return EventCall(name)
elif isinstance(ir, HighLevelCall): # include LibraryCall
destination = get_variable(ir, lambda x: x.destination, *instances)
function_name = ir.function_name
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
if isinstance(ir, LibraryCall):
new_ir = LibraryCall(
destination, function_name, nbr_arguments, lvalue, type_call
)
else:
new_ir = HighLevelCall(
destination, function_name, nbr_arguments, lvalue, type_call
)
new_ir.call_id = ir.call_id
new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances)
new_ir.call_gas = get_variable(ir, lambda x: x.call_gas, *instances)
new_ir.arguments = get_arguments(ir, *instances)
new_ir.function = ir.function
return new_ir
elif isinstance(ir, Index):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable_left = get_variable(ir, lambda x: x.variable_left, *instances)
variable_right = get_variable(ir, lambda x: x.variable_right, *instances)
index_type = ir.index_type
return Index(lvalue, variable_left, variable_right, index_type)
elif isinstance(ir, InitArray):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
init_values = get_rec_values(ir, lambda x: x.init_values, *instances)
return InitArray(init_values, lvalue)
elif isinstance(ir, InternalCall):
function = ir.function
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
new_ir = InternalCall(function, nbr_arguments, lvalue, type_call)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, InternalDynamicCall):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
function = get_variable(ir, lambda x: x.function, *instances)
function_type = ir.function_type
new_ir = InternalDynamicCall(lvalue, function, function_type)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, LowLevelCall):
destination = get_variable(ir, lambda x: x.destination, *instances)
function_name = ir.function_name
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
new_ir = LowLevelCall(
destination, function_name, nbr_arguments, lvalue, type_call
)
new_ir.call_id = ir.call_id
new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances)
new_ir.call_gas = get_variable(ir, lambda x: x.call_gas, *instances)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, Member):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable_left = get_variable(ir, lambda x: x.variable_left, *instances)
variable_right = get_variable(ir, lambda x: x.variable_right, *instances)
return Member(variable_left, variable_right, lvalue)
elif isinstance(ir, NewArray):
depth = ir.depth
array_type = ir.array_type
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewArray(depth, array_type, lvalue)
new_ir.arguments = get_rec_values(ir, lambda x: x.arguments, *instances)
return new_ir
elif isinstance(ir, NewElementaryType):
new_type = ir.type
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewElementaryType(new_type, lvalue)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, NewContract):
contract_name = ir.contract_name
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewContract(contract_name, lvalue)
new_ir.arguments = get_arguments(ir, *instances)
new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances)
new_ir.call_salt = get_variable(ir, lambda x: x.call_salt, *instances)
return new_ir
elif isinstance(ir, NewStructure):
structure = ir.structure
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewStructure(structure, lvalue)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, Nop):
return Nop()
elif isinstance(ir, Push):
array = get_variable(ir, lambda x: x.array, *instances)
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
return Push(array, lvalue)
elif isinstance(ir, Return):
values = get_rec_values(ir, lambda x: x.values, *instances)
return Return(values)
elif isinstance(ir, Send):
destination = get_variable(ir, lambda x: x.destination, *instances)
value = get_variable(ir, lambda x: x.call_value, *instances)
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
return Send(destination, value, lvalue)
elif isinstance(ir, SolidityCall):
function = ir.function
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
new_ir = SolidityCall(function, nbr_arguments, lvalue, type_call)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, Transfer):
destination = get_variable(ir, lambda x: x.destination, *instances)
value = get_variable(ir, lambda x: x.call_value, *instances)
return Transfer(destination, value)
elif isinstance(ir, TypeConversion):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable = get_variable(ir, lambda x: x.variable, *instances)
variable_type = ir.type
return TypeConversion(lvalue, variable, variable_type)
elif isinstance(ir, Unary):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
rvalue = get_variable(ir, lambda x: x.rvalue, *instances)
operation_type = ir.type
return Unary(lvalue, rvalue, operation_type)
elif isinstance(ir, Unpack):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
tuple_var = get_variable(ir, lambda x: x.tuple, *instances)
idx = ir.index
return Unpack(lvalue, tuple_var, idx)
elif isinstance(ir, Length):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
value = get_variable(ir, lambda x: x.value, *instances)
return Length(value, lvalue)
raise SlithIRError("Impossible ir copy on {} ({})".format(ir, type(ir)))
|
def copy_ir(ir, *instances):
"""
Args:
ir (Operation)
local_variables_instances(dict(str -> LocalVariable))
state_variables_instances(dict(str -> StateVariable))
temporary_variables_instances(dict(int -> Variable))
reference_variables_instances(dict(int -> Variable))
Note: temporary and reference can be indexed by int, as they dont need phi functions
"""
if isinstance(ir, Assignment):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
rvalue = get_variable(ir, lambda x: x.rvalue, *instances)
variable_return_type = ir.variable_return_type
return Assignment(lvalue, rvalue, variable_return_type)
elif isinstance(ir, Balance):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
value = get_variable(ir, lambda x: x.value, *instances)
return Balance(value, lvalue)
elif isinstance(ir, Binary):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable_left = get_variable(ir, lambda x: x.variable_left, *instances)
variable_right = get_variable(ir, lambda x: x.variable_right, *instances)
operation_type = ir.type
return Binary(lvalue, variable_left, variable_right, operation_type)
elif isinstance(ir, Condition):
val = get_variable(ir, lambda x: x.value, *instances)
return Condition(val)
elif isinstance(ir, Delete):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable = get_variable(ir, lambda x: x.variable, *instances)
return Delete(lvalue, variable)
elif isinstance(ir, EventCall):
name = ir.name
return EventCall(name)
elif isinstance(ir, HighLevelCall): # include LibraryCall
destination = get_variable(ir, lambda x: x.destination, *instances)
function_name = ir.function_name
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
if isinstance(ir, LibraryCall):
new_ir = LibraryCall(
destination, function_name, nbr_arguments, lvalue, type_call
)
else:
new_ir = HighLevelCall(
destination, function_name, nbr_arguments, lvalue, type_call
)
new_ir.call_id = ir.call_id
new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances)
new_ir.call_gas = get_variable(ir, lambda x: x.call_gas, *instances)
new_ir.arguments = get_arguments(ir, *instances)
new_ir.function = ir.function
return new_ir
elif isinstance(ir, Index):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable_left = get_variable(ir, lambda x: x.variable_left, *instances)
variable_right = get_variable(ir, lambda x: x.variable_right, *instances)
index_type = ir.index_type
return Index(lvalue, variable_left, variable_right, index_type)
elif isinstance(ir, InitArray):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
init_values = get_rec_values(ir, lambda x: x.init_values, *instances)
return InitArray(init_values, lvalue)
elif isinstance(ir, InternalCall):
function = ir.function
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
new_ir = InternalCall(function, nbr_arguments, lvalue, type_call)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, InternalDynamicCall):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
function = get_variable(ir, lambda x: x.function, *instances)
function_type = ir.function_type
new_ir = InternalDynamicCall(lvalue, function, function_type)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, LowLevelCall):
destination = get_variable(ir, lambda x: x.destination, *instances)
function_name = ir.function_name
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
new_ir = LowLevelCall(
destination, function_name, nbr_arguments, lvalue, type_call
)
new_ir.call_id = ir.call_id
new_ir.call_value = get_variable(ir, lambda x: x.call_value, *instances)
new_ir.call_gas = get_variable(ir, lambda x: x.call_gas, *instances)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, Member):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable_left = get_variable(ir, lambda x: x.variable_left, *instances)
variable_right = get_variable(ir, lambda x: x.variable_right, *instances)
return Member(variable_left, variable_right, lvalue)
elif isinstance(ir, NewArray):
depth = ir.depth
array_type = ir.array_type
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewArray(depth, array_type, lvalue)
new_ir.arguments = get_rec_values(ir, lambda x: x.arguments, *instances)
return new_ir
elif isinstance(ir, NewElementaryType):
new_type = ir.type
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewElementaryType(new_type, lvalue)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, NewContract):
contract_name = ir.contract_name
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewContract(contract_name, lvalue)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, NewStructure):
structure = ir.structure
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
new_ir = NewStructure(structure, lvalue)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, Nop):
return Nop()
elif isinstance(ir, Push):
array = get_variable(ir, lambda x: x.array, *instances)
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
return Push(array, lvalue)
elif isinstance(ir, Return):
values = get_rec_values(ir, lambda x: x.values, *instances)
return Return(values)
elif isinstance(ir, Send):
destination = get_variable(ir, lambda x: x.destination, *instances)
value = get_variable(ir, lambda x: x.call_value, *instances)
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
return Send(destination, value, lvalue)
elif isinstance(ir, SolidityCall):
function = ir.function
nbr_arguments = ir.nbr_arguments
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
type_call = ir.type_call
new_ir = SolidityCall(function, nbr_arguments, lvalue, type_call)
new_ir.arguments = get_arguments(ir, *instances)
return new_ir
elif isinstance(ir, Transfer):
destination = get_variable(ir, lambda x: x.destination, *instances)
value = get_variable(ir, lambda x: x.call_value, *instances)
return Transfer(destination, value)
elif isinstance(ir, TypeConversion):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
variable = get_variable(ir, lambda x: x.variable, *instances)
variable_type = ir.type
return TypeConversion(lvalue, variable, variable_type)
elif isinstance(ir, Unary):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
rvalue = get_variable(ir, lambda x: x.rvalue, *instances)
operation_type = ir.type
return Unary(lvalue, rvalue, operation_type)
elif isinstance(ir, Unpack):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
tuple_var = get_variable(ir, lambda x: x.tuple, *instances)
idx = ir.index
return Unpack(lvalue, tuple_var, idx)
elif isinstance(ir, Length):
lvalue = get_variable(ir, lambda x: x.lvalue, *instances)
value = get_variable(ir, lambda x: x.value, *instances)
return Length(value, lvalue)
raise SlithIRError("Impossible ir copy on {} ({})".format(ir, type(ir)))
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def parse_call(expression, caller_context):
src = expression["src"]
if caller_context.is_compact_ast:
attributes = expression
type_conversion = expression["kind"] == "typeConversion"
type_return = attributes["typeDescriptions"]["typeString"]
else:
attributes = expression["attributes"]
type_conversion = attributes["type_conversion"]
type_return = attributes["type"]
if type_conversion:
type_call = parse_type(UnknownType(type_return), caller_context)
if caller_context.is_compact_ast:
assert len(expression["arguments"]) == 1
expression_to_parse = expression["arguments"][0]
else:
children = expression["children"]
assert len(children) == 2
type_info = children[0]
expression_to_parse = children[1]
assert type_info["name"] in [
"ElementaryTypenameExpression",
"ElementaryTypeNameExpression",
"Identifier",
"TupleExpression",
"IndexAccess",
"MemberAccess",
]
expression = parse_expression(expression_to_parse, caller_context)
t = TypeConversion(expression, type_call)
t.set_offset(src, caller_context.slither)
return t
call_gas = None
call_value = None
call_salt = None
if caller_context.is_compact_ast:
called = parse_expression(expression["expression"], caller_context)
# If the next expression is a FunctionCallOptions
# We can here the gas/value information
# This is only available if the syntax is {gas: , value: }
# For the .gas().value(), the member are considered as function call
# And converted later to the correct info (convert.py)
if expression["expression"][caller_context.get_key()] == "FunctionCallOptions":
call_with_options = expression["expression"]
for idx, name in enumerate(call_with_options.get("names", [])):
option = parse_expression(
call_with_options["options"][idx], caller_context
)
if name == "value":
call_value = option
if name == "gas":
call_gas = option
if name == "salt":
call_salt = option
arguments = []
if expression["arguments"]:
arguments = [
parse_expression(a, caller_context) for a in expression["arguments"]
]
else:
children = expression["children"]
called = parse_expression(children[0], caller_context)
arguments = [parse_expression(a, caller_context) for a in children[1::]]
if isinstance(called, SuperCallExpression):
sp = SuperCallExpression(called, arguments, type_return)
sp.set_offset(expression["src"], caller_context.slither)
return sp
call_expression = CallExpression(called, arguments, type_return)
call_expression.set_offset(src, caller_context.slither)
# Only available if the syntax {gas:, value:} was used
call_expression.call_gas = call_gas
call_expression.call_value = call_value
call_expression.call_salt = call_salt
return call_expression
|
def parse_call(expression, caller_context):
src = expression["src"]
if caller_context.is_compact_ast:
attributes = expression
type_conversion = expression["kind"] == "typeConversion"
type_return = attributes["typeDescriptions"]["typeString"]
else:
attributes = expression["attributes"]
type_conversion = attributes["type_conversion"]
type_return = attributes["type"]
if type_conversion:
type_call = parse_type(UnknownType(type_return), caller_context)
if caller_context.is_compact_ast:
assert len(expression["arguments"]) == 1
expression_to_parse = expression["arguments"][0]
else:
children = expression["children"]
assert len(children) == 2
type_info = children[0]
expression_to_parse = children[1]
assert type_info["name"] in [
"ElementaryTypenameExpression",
"ElementaryTypeNameExpression",
"Identifier",
"TupleExpression",
"IndexAccess",
"MemberAccess",
]
expression = parse_expression(expression_to_parse, caller_context)
t = TypeConversion(expression, type_call)
t.set_offset(src, caller_context.slither)
return t
call_gas = None
call_value = None
if caller_context.is_compact_ast:
called = parse_expression(expression["expression"], caller_context)
# If the next expression is a FunctionCallOptions
# We can here the gas/value information
# This is only available if the syntax is {gas: , value: }
# For the .gas().value(), the member are considered as function call
# And converted later to the correct info (convert.py)
if expression["expression"][caller_context.get_key()] == "FunctionCallOptions":
call_with_options = expression["expression"]
for idx, name in enumerate(call_with_options.get("names", [])):
option = parse_expression(
call_with_options["options"][idx], caller_context
)
if name == "value":
call_value = option
if name == "gas":
call_gas = option
arguments = []
if expression["arguments"]:
arguments = [
parse_expression(a, caller_context) for a in expression["arguments"]
]
else:
children = expression["children"]
called = parse_expression(children[0], caller_context)
arguments = [parse_expression(a, caller_context) for a in children[1::]]
if isinstance(called, SuperCallExpression):
sp = SuperCallExpression(called, arguments, type_return)
sp.set_offset(expression["src"], caller_context.slither)
return sp
call_expression = CallExpression(called, arguments, type_return)
call_expression.set_offset(src, caller_context.slither)
# Only available if the syntax {gas:, value:} was used
call_expression.call_gas = call_gas
call_expression.call_value = call_value
return call_expression
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def parse_expression(expression, caller_context):
"""
Returns:
str: expression
"""
# Expression
# = Expression ('++' | '--')
# | NewExpression
# | IndexAccess
# | MemberAccess
# | FunctionCall
# | '(' Expression ')'
# | ('!' | '~' | 'delete' | '++' | '--' | '+' | '-') Expression
# | Expression '**' Expression
# | Expression ('*' | '/' | '%') Expression
# | Expression ('+' | '-') Expression
# | Expression ('<<' | '>>') Expression
# | Expression '&' Expression
# | Expression '^' Expression
# | Expression '|' Expression
# | Expression ('<' | '>' | '<=' | '>=') Expression
# | Expression ('==' | '!=') Expression
# | Expression '&&' Expression
# | Expression '||' Expression
# | Expression '?' Expression ':' Expression
# | Expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') Expression
# | PrimaryExpression
# The AST naming does not follow the spec
name = expression[caller_context.get_key()]
is_compact_ast = caller_context.is_compact_ast
src = expression["src"]
if name == "UnaryOperation":
if is_compact_ast:
attributes = expression
else:
attributes = expression["attributes"]
assert "prefix" in attributes
operation_type = UnaryOperationType.get_type(
attributes["operator"], attributes["prefix"]
)
if is_compact_ast:
expression = parse_expression(expression["subExpression"], caller_context)
else:
assert len(expression["children"]) == 1
expression = parse_expression(expression["children"][0], caller_context)
unary_op = UnaryOperation(expression, operation_type)
unary_op.set_offset(src, caller_context.slither)
return unary_op
elif name == "BinaryOperation":
if is_compact_ast:
attributes = expression
else:
attributes = expression["attributes"]
operation_type = BinaryOperationType.get_type(attributes["operator"])
if is_compact_ast:
left_expression = parse_expression(
expression["leftExpression"], caller_context
)
right_expression = parse_expression(
expression["rightExpression"], caller_context
)
else:
assert len(expression["children"]) == 2
left_expression = parse_expression(
expression["children"][0], caller_context
)
right_expression = parse_expression(
expression["children"][1], caller_context
)
binary_op = BinaryOperation(left_expression, right_expression, operation_type)
binary_op.set_offset(src, caller_context.slither)
return binary_op
elif name in "FunctionCall":
return parse_call(expression, caller_context)
elif name == "FunctionCallOptions":
# call/gas info are handled in parse_call
called = parse_expression(expression["expression"], caller_context)
assert isinstance(called, (MemberAccess, NewContract))
return called
elif name == "TupleExpression":
"""
For expression like
(a,,c) = (1,2,3)
the AST provides only two children in the left side
We check the type provided (tuple(uint256,,uint256))
To determine that there is an empty variable
Otherwhise we would not be able to determine that
a = 1, c = 3, and 2 is lost
Note: this is only possible with Solidity >= 0.4.12
"""
if is_compact_ast:
expressions = [
parse_expression(e, caller_context) if e else None
for e in expression["components"]
]
else:
if "children" not in expression:
attributes = expression["attributes"]
components = attributes["components"]
expressions = [
parse_expression(c, caller_context) if c else None
for c in components
]
else:
expressions = [
parse_expression(e, caller_context) for e in expression["children"]
]
# Add none for empty tuple items
if "attributes" in expression:
if "type" in expression["attributes"]:
t = expression["attributes"]["type"]
if ",," in t or "(," in t or ",)" in t:
t = t[len("tuple(") : -1]
elems = t.split(",")
for idx in range(len(elems)):
if elems[idx] == "":
expressions.insert(idx, None)
t = TupleExpression(expressions)
t.set_offset(src, caller_context.slither)
return t
elif name == "Conditional":
if is_compact_ast:
if_expression = parse_expression(expression["condition"], caller_context)
then_expression = parse_expression(
expression["trueExpression"], caller_context
)
else_expression = parse_expression(
expression["falseExpression"], caller_context
)
else:
children = expression["children"]
assert len(children) == 3
if_expression = parse_expression(children[0], caller_context)
then_expression = parse_expression(children[1], caller_context)
else_expression = parse_expression(children[2], caller_context)
conditional = ConditionalExpression(
if_expression, then_expression, else_expression
)
conditional.set_offset(src, caller_context.slither)
return conditional
elif name == "Assignment":
if is_compact_ast:
left_expression = parse_expression(
expression["leftHandSide"], caller_context
)
right_expression = parse_expression(
expression["rightHandSide"], caller_context
)
operation_type = AssignmentOperationType.get_type(expression["operator"])
operation_return_type = expression["typeDescriptions"]["typeString"]
else:
attributes = expression["attributes"]
children = expression["children"]
assert len(expression["children"]) == 2
left_expression = parse_expression(children[0], caller_context)
right_expression = parse_expression(children[1], caller_context)
operation_type = AssignmentOperationType.get_type(attributes["operator"])
operation_return_type = attributes["type"]
assignement = AssignmentOperation(
left_expression, right_expression, operation_type, operation_return_type
)
assignement.set_offset(src, caller_context.slither)
return assignement
elif name == "Literal":
subdenomination = None
assert "children" not in expression
if is_compact_ast:
value = expression["value"]
if value:
if "subdenomination" in expression and expression["subdenomination"]:
subdenomination = expression["subdenomination"]
elif not value and value != "":
value = "0x" + expression["hexValue"]
type = expression["typeDescriptions"]["typeString"]
# Length declaration for array was None until solc 0.5.5
if type is None:
if expression["kind"] == "number":
type = "int_const"
else:
value = expression["attributes"]["value"]
if value:
if (
"subdenomination" in expression["attributes"]
and expression["attributes"]["subdenomination"]
):
subdenomination = expression["attributes"]["subdenomination"]
elif value is None:
# for literal declared as hex
# see https://solidity.readthedocs.io/en/v0.4.25/types.html?highlight=hex#hexadecimal-literals
assert "hexvalue" in expression["attributes"]
value = "0x" + expression["attributes"]["hexvalue"]
type = expression["attributes"]["type"]
if type is None:
if value.isdecimal():
type = ElementaryType("uint256")
else:
type = ElementaryType("string")
elif type.startswith("int_const "):
type = ElementaryType("uint256")
elif type.startswith("bool"):
type = ElementaryType("bool")
elif type.startswith("address"):
type = ElementaryType("address")
else:
type = ElementaryType("string")
literal = Literal(value, type, subdenomination)
literal.set_offset(src, caller_context.slither)
return literal
elif name == "Identifier":
assert "children" not in expression
t = None
if caller_context.is_compact_ast:
value = expression["name"]
t = expression["typeDescriptions"]["typeString"]
else:
value = expression["attributes"]["value"]
if "type" in expression["attributes"]:
t = expression["attributes"]["type"]
if t:
found = re.findall(
"[struct|enum|function|modifier] \(([\[\] ()a-zA-Z0-9\.,_]*)\)", t
)
assert len(found) <= 1
if found:
value = value + "(" + found[0] + ")"
value = filter_name(value)
if "referencedDeclaration" in expression:
referenced_declaration = expression["referencedDeclaration"]
else:
referenced_declaration = None
var = find_variable(value, caller_context, referenced_declaration)
identifier = Identifier(var)
identifier.set_offset(src, caller_context.slither)
return identifier
elif name == "IndexAccess":
if is_compact_ast:
index_type = expression["typeDescriptions"]["typeString"]
left = expression["baseExpression"]
right = expression["indexExpression"]
else:
index_type = expression["attributes"]["type"]
children = expression["children"]
assert len(children) == 2
left = children[0]
right = children[1]
# IndexAccess is used to describe ElementaryTypeNameExpression
# if abi.decode is used
# For example, abi.decode(data, ...(uint[]) )
if right is None:
return parse_expression(left, caller_context)
left_expression = parse_expression(left, caller_context)
right_expression = parse_expression(right, caller_context)
index = IndexAccess(left_expression, right_expression, index_type)
index.set_offset(src, caller_context.slither)
return index
elif name == "MemberAccess":
if caller_context.is_compact_ast:
member_name = expression["memberName"]
member_type = expression["typeDescriptions"]["typeString"]
member_expression = parse_expression(
expression["expression"], caller_context
)
else:
member_name = expression["attributes"]["member_name"]
member_type = expression["attributes"]["type"]
children = expression["children"]
assert len(children) == 1
member_expression = parse_expression(children[0], caller_context)
if str(member_expression) == "super":
super_name = parse_super_name(expression, is_compact_ast)
var = find_variable(super_name, caller_context, is_super=True)
if var is None:
raise VariableNotFound("Variable not found: {}".format(super_name))
sup = SuperIdentifier(var)
sup.set_offset(src, caller_context.slither)
return sup
member_access = MemberAccess(member_name, member_type, member_expression)
member_access.set_offset(src, caller_context.slither)
if str(member_access) in SOLIDITY_VARIABLES_COMPOSED:
idx = Identifier(SolidityVariableComposed(str(member_access)))
idx.set_offset(src, caller_context.slither)
return idx
return member_access
elif name == "ElementaryTypeNameExpression":
return _parse_elementary_type_name_expression(
expression, is_compact_ast, caller_context
)
# NewExpression is not a root expression, it's always the child of another expression
elif name == "NewExpression":
if is_compact_ast:
type_name = expression["typeName"]
else:
children = expression["children"]
assert len(children) == 1
type_name = children[0]
if type_name[caller_context.get_key()] == "ArrayTypeName":
depth = 0
while type_name[caller_context.get_key()] == "ArrayTypeName":
# Note: dont conserve the size of the array if provided
# We compute it directly
if is_compact_ast:
type_name = type_name["baseType"]
else:
type_name = type_name["children"][0]
depth += 1
if type_name[caller_context.get_key()] == "ElementaryTypeName":
if is_compact_ast:
array_type = ElementaryType(type_name["name"])
else:
array_type = ElementaryType(type_name["attributes"]["name"])
elif type_name[caller_context.get_key()] == "UserDefinedTypeName":
if is_compact_ast:
array_type = parse_type(
UnknownType(type_name["name"]), caller_context
)
else:
array_type = parse_type(
UnknownType(type_name["attributes"]["name"]), caller_context
)
elif type_name[caller_context.get_key()] == "FunctionTypeName":
array_type = parse_type(type_name, caller_context)
else:
raise ParsingError("Incorrect type array {}".format(type_name))
array = NewArray(depth, array_type)
array.set_offset(src, caller_context.slither)
return array
if type_name[caller_context.get_key()] == "ElementaryTypeName":
if is_compact_ast:
elem_type = ElementaryType(type_name["name"])
else:
elem_type = ElementaryType(type_name["attributes"]["name"])
new_elem = NewElementaryType(elem_type)
new_elem.set_offset(src, caller_context.slither)
return new_elem
assert type_name[caller_context.get_key()] == "UserDefinedTypeName"
if is_compact_ast:
contract_name = type_name["name"]
else:
contract_name = type_name["attributes"]["name"]
new = NewContract(contract_name)
new.set_offset(src, caller_context.slither)
return new
elif name == "ModifierInvocation":
if is_compact_ast:
called = parse_expression(expression["modifierName"], caller_context)
arguments = []
if expression["arguments"]:
arguments = [
parse_expression(a, caller_context) for a in expression["arguments"]
]
else:
children = expression["children"]
called = parse_expression(children[0], caller_context)
arguments = [parse_expression(a, caller_context) for a in children[1::]]
call = CallExpression(called, arguments, "Modifier")
call.set_offset(src, caller_context.slither)
return call
raise ParsingError("Expression not parsed %s" % name)
|
def parse_expression(expression, caller_context):
"""
Returns:
str: expression
"""
# Expression
# = Expression ('++' | '--')
# | NewExpression
# | IndexAccess
# | MemberAccess
# | FunctionCall
# | '(' Expression ')'
# | ('!' | '~' | 'delete' | '++' | '--' | '+' | '-') Expression
# | Expression '**' Expression
# | Expression ('*' | '/' | '%') Expression
# | Expression ('+' | '-') Expression
# | Expression ('<<' | '>>') Expression
# | Expression '&' Expression
# | Expression '^' Expression
# | Expression '|' Expression
# | Expression ('<' | '>' | '<=' | '>=') Expression
# | Expression ('==' | '!=') Expression
# | Expression '&&' Expression
# | Expression '||' Expression
# | Expression '?' Expression ':' Expression
# | Expression ('=' | '|=' | '^=' | '&=' | '<<=' | '>>=' | '+=' | '-=' | '*=' | '/=' | '%=') Expression
# | PrimaryExpression
# The AST naming does not follow the spec
name = expression[caller_context.get_key()]
is_compact_ast = caller_context.is_compact_ast
src = expression["src"]
if name == "UnaryOperation":
if is_compact_ast:
attributes = expression
else:
attributes = expression["attributes"]
assert "prefix" in attributes
operation_type = UnaryOperationType.get_type(
attributes["operator"], attributes["prefix"]
)
if is_compact_ast:
expression = parse_expression(expression["subExpression"], caller_context)
else:
assert len(expression["children"]) == 1
expression = parse_expression(expression["children"][0], caller_context)
unary_op = UnaryOperation(expression, operation_type)
unary_op.set_offset(src, caller_context.slither)
return unary_op
elif name == "BinaryOperation":
if is_compact_ast:
attributes = expression
else:
attributes = expression["attributes"]
operation_type = BinaryOperationType.get_type(attributes["operator"])
if is_compact_ast:
left_expression = parse_expression(
expression["leftExpression"], caller_context
)
right_expression = parse_expression(
expression["rightExpression"], caller_context
)
else:
assert len(expression["children"]) == 2
left_expression = parse_expression(
expression["children"][0], caller_context
)
right_expression = parse_expression(
expression["children"][1], caller_context
)
binary_op = BinaryOperation(left_expression, right_expression, operation_type)
binary_op.set_offset(src, caller_context.slither)
return binary_op
elif name in "FunctionCall":
return parse_call(expression, caller_context)
elif name == "FunctionCallOptions":
# call/gas info are handled in parse_call
called = parse_expression(expression["expression"], caller_context)
assert isinstance(called, MemberAccess)
return called
elif name == "TupleExpression":
"""
For expression like
(a,,c) = (1,2,3)
the AST provides only two children in the left side
We check the type provided (tuple(uint256,,uint256))
To determine that there is an empty variable
Otherwhise we would not be able to determine that
a = 1, c = 3, and 2 is lost
Note: this is only possible with Solidity >= 0.4.12
"""
if is_compact_ast:
expressions = [
parse_expression(e, caller_context) if e else None
for e in expression["components"]
]
else:
if "children" not in expression:
attributes = expression["attributes"]
components = attributes["components"]
expressions = [
parse_expression(c, caller_context) if c else None
for c in components
]
else:
expressions = [
parse_expression(e, caller_context) for e in expression["children"]
]
# Add none for empty tuple items
if "attributes" in expression:
if "type" in expression["attributes"]:
t = expression["attributes"]["type"]
if ",," in t or "(," in t or ",)" in t:
t = t[len("tuple(") : -1]
elems = t.split(",")
for idx in range(len(elems)):
if elems[idx] == "":
expressions.insert(idx, None)
t = TupleExpression(expressions)
t.set_offset(src, caller_context.slither)
return t
elif name == "Conditional":
if is_compact_ast:
if_expression = parse_expression(expression["condition"], caller_context)
then_expression = parse_expression(
expression["trueExpression"], caller_context
)
else_expression = parse_expression(
expression["falseExpression"], caller_context
)
else:
children = expression["children"]
assert len(children) == 3
if_expression = parse_expression(children[0], caller_context)
then_expression = parse_expression(children[1], caller_context)
else_expression = parse_expression(children[2], caller_context)
conditional = ConditionalExpression(
if_expression, then_expression, else_expression
)
conditional.set_offset(src, caller_context.slither)
return conditional
elif name == "Assignment":
if is_compact_ast:
left_expression = parse_expression(
expression["leftHandSide"], caller_context
)
right_expression = parse_expression(
expression["rightHandSide"], caller_context
)
operation_type = AssignmentOperationType.get_type(expression["operator"])
operation_return_type = expression["typeDescriptions"]["typeString"]
else:
attributes = expression["attributes"]
children = expression["children"]
assert len(expression["children"]) == 2
left_expression = parse_expression(children[0], caller_context)
right_expression = parse_expression(children[1], caller_context)
operation_type = AssignmentOperationType.get_type(attributes["operator"])
operation_return_type = attributes["type"]
assignement = AssignmentOperation(
left_expression, right_expression, operation_type, operation_return_type
)
assignement.set_offset(src, caller_context.slither)
return assignement
elif name == "Literal":
subdenomination = None
assert "children" not in expression
if is_compact_ast:
value = expression["value"]
if value:
if "subdenomination" in expression and expression["subdenomination"]:
subdenomination = expression["subdenomination"]
elif not value and value != "":
value = "0x" + expression["hexValue"]
type = expression["typeDescriptions"]["typeString"]
# Length declaration for array was None until solc 0.5.5
if type is None:
if expression["kind"] == "number":
type = "int_const"
else:
value = expression["attributes"]["value"]
if value:
if (
"subdenomination" in expression["attributes"]
and expression["attributes"]["subdenomination"]
):
subdenomination = expression["attributes"]["subdenomination"]
elif value is None:
# for literal declared as hex
# see https://solidity.readthedocs.io/en/v0.4.25/types.html?highlight=hex#hexadecimal-literals
assert "hexvalue" in expression["attributes"]
value = "0x" + expression["attributes"]["hexvalue"]
type = expression["attributes"]["type"]
if type is None:
if value.isdecimal():
type = ElementaryType("uint256")
else:
type = ElementaryType("string")
elif type.startswith("int_const "):
type = ElementaryType("uint256")
elif type.startswith("bool"):
type = ElementaryType("bool")
elif type.startswith("address"):
type = ElementaryType("address")
else:
type = ElementaryType("string")
literal = Literal(value, type, subdenomination)
literal.set_offset(src, caller_context.slither)
return literal
elif name == "Identifier":
assert "children" not in expression
t = None
if caller_context.is_compact_ast:
value = expression["name"]
t = expression["typeDescriptions"]["typeString"]
else:
value = expression["attributes"]["value"]
if "type" in expression["attributes"]:
t = expression["attributes"]["type"]
if t:
found = re.findall(
"[struct|enum|function|modifier] \(([\[\] ()a-zA-Z0-9\.,_]*)\)", t
)
assert len(found) <= 1
if found:
value = value + "(" + found[0] + ")"
value = filter_name(value)
if "referencedDeclaration" in expression:
referenced_declaration = expression["referencedDeclaration"]
else:
referenced_declaration = None
var = find_variable(value, caller_context, referenced_declaration)
identifier = Identifier(var)
identifier.set_offset(src, caller_context.slither)
return identifier
elif name == "IndexAccess":
if is_compact_ast:
index_type = expression["typeDescriptions"]["typeString"]
left = expression["baseExpression"]
right = expression["indexExpression"]
else:
index_type = expression["attributes"]["type"]
children = expression["children"]
assert len(children) == 2
left = children[0]
right = children[1]
# IndexAccess is used to describe ElementaryTypeNameExpression
# if abi.decode is used
# For example, abi.decode(data, ...(uint[]) )
if right is None:
return parse_expression(left, caller_context)
left_expression = parse_expression(left, caller_context)
right_expression = parse_expression(right, caller_context)
index = IndexAccess(left_expression, right_expression, index_type)
index.set_offset(src, caller_context.slither)
return index
elif name == "MemberAccess":
if caller_context.is_compact_ast:
member_name = expression["memberName"]
member_type = expression["typeDescriptions"]["typeString"]
member_expression = parse_expression(
expression["expression"], caller_context
)
else:
member_name = expression["attributes"]["member_name"]
member_type = expression["attributes"]["type"]
children = expression["children"]
assert len(children) == 1
member_expression = parse_expression(children[0], caller_context)
if str(member_expression) == "super":
super_name = parse_super_name(expression, is_compact_ast)
var = find_variable(super_name, caller_context, is_super=True)
if var is None:
raise VariableNotFound("Variable not found: {}".format(super_name))
sup = SuperIdentifier(var)
sup.set_offset(src, caller_context.slither)
return sup
member_access = MemberAccess(member_name, member_type, member_expression)
member_access.set_offset(src, caller_context.slither)
if str(member_access) in SOLIDITY_VARIABLES_COMPOSED:
idx = Identifier(SolidityVariableComposed(str(member_access)))
idx.set_offset(src, caller_context.slither)
return idx
return member_access
elif name == "ElementaryTypeNameExpression":
return _parse_elementary_type_name_expression(
expression, is_compact_ast, caller_context
)
# NewExpression is not a root expression, it's always the child of another expression
elif name == "NewExpression":
if is_compact_ast:
type_name = expression["typeName"]
else:
children = expression["children"]
assert len(children) == 1
type_name = children[0]
if type_name[caller_context.get_key()] == "ArrayTypeName":
depth = 0
while type_name[caller_context.get_key()] == "ArrayTypeName":
# Note: dont conserve the size of the array if provided
# We compute it directly
if is_compact_ast:
type_name = type_name["baseType"]
else:
type_name = type_name["children"][0]
depth += 1
if type_name[caller_context.get_key()] == "ElementaryTypeName":
if is_compact_ast:
array_type = ElementaryType(type_name["name"])
else:
array_type = ElementaryType(type_name["attributes"]["name"])
elif type_name[caller_context.get_key()] == "UserDefinedTypeName":
if is_compact_ast:
array_type = parse_type(
UnknownType(type_name["name"]), caller_context
)
else:
array_type = parse_type(
UnknownType(type_name["attributes"]["name"]), caller_context
)
elif type_name[caller_context.get_key()] == "FunctionTypeName":
array_type = parse_type(type_name, caller_context)
else:
raise ParsingError("Incorrect type array {}".format(type_name))
array = NewArray(depth, array_type)
array.set_offset(src, caller_context.slither)
return array
if type_name[caller_context.get_key()] == "ElementaryTypeName":
if is_compact_ast:
elem_type = ElementaryType(type_name["name"])
else:
elem_type = ElementaryType(type_name["attributes"]["name"])
new_elem = NewElementaryType(elem_type)
new_elem.set_offset(src, caller_context.slither)
return new_elem
assert type_name[caller_context.get_key()] == "UserDefinedTypeName"
if is_compact_ast:
contract_name = type_name["name"]
else:
contract_name = type_name["attributes"]["name"]
new = NewContract(contract_name)
new.set_offset(src, caller_context.slither)
return new
elif name == "ModifierInvocation":
if is_compact_ast:
called = parse_expression(expression["modifierName"], caller_context)
arguments = []
if expression["arguments"]:
arguments = [
parse_expression(a, caller_context) for a in expression["arguments"]
]
else:
children = expression["children"]
called = parse_expression(children[0], caller_context)
arguments = [parse_expression(a, caller_context) for a in children[1::]]
call = CallExpression(called, arguments, "Modifier")
call.set_offset(src, caller_context.slither)
return call
raise ParsingError("Expression not parsed %s" % name)
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def _visit_call_expression(self, expression):
self._visit_expression(expression.called)
for arg in expression.arguments:
if arg:
self._visit_expression(arg)
if expression.call_value:
self._visit_expression(expression.call_value)
if expression.call_gas:
self._visit_expression(expression.call_gas)
if expression.call_salt:
self._visit_expression(expression.call_salt)
|
def _visit_call_expression(self, expression):
self._visit_expression(expression.called)
for arg in expression.arguments:
if arg:
self._visit_expression(arg)
if expression.call_value:
self._visit_expression(expression.call_value)
if expression.call_gas:
self._visit_expression(expression.call_gas)
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def _post_call_expression(self, expression):
called = get(expression.called)
args = [get(a) for a in expression.arguments if a]
for arg in args:
arg_ = Argument(arg)
arg_.set_expression(expression)
self._result.append(arg_)
if isinstance(called, Function):
# internal call
# If tuple
if (
expression.type_call.startswith("tuple(")
and expression.type_call != "tuple()"
):
val = TupleVariable(self._node)
else:
val = TemporaryVariable(self._node)
internal_call = InternalCall(called, len(args), val, expression.type_call)
internal_call.set_expression(expression)
self._result.append(internal_call)
set_val(expression, val)
else:
# If tuple
if (
expression.type_call.startswith("tuple(")
and expression.type_call != "tuple()"
):
val = TupleVariable(self._node)
else:
val = TemporaryVariable(self._node)
message_call = TmpCall(called, len(args), val, expression.type_call)
message_call.set_expression(expression)
# Gas/value are only accessible here if the syntax {gas: , value: }
# Is used over .gas().value()
if expression.call_gas:
call_gas = get(expression.call_gas)
message_call.call_gas = call_gas
if expression.call_value:
call_value = get(expression.call_value)
message_call.call_value = call_value
if expression.call_salt:
call_salt = get(expression.call_salt)
message_call.call_salt = call_salt
self._result.append(message_call)
set_val(expression, val)
|
def _post_call_expression(self, expression):
called = get(expression.called)
args = [get(a) for a in expression.arguments if a]
for arg in args:
arg_ = Argument(arg)
arg_.set_expression(expression)
self._result.append(arg_)
if isinstance(called, Function):
# internal call
# If tuple
if (
expression.type_call.startswith("tuple(")
and expression.type_call != "tuple()"
):
val = TupleVariable(self._node)
else:
val = TemporaryVariable(self._node)
internal_call = InternalCall(called, len(args), val, expression.type_call)
internal_call.set_expression(expression)
self._result.append(internal_call)
set_val(expression, val)
else:
# If tuple
if (
expression.type_call.startswith("tuple(")
and expression.type_call != "tuple()"
):
val = TupleVariable(self._node)
else:
val = TemporaryVariable(self._node)
message_call = TmpCall(called, len(args), val, expression.type_call)
message_call.set_expression(expression)
# Gas/value are only accessible here if the syntax {gas: , value: }
# Is used over .gas().value()
if expression.call_gas:
call_gas = get(expression.call_gas)
message_call.call_gas = call_gas
if expression.call_value:
call_value = get(expression.call_value)
message_call.call_value = call_value
self._result.append(message_call)
set_val(expression, val)
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def _post_new_contract(self, expression):
val = TemporaryVariable(self._node)
operation = TmpNewContract(expression.contract_name, val)
operation.set_expression(expression)
if expression.call_value:
call_value = get(expression.call_value)
operation.call_value = call_value
if expression.call_salt:
call_salt = get(expression.call_salt)
operation.call_salt = call_salt
self._result.append(operation)
set_val(expression, val)
|
def _post_new_contract(self, expression):
val = TemporaryVariable(self._node)
operation = TmpNewContract(expression.contract_name, val)
operation.set_expression(expression)
self._result.append(operation)
set_val(expression, val)
|
https://github.com/crytic/slither/issues/485
|
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 606, in main_impl
printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 68, in process_all
compilation, args, detector_classes, printer_classes)
File "/usr/local/lib/python3.7/site-packages/slither/__main__.py", line 55, in process_single
**vars(args))
File "/usr/local/lib/python3.7/site-packages/slither/slither.py", line 86, in __init__
self._analyze_contracts()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 254, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 332, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/slitherSolc.py", line 372, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/contract.py", line 291, in analyze_content_functions
function.analyze_content()
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/declarations/function.py", line 240, in analyze_content
node.analyze_expressions(self)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/cfg/node.py", line 31, in analyze_expressions
expression = parse_expression(self._unparsed_expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 417, in parse_expression
return parse_call(expression, caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 271, in parse_call
called = parse_expression(expression['expression'], caller_context)
File "/usr/local/lib/python3.7/site-packages/slither/solc_parsing/expressions/expression_parsing.py", line 422, in parse_expression
assert isinstance(called, MemberAccess)
AssertionError
|
AssertionError
|
def choose_printers(args, all_printer_classes):
printers_to_run = []
# disable default printer
if args.printers_to_run is None:
return []
if args.printers_to_run == "all":
return all_printer_classes
printers = {p.ARGUMENT: p for p in all_printer_classes}
for p in args.printers_to_run.split(","):
if p in printers:
printers_to_run.append(printers[p])
else:
raise Exception("Error: {} is not a printer".format(p))
return printers_to_run
|
def choose_printers(args, all_printer_classes):
printers_to_run = []
# disable default printer
if args.printers_to_run is None:
return []
printers = {p.ARGUMENT: p for p in all_printer_classes}
for p in args.printers_to_run.split(","):
if p in printers:
printers_to_run.append(printers[p])
else:
raise Exception("Error: {} is not a printer".format(p))
return printers_to_run
|
https://github.com/crytic/slither/issues/207
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 512, in main_impl
extension = "*.sol" if not args.solc_ast else "*.json"
AttributeError: 'Namespace' object has no attribute 'solc_ast'
|
AttributeError
|
def parse_args(detector_classes, printer_classes):
parser = argparse.ArgumentParser(
description="Slither. For usage information, see https://github.com/crytic/slither/wiki/Usage",
usage="slither.py contract.sol [flag]",
)
parser.add_argument("filename", help="contract.sol")
cryticparser.init(parser)
parser.add_argument(
"--version",
help="displays the current version",
version=require("slither-analyzer")[0].version,
action="version",
)
group_detector = parser.add_argument_group("Detectors")
group_printer = parser.add_argument_group("Printers")
group_misc = parser.add_argument_group("Additional option")
group_detector.add_argument(
"--detect",
help="Comma-separated list of detectors, defaults to all, "
"available detectors: {}".format(
", ".join(d.ARGUMENT for d in detector_classes)
),
action="store",
dest="detectors_to_run",
default=defaults_flag_in_config["detectors_to_run"],
)
group_printer.add_argument(
"--print",
help="Comma-separated list fo contract information printers, "
"available printers: {}".format(", ".join(d.ARGUMENT for d in printer_classes)),
action="store",
dest="printers_to_run",
default=defaults_flag_in_config["printers_to_run"],
)
group_detector.add_argument(
"--list-detectors",
help="List available detectors",
action=ListDetectors,
nargs=0,
default=False,
)
group_printer.add_argument(
"--list-printers",
help="List available printers",
action=ListPrinters,
nargs=0,
default=False,
)
group_detector.add_argument(
"--exclude",
help="Comma-separated list of detectors that should be excluded",
action="store",
dest="detectors_to_exclude",
default=defaults_flag_in_config["detectors_to_exclude"],
)
group_detector.add_argument(
"--exclude-informational",
help="Exclude informational impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_informational"],
)
group_detector.add_argument(
"--exclude-low",
help="Exclude low impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_low"],
)
group_detector.add_argument(
"--exclude-medium",
help="Exclude medium impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_medium"],
)
group_detector.add_argument(
"--exclude-high",
help="Exclude high impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_high"],
)
group_misc.add_argument(
"--json",
help="Export results as JSON",
action="store",
default=defaults_flag_in_config["json"],
)
group_misc.add_argument(
"--disable-color",
help="Disable output colorization",
action="store_true",
default=defaults_flag_in_config["disable_color"],
)
group_misc.add_argument(
"--filter-paths",
help="Comma-separated list of paths for which results will be excluded",
action="store",
dest="filter_paths",
default=defaults_flag_in_config["filter_paths"],
)
group_misc.add_argument(
"--triage-mode",
help="Run triage mode (save results in slither.db.json)",
action="store_true",
dest="triage_mode",
default=False,
)
group_misc.add_argument(
"--config-file",
help="Provide a config file (default: slither.config.json)",
action="store",
dest="config_file",
default="slither.config.json",
)
group_misc.add_argument(
"--solc-ast",
help="Provide the contract as a json AST",
action="store_true",
default=False,
)
# debugger command
parser.add_argument(
"--debug", help=argparse.SUPPRESS, action="store_true", default=False
)
parser.add_argument(
"--markdown", help=argparse.SUPPRESS, action=OutputMarkdown, default=False
)
group_misc.add_argument(
"--checklist", help=argparse.SUPPRESS, action="store_true", default=False
)
parser.add_argument(
"--wiki-detectors", help=argparse.SUPPRESS, action=OutputWiki, default=False
)
parser.add_argument(
"--list-detectors-json",
help=argparse.SUPPRESS,
action=ListDetectorsJson,
nargs=0,
default=False,
)
parser.add_argument(
"--legacy-ast",
help=argparse.SUPPRESS,
action="store_true",
default=defaults_flag_in_config["legacy_ast"],
)
parser.add_argument(
"--ignore-return-value",
help=argparse.SUPPRESS,
action="store_true",
default=defaults_flag_in_config["ignore_return_value"],
)
# if the json is splitted in different files
parser.add_argument(
"--splitted", help=argparse.SUPPRESS, action="store_true", default=False
)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
args = parser.parse_args()
if os.path.isfile(args.config_file):
try:
with open(args.config_file) as f:
config = json.load(f)
for key, elem in config.items():
if key not in defaults_flag_in_config:
logger.info(
yellow(
"{} has an unknown key: {} : {}".format(
args.config_file, key, elem
)
)
)
continue
if getattr(args, key) == defaults_flag_in_config[key]:
setattr(args, key, elem)
except json.decoder.JSONDecodeError as e:
logger.error(
red(
"Impossible to read {}, please check the file {}".format(
args.config_file, e
)
)
)
return args
|
def parse_args(detector_classes, printer_classes):
parser = argparse.ArgumentParser(
description="Slither. For usage information, see https://github.com/crytic/slither/wiki/Usage",
usage="slither.py contract.sol [flag]",
)
parser.add_argument("filename", help="contract.sol")
cryticparser.init(parser)
parser.add_argument(
"--version",
help="displays the current version",
version=require("slither-analyzer")[0].version,
action="version",
)
group_detector = parser.add_argument_group("Detectors")
group_printer = parser.add_argument_group("Printers")
group_misc = parser.add_argument_group("Additional option")
group_detector.add_argument(
"--detect",
help="Comma-separated list of detectors, defaults to all, "
"available detectors: {}".format(
", ".join(d.ARGUMENT for d in detector_classes)
),
action="store",
dest="detectors_to_run",
default=defaults_flag_in_config["detectors_to_run"],
)
group_printer.add_argument(
"--print",
help="Comma-separated list fo contract information printers, "
"available printers: {}".format(", ".join(d.ARGUMENT for d in printer_classes)),
action="store",
dest="printers_to_run",
default=defaults_flag_in_config["printers_to_run"],
)
group_detector.add_argument(
"--list-detectors",
help="List available detectors",
action=ListDetectors,
nargs=0,
default=False,
)
group_printer.add_argument(
"--list-printers",
help="List available printers",
action=ListPrinters,
nargs=0,
default=False,
)
group_detector.add_argument(
"--exclude",
help="Comma-separated list of detectors that should be excluded",
action="store",
dest="detectors_to_exclude",
default=defaults_flag_in_config["detectors_to_exclude"],
)
group_detector.add_argument(
"--exclude-informational",
help="Exclude informational impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_informational"],
)
group_detector.add_argument(
"--exclude-low",
help="Exclude low impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_low"],
)
group_detector.add_argument(
"--exclude-medium",
help="Exclude medium impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_medium"],
)
group_detector.add_argument(
"--exclude-high",
help="Exclude high impact analyses",
action="store_true",
default=defaults_flag_in_config["exclude_high"],
)
group_misc.add_argument(
"--json",
help="Export results as JSON",
action="store",
default=defaults_flag_in_config["json"],
)
group_misc.add_argument(
"--disable-color",
help="Disable output colorization",
action="store_true",
default=defaults_flag_in_config["disable_color"],
)
group_misc.add_argument(
"--filter-paths",
help="Comma-separated list of paths for which results will be excluded",
action="store",
dest="filter_paths",
default=defaults_flag_in_config["filter_paths"],
)
group_misc.add_argument(
"--triage-mode",
help="Run triage mode (save results in slither.db.json)",
action="store_true",
dest="triage_mode",
default=False,
)
group_misc.add_argument(
"--config-file",
help="Provide a config file (default: slither.config.json)",
action="store",
dest="config_file",
default="slither.config.json",
)
# debugger command
parser.add_argument(
"--debug", help=argparse.SUPPRESS, action="store_true", default=False
)
parser.add_argument(
"--markdown", help=argparse.SUPPRESS, action=OutputMarkdown, default=False
)
group_misc.add_argument(
"--checklist", help=argparse.SUPPRESS, action="store_true", default=False
)
parser.add_argument(
"--wiki-detectors", help=argparse.SUPPRESS, action=OutputWiki, default=False
)
parser.add_argument(
"--list-detectors-json",
help=argparse.SUPPRESS,
action=ListDetectorsJson,
nargs=0,
default=False,
)
parser.add_argument(
"--legacy-ast",
help=argparse.SUPPRESS,
action="store_true",
default=defaults_flag_in_config["legacy_ast"],
)
parser.add_argument(
"--ignore-return-value",
help=argparse.SUPPRESS,
action="store_true",
default=False,
)
# if the json is splitted in different files
parser.add_argument(
"--splitted", help=argparse.SUPPRESS, action="store_true", default=False
)
if len(sys.argv) == 1:
parser.print_help(sys.stderr)
sys.exit(1)
args = parser.parse_args()
if os.path.isfile(args.config_file):
try:
with open(args.config_file) as f:
config = json.load(f)
for key, elem in config.items():
if key not in defaults_flag_in_config:
logger.info(
yellow(
"{} has an unknown key: {} : {}".format(
args.config_file, key, elem
)
)
)
continue
if getattr(args, key) == defaults_flag_in_config[key]:
setattr(args, key, elem)
except json.decoder.JSONDecodeError as e:
logger.error(
red(
"Impossible to read {}, please check the file {}".format(
args.config_file, e
)
)
)
return args
|
https://github.com/crytic/slither/issues/207
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 512, in main_impl
extension = "*.sol" if not args.solc_ast else "*.json"
AttributeError: 'Namespace' object has no attribute 'solc_ast'
|
AttributeError
|
def process_truffle(dirname, args, detector_classes, printer_classes):
# Truffle on windows has naming conflicts where it will invoke truffle.js directly instead
# of truffle.cmd (unless in powershell or git bash). The cleanest solution is to explicitly call
# truffle.cmd. Reference:
# https://truffleframework.com/docs/truffle/reference/configuration#resolving-naming-conflicts-on-windows
if not args.ignore_truffle_compile:
truffle_base_command = (
"truffle" if platform.system() != "Windows" else "truffle.cmd"
)
cmd = [truffle_base_command, "compile"]
if args.truffle_version:
cmd = ["npx", args.truffle_version, "compile"]
elif os.path.isfile("package.json"):
with open("package.json") as f:
package = json.load(f)
if "devDependencies" in package:
if "truffle" in package["devDependencies"]:
version = package["devDependencies"]["truffle"]
if version.startswith("^"):
version = version[1:]
truffle_version = "truffle@{}".format(version)
cmd = ["npx", truffle_version, "compile"]
logger.info(
"'{}' running (use --truffle-version truffle@x.x.x to use specific version)".format(
" ".join(cmd)
)
)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr = (
stdout.decode(),
stderr.decode(),
) # convert bytestrings to unicode strings
logger.info(stdout)
if stderr:
logger.error(stderr)
slither = Slither(
dirname,
solc=args.solc,
disable_solc_warnings=args.disable_solc_warnings,
solc_arguments=args.solc_args,
is_truffle=True,
filter_paths=parse_filter_paths(args),
triage_mode=args.triage_mode,
)
return _process(slither, detector_classes, printer_classes)
|
def process_truffle(dirname, args, detector_classes, printer_classes):
if not args.ignore_truffle_compile:
cmd = ["truffle", "compile"]
if args.truffle_version:
cmd = ["npx", args.truffle_version, "compile"]
elif os.path.isfile("package.json"):
with open("package.json") as f:
package = json.load(f)
if "devDependencies" in package:
if "truffle" in package["devDependencies"]:
version = package["devDependencies"]["truffle"]
if version.startswith("^"):
version = version[1:]
truffle_version = "truffle@{}".format(version)
cmd = ["npx", truffle_version, "compile"]
logger.info(
"'{}' running (use --truffle-version truffle@x.x.x to use specific version)".format(
" ".join(cmd)
)
)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout, stderr = (
stdout.decode(),
stderr.decode(),
) # convert bytestrings to unicode strings
logger.info(stdout)
if stderr:
logger.error(stderr)
slither = Slither(
dirname,
solc=args.solc,
disable_solc_warnings=args.disable_solc_warnings,
solc_arguments=args.solc_args,
is_truffle=True,
filter_paths=parse_filter_paths(args),
triage_mode=args.triage_mode,
)
return _process(slither, detector_classes, printer_classes)
|
https://github.com/crytic/slither/issues/173
|
INFO:Slither:'truffle compile' running (use --truffle-version truffle@x.x.x to use specific version)
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 471, in main_impl
(results, number_contracts) = process_truffle(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 87, in process_truffle
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
File "C:\Users\Vyper\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 769, in __init__
restore_signals, start_new_session)
File "C:\Users\Vyper\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1172, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
|
FileNotFoundError
|
def __init__(self, t, length):
assert isinstance(t, Type)
if length:
if isinstance(length, int):
length = Literal(length)
assert isinstance(length, Expression)
if not isinstance(length, Literal):
cf = ConstantFolding(length)
length = cf.result()
super(ArrayType, self).__init__()
self._type = t
self._length = length
|
def __init__(self, t, length):
assert isinstance(t, Type)
if length:
if isinstance(length, int):
length = Literal(length)
assert isinstance(length, Expression)
super(ArrayType, self).__init__()
self._type = t
self._length = length
|
https://github.com/crytic/slither/issues/144
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 278, in main_impl
(results_tmp, number_contracts_tmp) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 40, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 210, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 294, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 329, in _analyze_variables_modifiers_functions
contract.analyze_params_functions()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 348, in analyze_params_functions
self._functions[function.full_name] = function
File "c:\users\vyper\documents\github\slither\slither\core\declarations\function.py", line 358, in full_name
name, parameters, _ = self.signature
File "c:\users\vyper\documents\github\slither\slither\core\declarations\function.py", line 341, in signature
return self.name, [str(x.type) for x in self.parameters], [str(x.type) for x in self.returns]
File "c:\users\vyper\documents\github\slither\slither\core\declarations\function.py", line 341, in <listcomp>
return self.name, [str(x.type) for x in self.parameters], [str(x.type) for x in self.returns]
File "c:\users\vyper\documents\github\slither\slither\core\solidity_types\array_type.py", line 25, in __str__
if isinstance(self._length.value, Variable) and self._length.value.is_constant:
AttributeError: 'BinaryOperation' object has no attribute 'value'
|
AttributeError
|
def __init__(self, function, contract):
super(FunctionSolc, self).__init__()
self._contract = contract
if self.is_compact_ast:
self._name = function["name"]
else:
self._name = function["attributes"][self.get_key()]
self._functionNotParsed = function
self._params_was_analyzed = False
self._content_was_analyzed = False
self._counter_nodes = 0
self._counter_scope_local_variables = 0
# variable renamed will map the solc id
# to the variable. It only works for compact format
# Later if an expression provides the referencedDeclaration attr
# we can retrieve the variable
# It only matters if two variables have the same name in the function
# which is only possible with solc > 0.5
self._variables_renamed = {}
|
def __init__(self, function, contract):
super(FunctionSolc, self).__init__()
self._contract = contract
if self.is_compact_ast:
self._name = function["name"]
else:
self._name = function["attributes"][self.get_key()]
self._functionNotParsed = function
self._params_was_analyzed = False
self._content_was_analyzed = False
self._counter_nodes = 0
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def _parse_variable_definition(self, statement, node):
try:
local_var = LocalVariableSolc(statement)
local_var.set_function(self)
local_var.set_offset(statement["src"], self.contract.slither)
self._add_local_variable(local_var)
# local_var.analyze(self)
new_node = self._new_node(NodeType.VARIABLE, statement["src"])
new_node.add_variable_declaration(local_var)
link_nodes(node, new_node)
return new_node
except MultipleVariablesDeclaration:
# Custom handling of var (a,b) = .. style declaration
if self.is_compact_ast:
variables = statement["declarations"]
count = len(variables)
if statement["initialValue"]["nodeType"] == "TupleExpression":
inits = statement["initialValue"]["components"]
i = 0
new_node = node
for variable in variables:
init = inits[i]
src = variable["src"]
i = i + 1
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
"initialValue": init,
}
new_node = self._parse_variable_definition(new_statement, new_node)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
variables = []
i = 0
new_node = node
for variable in statement["declarations"]:
i = i + 1
if variable:
src = variable["src"]
# Create a fake statement to be consistent
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node
)
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
identifier = {
"nodeType": "Identifier",
"src": v["src"],
"name": v["name"],
"typeDescriptions": {
"typeString": v["typeDescriptions"]["typeString"]
},
}
var_identifiers.append(identifier)
tuple_expression = {
"nodeType": "TupleExpression",
"src": statement["src"],
"components": var_identifiers,
}
expression = {
"nodeType": "Assignment",
"src": statement["src"],
"operator": "=",
"type": "tuple()",
"leftHandSide": tuple_expression,
"rightHandSide": statement["initialValue"],
"typeDescriptions": {"typeString": "tuple()"},
}
node = new_node
new_node = self._new_node(NodeType.EXPRESSION, statement["src"])
new_node.add_unparsed_expression(expression)
link_nodes(node, new_node)
else:
count = 0
children = statement[self.get_children("children")]
child = children[0]
while child[self.get_key()] == "VariableDeclaration":
count = count + 1
child = children[count]
assert len(children) == (count + 1)
tuple_vars = children[count]
variables_declaration = children[0:count]
i = 0
new_node = node
if tuple_vars[self.get_key()] == "TupleExpression":
assert len(tuple_vars[self.get_children("children")]) == count
for variable in variables_declaration:
init = tuple_vars[self.get_children("children")][i]
src = variable["src"]
i = i + 1
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable, init],
}
new_node = self._parse_variable_definition(new_statement, new_node)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
assert tuple_vars[self.get_key()] in ["FunctionCall", "Conditional"]
variables = []
for variable in variables_declaration:
src = variable["src"]
i = i + 1
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node
)
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
identifier = {
self.get_key(): "Identifier",
"src": v["src"],
"attributes": {
"value": v["attributes"][self.get_key()],
"type": v["attributes"]["type"],
},
}
var_identifiers.append(identifier)
expression = {
self.get_key(): "Assignment",
"src": statement["src"],
"attributes": {"operator": "=", "type": "tuple()"},
self.get_children("children"): [
{
self.get_key(): "TupleExpression",
"src": statement["src"],
self.get_children("children"): var_identifiers,
},
tuple_vars,
],
}
node = new_node
new_node = self._new_node(NodeType.EXPRESSION, statement["src"])
new_node.add_unparsed_expression(expression)
link_nodes(node, new_node)
return new_node
|
def _parse_variable_definition(self, statement, node):
try:
local_var = LocalVariableSolc(statement)
local_var.set_function(self)
local_var.set_offset(statement["src"], self.contract.slither)
self._variables[local_var.name] = local_var
# local_var.analyze(self)
new_node = self._new_node(NodeType.VARIABLE, statement["src"])
new_node.add_variable_declaration(local_var)
link_nodes(node, new_node)
return new_node
except MultipleVariablesDeclaration:
# Custom handling of var (a,b) = .. style declaration
if self.is_compact_ast:
variables = statement["declarations"]
count = len(variables)
if statement["initialValue"]["nodeType"] == "TupleExpression":
inits = statement["initialValue"]["components"]
i = 0
new_node = node
for variable in variables:
init = inits[i]
src = variable["src"]
i = i + 1
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
"initialValue": init,
}
new_node = self._parse_variable_definition(new_statement, new_node)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
variables = []
i = 0
new_node = node
for variable in statement["declarations"]:
i = i + 1
if variable:
src = variable["src"]
# Create a fake statement to be consistent
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node
)
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
identifier = {
"nodeType": "Identifier",
"src": v["src"],
"name": v["name"],
"typeDescriptions": {
"typeString": v["typeDescriptions"]["typeString"]
},
}
var_identifiers.append(identifier)
tuple_expression = {
"nodeType": "TupleExpression",
"src": statement["src"],
"components": var_identifiers,
}
expression = {
"nodeType": "Assignment",
"src": statement["src"],
"operator": "=",
"type": "tuple()",
"leftHandSide": tuple_expression,
"rightHandSide": statement["initialValue"],
"typeDescriptions": {"typeString": "tuple()"},
}
node = new_node
new_node = self._new_node(NodeType.EXPRESSION, statement["src"])
new_node.add_unparsed_expression(expression)
link_nodes(node, new_node)
else:
count = 0
children = statement[self.get_children("children")]
child = children[0]
while child[self.get_key()] == "VariableDeclaration":
count = count + 1
child = children[count]
assert len(children) == (count + 1)
tuple_vars = children[count]
variables_declaration = children[0:count]
i = 0
new_node = node
if tuple_vars[self.get_key()] == "TupleExpression":
assert len(tuple_vars[self.get_children("children")]) == count
for variable in variables_declaration:
init = tuple_vars[self.get_children("children")][i]
src = variable["src"]
i = i + 1
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable, init],
}
new_node = self._parse_variable_definition(new_statement, new_node)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
assert tuple_vars[self.get_key()] in ["FunctionCall", "Conditional"]
variables = []
for variable in variables_declaration:
src = variable["src"]
i = i + 1
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node
)
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
identifier = {
self.get_key(): "Identifier",
"src": v["src"],
"attributes": {
"value": v["attributes"][self.get_key()],
"type": v["attributes"]["type"],
},
}
var_identifiers.append(identifier)
expression = {
self.get_key(): "Assignment",
"src": statement["src"],
"attributes": {"operator": "=", "type": "tuple()"},
self.get_children("children"): [
{
self.get_key(): "TupleExpression",
"src": statement["src"],
self.get_children("children"): var_identifiers,
},
tuple_vars,
],
}
node = new_node
new_node = self._new_node(NodeType.EXPRESSION, statement["src"])
new_node.add_unparsed_expression(expression)
link_nodes(node, new_node)
return new_node
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def _parse_variable_definition_init_tuple(self, statement, index, node):
local_var = LocalVariableInitFromTupleSolc(statement, index)
# local_var = LocalVariableSolc(statement[self.get_children('children')][0], statement[self.get_children('children')][1::])
local_var.set_function(self)
local_var.set_offset(statement["src"], self.contract.slither)
self._add_local_variable(local_var)
# local_var.analyze(self)
new_node = self._new_node(NodeType.VARIABLE, statement["src"])
new_node.add_variable_declaration(local_var)
link_nodes(node, new_node)
return new_node
|
def _parse_variable_definition_init_tuple(self, statement, index, node):
local_var = LocalVariableInitFromTupleSolc(statement, index)
# local_var = LocalVariableSolc(statement[self.get_children('children')][0], statement[self.get_children('children')][1::])
local_var.set_function(self)
local_var.set_offset(statement["src"], self.contract.slither)
self._variables[local_var.name] = local_var
# local_var.analyze(self)
new_node = self._new_node(NodeType.VARIABLE, statement["src"])
new_node.add_variable_declaration(local_var)
link_nodes(node, new_node)
return new_node
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def _parse_params(self, params):
assert params[self.get_key()] == "ParameterList"
if self.is_compact_ast:
params = params["parameters"]
else:
params = params[self.get_children("children")]
for param in params:
assert param[self.get_key()] == "VariableDeclaration"
local_var = LocalVariableSolc(param)
local_var.set_function(self)
local_var.set_offset(param["src"], self.contract.slither)
local_var.analyze(self)
# see https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
if local_var.location == "default":
local_var.set_location("memory")
self._add_local_variable(local_var)
self._parameters.append(local_var)
|
def _parse_params(self, params):
assert params[self.get_key()] == "ParameterList"
if self.is_compact_ast:
params = params["parameters"]
else:
params = params[self.get_children("children")]
for param in params:
assert param[self.get_key()] == "VariableDeclaration"
local_var = LocalVariableSolc(param)
local_var.set_function(self)
local_var.set_offset(param["src"], self.contract.slither)
local_var.analyze(self)
# see https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
if local_var.location == "default":
local_var.set_location("memory")
self._variables[local_var.name] = local_var
self._parameters.append(local_var)
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def _parse_returns(self, returns):
assert returns[self.get_key()] == "ParameterList"
if self.is_compact_ast:
returns = returns["parameters"]
else:
returns = returns[self.get_children("children")]
for ret in returns:
assert ret[self.get_key()] == "VariableDeclaration"
local_var = LocalVariableSolc(ret)
local_var.set_function(self)
local_var.set_offset(ret["src"], self.contract.slither)
local_var.analyze(self)
# see https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
if local_var.location == "default":
local_var.set_location("memory")
self._add_local_variable(local_var)
self._returns.append(local_var)
|
def _parse_returns(self, returns):
assert returns[self.get_key()] == "ParameterList"
if self.is_compact_ast:
returns = returns["parameters"]
else:
returns = returns[self.get_children("children")]
for ret in returns:
assert ret[self.get_key()] == "VariableDeclaration"
local_var = LocalVariableSolc(ret)
local_var.set_function(self)
local_var.set_offset(ret["src"], self.contract.slither)
local_var.analyze(self)
# see https://solidity.readthedocs.io/en/v0.4.24/types.html?highlight=storage%20location#data-location
if local_var.location == "default":
local_var.set_location("memory")
self._variables[local_var.name] = local_var
self._returns.append(local_var)
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def find_variable(var_name, caller_context, referenced_declaration=None):
if isinstance(caller_context, Contract):
function = None
contract = caller_context
elif isinstance(caller_context, Function):
function = caller_context
contract = function.contract
else:
logger.error("Incorrect caller context")
exit(-1)
if function:
# We look for variable declared with the referencedDeclaration attr
func_variables = function.variables_renamed
if referenced_declaration and referenced_declaration in func_variables:
return func_variables[referenced_declaration]
# If not found, check for name
func_variables = function.variables_as_dict()
if var_name in func_variables:
return func_variables[var_name]
# A local variable can be a pointer
# for example
# function test(function(uint) internal returns(bool) t) interna{
# Will have a local variable t which will match the signature
# t(uint256)
func_variables_ptr = {get_pointer_name(f): f for f in function.variables}
if var_name and var_name in func_variables_ptr:
return func_variables_ptr[var_name]
contract_variables = contract.variables_as_dict()
if var_name in contract_variables:
return contract_variables[var_name]
# A state variable can be a pointer
conc_variables_ptr = {get_pointer_name(f): f for f in contract.variables}
if var_name and var_name in conc_variables_ptr:
return conc_variables_ptr[var_name]
functions = contract.functions_as_dict()
if var_name in functions:
return functions[var_name]
modifiers = contract.modifiers_as_dict()
if var_name in modifiers:
return modifiers[var_name]
structures = contract.structures_as_dict()
if var_name in structures:
return structures[var_name]
events = contract.events_as_dict()
if var_name in events:
return events[var_name]
enums = contract.enums_as_dict()
if var_name in enums:
return enums[var_name]
# If the enum is refered as its name rather than its canonicalName
enums = {e.name: e for e in contract.enums}
if var_name in enums:
return enums[var_name]
# Could refer to any enum
all_enums = [c.enums_as_dict() for c in contract.slither.contracts]
all_enums = {k: v for d in all_enums for k, v in d.items()}
if var_name in all_enums:
return all_enums[var_name]
if var_name in SOLIDITY_VARIABLES:
return SolidityVariable(var_name)
if var_name in SOLIDITY_FUNCTIONS:
return SolidityFunction(var_name)
contracts = contract.slither.contracts_as_dict()
if var_name in contracts:
return contracts[var_name]
if referenced_declaration:
for contract in contract.slither.contracts:
if contract.id == referenced_declaration:
return contract
raise VariableNotFound("Variable not found: {}".format(var_name))
|
def find_variable(var_name, caller_context, referenced_declaration=None):
if isinstance(caller_context, Contract):
function = None
contract = caller_context
elif isinstance(caller_context, Function):
function = caller_context
contract = function.contract
else:
logger.error("Incorrect caller context")
exit(-1)
if function:
func_variables = function.variables_as_dict()
if var_name in func_variables:
return func_variables[var_name]
# A local variable can be a pointer
# for example
# function test(function(uint) internal returns(bool) t) interna{
# Will have a local variable t which will match the signature
# t(uint256)
func_variables_ptr = {get_pointer_name(f): f for f in function.variables}
if var_name and var_name in func_variables_ptr:
return func_variables_ptr[var_name]
contract_variables = contract.variables_as_dict()
if var_name in contract_variables:
return contract_variables[var_name]
# A state variable can be a pointer
conc_variables_ptr = {get_pointer_name(f): f for f in contract.variables}
if var_name and var_name in conc_variables_ptr:
return conc_variables_ptr[var_name]
functions = contract.functions_as_dict()
if var_name in functions:
return functions[var_name]
modifiers = contract.modifiers_as_dict()
if var_name in modifiers:
return modifiers[var_name]
structures = contract.structures_as_dict()
if var_name in structures:
return structures[var_name]
events = contract.events_as_dict()
if var_name in events:
return events[var_name]
enums = contract.enums_as_dict()
if var_name in enums:
return enums[var_name]
# If the enum is refered as its name rather than its canonicalName
enums = {e.name: e for e in contract.enums}
if var_name in enums:
return enums[var_name]
# Could refer to any enum
all_enums = [c.enums_as_dict() for c in contract.slither.contracts]
all_enums = {k: v for d in all_enums for k, v in d.items()}
if var_name in all_enums:
return all_enums[var_name]
if var_name in SOLIDITY_VARIABLES:
return SolidityVariable(var_name)
if var_name in SOLIDITY_FUNCTIONS:
return SolidityFunction(var_name)
contracts = contract.slither.contracts_as_dict()
if var_name in contracts:
return contracts[var_name]
if referenced_declaration:
for contract in contract.slither.contracts:
if contract.id == referenced_declaration:
return contract
raise VariableNotFound("Variable not found: {}".format(var_name))
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def __init__(self, var):
"""
A variable can be declared through a statement, or directly.
If it is through a statement, the following children may contain
the init value.
It may be possible that the variable is declared through a statement,
but the init value is declared at the VariableDeclaration children level
"""
super(VariableDeclarationSolc, self).__init__()
self._was_analyzed = False
self._elem_to_parse = None
self._initializedNotParsed = None
self._is_compact_ast = False
self._reference_id = None
if "nodeType" in var:
self._is_compact_ast = True
nodeType = var["nodeType"]
if nodeType in ["VariableDeclarationStatement", "VariableDefinitionStatement"]:
if len(var["declarations"]) > 1:
raise MultipleVariablesDeclaration
init = None
if "initialValue" in var:
init = var["initialValue"]
self._init_from_declaration(var["declarations"][0], init)
elif nodeType == "VariableDeclaration":
self._init_from_declaration(var, var["value"])
else:
logger.error("Incorrect variable declaration type {}".format(nodeType))
exit(-1)
else:
nodeType = var["name"]
if nodeType in ["VariableDeclarationStatement", "VariableDefinitionStatement"]:
if len(var["children"]) == 2:
init = var["children"][1]
elif len(var["children"]) == 1:
init = None
elif len(var["children"]) > 2:
raise MultipleVariablesDeclaration
else:
logger.error("Variable declaration without children?" + var)
exit(-1)
declaration = var["children"][0]
self._init_from_declaration(declaration, init)
elif nodeType == "VariableDeclaration":
self._init_from_declaration(var, None)
else:
logger.error("Incorrect variable declaration type {}".format(nodeType))
exit(-1)
|
def __init__(self, var):
"""
A variable can be declared through a statement, or directly.
If it is through a statement, the following children may contain
the init value.
It may be possible that the variable is declared through a statement,
but the init value is declared at the VariableDeclaration children level
"""
super(VariableDeclarationSolc, self).__init__()
self._was_analyzed = False
self._elem_to_parse = None
self._initializedNotParsed = None
self._is_compact_ast = False
if "nodeType" in var:
self._is_compact_ast = True
nodeType = var["nodeType"]
if nodeType in ["VariableDeclarationStatement", "VariableDefinitionStatement"]:
if len(var["declarations"]) > 1:
raise MultipleVariablesDeclaration
init = None
if "initialValue" in var:
init = var["initialValue"]
self._init_from_declaration(var["declarations"][0], init)
elif nodeType == "VariableDeclaration":
self._init_from_declaration(var, var["value"])
else:
logger.error("Incorrect variable declaration type {}".format(nodeType))
exit(-1)
else:
nodeType = var["name"]
if nodeType in ["VariableDeclarationStatement", "VariableDefinitionStatement"]:
if len(var["children"]) == 2:
init = var["children"][1]
elif len(var["children"]) == 1:
init = None
elif len(var["children"]) > 2:
raise MultipleVariablesDeclaration
else:
logger.error("Variable declaration without children?" + var)
exit(-1)
declaration = var["children"][0]
self._init_from_declaration(declaration, init)
elif nodeType == "VariableDeclaration":
self._init_from_declaration(var, None)
else:
logger.error("Incorrect variable declaration type {}".format(nodeType))
exit(-1)
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def _init_from_declaration(self, var, init):
if self._is_compact_ast:
attributes = var
self._typeName = attributes["typeDescriptions"]["typeString"]
else:
assert len(var["children"]) <= 2
assert var["name"] == "VariableDeclaration"
attributes = var["attributes"]
self._typeName = attributes["type"]
self._name = attributes["name"]
self._arrayDepth = 0
self._isMapping = False
self._mappingFrom = None
self._mappingTo = False
self._initial_expression = None
self._type = None
# Only for comapct ast format
# the id can be used later if referencedDeclaration
# is provided
if "id" in var:
self._reference_id = var["id"]
if "constant" in attributes:
self._is_constant = attributes["constant"]
self._analyze_variable_attributes(attributes)
if self._is_compact_ast:
if var["typeName"]:
self._elem_to_parse = var["typeName"]
else:
self._elem_to_parse = UnknownType(var["typeDescriptions"]["typeString"])
else:
if not var["children"]:
# It happens on variable declared inside loop declaration
try:
self._type = ElementaryType(self._typeName)
self._elem_to_parse = None
except NonElementaryType:
self._elem_to_parse = UnknownType(self._typeName)
else:
self._elem_to_parse = var["children"][0]
if self._is_compact_ast:
self._initializedNotParsed = init
if init:
self._initialized = True
else:
if init: # there are two way to init a var local in the AST
assert len(var["children"]) <= 1
self._initialized = True
self._initializedNotParsed = init
elif len(var["children"]) in [0, 1]:
self._initialized = False
self._initializedNotParsed = []
else:
assert len(var["children"]) == 2
self._initialized = True
self._initializedNotParsed = var["children"][1]
|
def _init_from_declaration(self, var, init):
if self._is_compact_ast:
attributes = var
self._typeName = attributes["typeDescriptions"]["typeString"]
else:
assert len(var["children"]) <= 2
assert var["name"] == "VariableDeclaration"
attributes = var["attributes"]
self._typeName = attributes["type"]
self._name = attributes["name"]
self._arrayDepth = 0
self._isMapping = False
self._mappingFrom = None
self._mappingTo = False
self._initial_expression = None
self._type = None
if "constant" in attributes:
self._is_constant = attributes["constant"]
self._analyze_variable_attributes(attributes)
if self._is_compact_ast:
if var["typeName"]:
self._elem_to_parse = var["typeName"]
else:
self._elem_to_parse = UnknownType(var["typeDescriptions"]["typeString"])
else:
if not var["children"]:
# It happens on variable declared inside loop declaration
try:
self._type = ElementaryType(self._typeName)
self._elem_to_parse = None
except NonElementaryType:
self._elem_to_parse = UnknownType(self._typeName)
else:
self._elem_to_parse = var["children"][0]
if self._is_compact_ast:
self._initializedNotParsed = init
if init:
self._initialized = True
else:
if init: # there are two way to init a var local in the AST
assert len(var["children"]) <= 1
self._initialized = True
self._initializedNotParsed = init
elif len(var["children"]) in [0, 1]:
self._initialized = False
self._initializedNotParsed = []
else:
assert len(var["children"]) == 2
self._initialized = True
self._initializedNotParsed = var["children"][1]
|
https://github.com/crytic/slither/issues/151
|
ERROR:root:Error in test.sol
ERROR:root:Traceback (most recent call last):
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 201, in _analyze_contracts
self._convert_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/slitherSolc.py", line 327, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/contract.py", line 374, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/solc_parsing/declarations/function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 69, in add_ssa_ir
add_phi_origins(function.entry_point, init_definition, dict())
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 363, in add_phi_origins
add_phi_origins(succ, local_variables_definition, state_variables_definition)
[Previous line repeated 2 more times]
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/slithir/utils/ssa.py", line 356, in add_phi_origins
phi_node.add_phi_origin_local_variable(variable, n)
File "/Users/matt/anaconda3/lib/python3.7/site-packages/slither_analyzer-0.5.0-py3.7.egg/slither/core/cfg/node.py", line 215, in add_phi_origin_local_variable
assert v == variable
AssertionError
|
AssertionError
|
def generate_ssa_irs(
node,
local_variables_instances,
all_local_variables_instances,
state_variables_instances,
all_state_variables_instances,
init_local_variables_instances,
visited,
):
if node in visited:
return
if node.type in [NodeType.ENDIF, NodeType.ENDLOOP] and any(
not father in visited for father in node.fathers
):
return
# visited is shared
visited.append(node)
for ir in node.irs_ssa:
assert isinstance(ir, Phi)
update_lvalue(
ir,
node,
local_variables_instances,
all_local_variables_instances,
state_variables_instances,
all_state_variables_instances,
)
# these variables are lived only during the liveness of the block
# They dont need phi function
temporary_variables_instances = dict()
reference_variables_instances = dict()
for ir in node.irs:
new_ir = copy_ir(
ir,
local_variables_instances,
state_variables_instances,
temporary_variables_instances,
reference_variables_instances,
all_local_variables_instances,
)
update_lvalue(
new_ir,
node,
local_variables_instances,
all_local_variables_instances,
state_variables_instances,
all_state_variables_instances,
)
if new_ir:
node.add_ssa_ir(new_ir)
if isinstance(
ir, (InternalCall, HighLevelCall, InternalDynamicCall, LowLevelCall)
):
if isinstance(ir, LibraryCall):
continue
for variable in all_state_variables_instances.values():
if not is_used_later(node, variable):
continue
new_var = StateIRVariable(variable)
new_var.index = (
all_state_variables_instances[variable.canonical_name].index + 1
)
all_state_variables_instances[variable.canonical_name] = new_var
state_variables_instances[variable.canonical_name] = new_var
phi_ir = PhiCallback(new_var, {node}, new_ir, variable)
# rvalues are fixed in solc_parsing.declaration.function
node.add_ssa_ir(phi_ir)
if isinstance(new_ir, (Assignment, Binary)):
if isinstance(new_ir.lvalue, LocalIRVariable):
if new_ir.lvalue.is_storage:
print(new_ir)
print(new_ir.lvalue.location)
if isinstance(new_ir.rvalue, ReferenceVariable):
refers_to = new_ir.rvalue.points_to_origin
new_ir.lvalue.add_refers_to(refers_to)
else:
new_ir.lvalue.add_refers_to(new_ir.rvalue)
for succ in node.dominator_successors:
generate_ssa_irs(
succ,
dict(local_variables_instances),
all_local_variables_instances,
dict(state_variables_instances),
all_state_variables_instances,
init_local_variables_instances,
visited,
)
for dominated in node.dominance_frontier:
generate_ssa_irs(
dominated,
dict(local_variables_instances),
all_local_variables_instances,
dict(state_variables_instances),
all_state_variables_instances,
init_local_variables_instances,
visited,
)
|
def generate_ssa_irs(
node,
local_variables_instances,
all_local_variables_instances,
state_variables_instances,
all_state_variables_instances,
init_local_variables_instances,
visited,
):
if node in visited:
return
if node.type in [NodeType.ENDIF, NodeType.ENDLOOP] and any(
not father in visited for father in node.fathers
):
return
# visited is shared
visited.append(node)
for ir in node.irs_ssa:
assert isinstance(ir, Phi)
update_lvalue(
ir,
node,
local_variables_instances,
all_local_variables_instances,
state_variables_instances,
all_state_variables_instances,
)
# these variables are lived only during the liveness of the block
# They dont need phi function
temporary_variables_instances = dict()
reference_variables_instances = dict()
for ir in node.irs:
new_ir = copy_ir(
ir,
local_variables_instances,
state_variables_instances,
temporary_variables_instances,
reference_variables_instances,
all_local_variables_instances,
)
update_lvalue(
new_ir,
node,
local_variables_instances,
all_local_variables_instances,
state_variables_instances,
all_state_variables_instances,
)
if new_ir:
node.add_ssa_ir(new_ir)
if isinstance(
ir, (InternalCall, HighLevelCall, InternalDynamicCall, LowLevelCall)
):
if isinstance(ir, LibraryCall):
continue
for variable in all_state_variables_instances.values():
if not is_used_later(node, variable):
continue
new_var = StateIRVariable(variable)
new_var.index = (
all_state_variables_instances[variable.canonical_name].index + 1
)
all_state_variables_instances[variable.canonical_name] = new_var
state_variables_instances[variable.canonical_name] = new_var
phi_ir = PhiCallback(new_var, {node}, new_ir, variable)
# rvalues are fixed in solc_parsing.declaration.function
node.add_ssa_ir(phi_ir)
if isinstance(new_ir, (Assignment, Binary)):
if isinstance(new_ir.lvalue, LocalIRVariable):
if new_ir.lvalue.is_storage:
if isinstance(new_ir.rvalue, ReferenceVariable):
refers_to = new_ir.rvalue.points_to_origin
new_ir.lvalue.add_refers_to(refers_to)
else:
new_ir.lvalue.add_refers_to(new_ir.rvalue)
for succ in node.dominator_successors:
generate_ssa_irs(
succ,
dict(local_variables_instances),
all_local_variables_instances,
dict(state_variables_instances),
all_state_variables_instances,
init_local_variables_instances,
visited,
)
for dominated in node.dominance_frontier:
generate_ssa_irs(
dominated,
dict(local_variables_instances),
all_local_variables_instances,
dict(state_variables_instances),
all_state_variables_instances,
init_local_variables_instances,
visited,
)
|
https://github.com/crytic/slither/issues/143
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 341, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 386, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "c:\users\vyper\documents\github\slither\slither\slithir\utils\ssa.py", line 123, in add_ssa_ir
[])
File "c:\users\vyper\documents\github\slither\slither\slithir\utils\ssa.py", line 295, in generate_ssa_irs
visited)
File "c:\users\vyper\documents\github\slither\slither\slithir\utils\ssa.py", line 285, in generate_ssa_irs
new_ir.lvalue.add_refers_to(new_ir.rvalue)
File "c:\users\vyper\documents\github\slither\slither\slithir\variables\local_variable.py", line 56, in add_refers_to
self._refers_to.add(variable)
TypeError: unhashable type: 'Constant'
|
TypeError
|
def __init__(self, local_variable):
assert isinstance(local_variable, LocalVariable)
super(LocalIRVariable, self).__init__()
# initiate ChildContract
self.set_function(local_variable.function)
# initiate Variable
self._name = local_variable.name
self._initial_expression = local_variable.expression
self._type = local_variable.type
self._initialized = local_variable.initialized
self._visibility = local_variable.visibility
self._is_constant = local_variable.is_constant
# initiate LocalVariable
self._location = local_variable.location
self._is_storage = local_variable.is_storage
self._index = 0
# Additional field
# points to state variables
self._refers_to = set()
# keep un-ssa version
if isinstance(local_variable, LocalIRVariable):
self._non_ssa_version = local_variable.non_ssa_version
else:
self._non_ssa_version = local_variable
self._non_ssa_version = local_variable
|
def __init__(self, local_variable):
assert isinstance(local_variable, LocalVariable)
super(LocalIRVariable, self).__init__()
# initiate ChildContract
self.set_function(local_variable.function)
# initiate Variable
self._name = local_variable.name
self._initial_expression = local_variable.expression
self._type = local_variable.type
self._initialized = local_variable.initialized
self._visibility = local_variable.visibility
self._is_constant = local_variable.is_constant
# initiate LocalVariable
self._location = self.location
self._is_storage = self.is_storage
self._index = 0
# Additional field
# points to state variables
self._refers_to = set()
# keep un-ssa version
if isinstance(local_variable, LocalIRVariable):
self._non_ssa_version = local_variable.non_ssa_version
else:
self._non_ssa_version = local_variable
self._non_ssa_version = local_variable
|
https://github.com/crytic/slither/issues/143
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 341, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 386, in convert_expression_to_slithir
func.generate_slithir_ssa(all_ssa_state_variables_instances)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 935, in generate_slithir_ssa
add_ssa_ir(self, all_ssa_state_variables_instances)
File "c:\users\vyper\documents\github\slither\slither\slithir\utils\ssa.py", line 123, in add_ssa_ir
[])
File "c:\users\vyper\documents\github\slither\slither\slithir\utils\ssa.py", line 295, in generate_ssa_irs
visited)
File "c:\users\vyper\documents\github\slither\slither\slithir\utils\ssa.py", line 285, in generate_ssa_irs
new_ir.lvalue.add_refers_to(new_ir.rvalue)
File "c:\users\vyper\documents\github\slither\slither\slithir\variables\local_variable.py", line 56, in add_refers_to
self._refers_to.add(variable)
TypeError: unhashable type: 'Constant'
|
TypeError
|
def propage_type_and_convert_call(result, node):
calls_value = {}
calls_gas = {}
call_data = []
idx = 0
# use of while len() as result can be modified during the iteration
while idx < len(result):
ins = result[idx]
if isinstance(ins, TmpCall):
new_ins = extract_tmp_call(ins)
if new_ins:
new_ins.set_node(ins.node)
ins = new_ins
result[idx] = ins
if isinstance(ins, Argument):
if ins.get_type() in [ArgumentType.GAS]:
assert not ins.call_id in calls_gas
calls_gas[ins.call_id] = ins.argument
elif ins.get_type() in [ArgumentType.VALUE]:
assert not ins.call_id in calls_value
calls_value[ins.call_id] = ins.argument
else:
assert ins.get_type() == ArgumentType.CALL
call_data.append(ins.argument)
if isinstance(ins, (HighLevelCall, NewContract, InternalDynamicCall)):
if ins.call_id in calls_value:
ins.call_value = calls_value[ins.call_id]
if ins.call_id in calls_gas:
ins.call_gas = calls_gas[ins.call_id]
if isinstance(ins, (Call, NewContract, NewStructure)):
ins.arguments = call_data
call_data = []
if is_temporary(ins):
del result[idx]
continue
new_ins = propagate_types(ins, node)
if new_ins:
if isinstance(new_ins, (list,)):
if len(new_ins) == 2:
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx + 1, new_ins[1])
idx = idx + 1
else:
assert len(new_ins) == 3
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
new_ins[2].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx + 1, new_ins[1])
result.insert(idx + 2, new_ins[2])
idx = idx + 2
else:
new_ins.set_node(ins.node)
result[idx] = new_ins
idx = idx + 1
return result
|
def propage_type_and_convert_call(result, node):
calls_value = {}
calls_gas = {}
call_data = []
idx = 0
# use of while len() as result can be modified during the iteration
while idx < len(result):
ins = result[idx]
if isinstance(ins, TmpCall):
new_ins = extract_tmp_call(ins)
if new_ins:
new_ins.set_node(ins.node)
ins = new_ins
result[idx] = ins
if isinstance(ins, Argument):
if ins.get_type() in [ArgumentType.GAS]:
assert not ins.call_id in calls_gas
calls_gas[ins.call_id] = ins.argument
elif ins.get_type() in [ArgumentType.VALUE]:
assert not ins.call_id in calls_value
calls_value[ins.call_id] = ins.argument
else:
assert ins.get_type() == ArgumentType.CALL
call_data.append(ins.argument)
if isinstance(ins, (HighLevelCall, NewContract)):
if ins.call_id in calls_value:
ins.call_value = calls_value[ins.call_id]
if ins.call_id in calls_gas:
ins.call_gas = calls_gas[ins.call_id]
if isinstance(ins, (Call, NewContract, NewStructure)):
ins.arguments = call_data
call_data = []
if is_temporary(ins):
del result[idx]
continue
new_ins = propagate_types(ins, node)
if new_ins:
if isinstance(new_ins, (list,)):
if len(new_ins) == 2:
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx + 1, new_ins[1])
idx = idx + 1
else:
assert len(new_ins) == 3
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
new_ins[2].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx + 1, new_ins[1])
result.insert(idx + 2, new_ins[2])
idx = idx + 2
else:
new_ins.set_node(ins.node)
result[idx] = new_ins
idx = idx + 1
return result
|
https://github.com/crytic/slither/issues/135
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 210, in _analyze_contracts
self._convert_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 336, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 508, in slithir_generation
self._find_read_write_call()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 551, in _find_read_write_call
self._high_level_calls.append((ir.destination.type.type, ir.function))
AttributeError: 'FunctionType' object has no attribute 'type'
|
AttributeError
|
def extract_tmp_call(ins):
assert isinstance(ins, TmpCall)
if isinstance(ins.called, Variable) and isinstance(ins.called.type, FunctionType):
call = InternalDynamicCall(ins.lvalue, ins.called, ins.called.type)
call.call_id = ins.call_id
return call
if isinstance(ins.ori, Member):
if isinstance(ins.ori.variable_left, Contract):
st = ins.ori.variable_left.get_structure_from_name(ins.ori.variable_right)
if st:
op = NewStructure(st, ins.lvalue)
op.call_id = ins.call_id
return op
libcall = LibraryCall(
ins.ori.variable_left,
ins.ori.variable_right,
ins.nbr_arguments,
ins.lvalue,
ins.type_call,
)
libcall.call_id = ins.call_id
return libcall
msgcall = HighLevelCall(
ins.ori.variable_left,
ins.ori.variable_right,
ins.nbr_arguments,
ins.lvalue,
ins.type_call,
)
msgcall.call_id = ins.call_id
return msgcall
if isinstance(ins.ori, TmpCall):
r = extract_tmp_call(ins.ori)
return r
if isinstance(ins.called, SolidityVariableComposed):
if str(ins.called) == "block.blockhash":
ins.called = SolidityFunction("blockhash(uint256)")
elif str(ins.called) == "this.balance":
return SolidityCall(
SolidityFunction("this.balance()"),
ins.nbr_arguments,
ins.lvalue,
ins.type_call,
)
if isinstance(ins.called, SolidityFunction):
return SolidityCall(ins.called, ins.nbr_arguments, ins.lvalue, ins.type_call)
if isinstance(ins.ori, TmpNewElementaryType):
return NewElementaryType(ins.ori.type, ins.lvalue)
if isinstance(ins.ori, TmpNewContract):
op = NewContract(Constant(ins.ori.contract_name), ins.lvalue)
op.call_id = ins.call_id
return op
if isinstance(ins.ori, TmpNewArray):
return NewArray(ins.ori.depth, ins.ori.array_type, ins.lvalue)
if isinstance(ins.called, Structure):
op = NewStructure(ins.called, ins.lvalue)
op.call_id = ins.call_id
return op
if isinstance(ins.called, Event):
return EventCall(ins.called.name)
raise Exception("Not extracted {} {}".format(type(ins.called), ins))
|
def extract_tmp_call(ins):
assert isinstance(ins, TmpCall)
if isinstance(ins.ori, Member):
if isinstance(ins.ori.variable_left, Contract):
st = ins.ori.variable_left.get_structure_from_name(ins.ori.variable_right)
if st:
op = NewStructure(st, ins.lvalue)
op.call_id = ins.call_id
return op
libcall = LibraryCall(
ins.ori.variable_left,
ins.ori.variable_right,
ins.nbr_arguments,
ins.lvalue,
ins.type_call,
)
libcall.call_id = ins.call_id
return libcall
msgcall = HighLevelCall(
ins.ori.variable_left,
ins.ori.variable_right,
ins.nbr_arguments,
ins.lvalue,
ins.type_call,
)
msgcall.call_id = ins.call_id
return msgcall
if isinstance(ins.ori, TmpCall):
r = extract_tmp_call(ins.ori)
return r
if isinstance(ins.called, SolidityVariableComposed):
if str(ins.called) == "block.blockhash":
ins.called = SolidityFunction("blockhash(uint256)")
elif str(ins.called) == "this.balance":
return SolidityCall(
SolidityFunction("this.balance()"),
ins.nbr_arguments,
ins.lvalue,
ins.type_call,
)
if isinstance(ins.called, SolidityFunction):
return SolidityCall(ins.called, ins.nbr_arguments, ins.lvalue, ins.type_call)
if isinstance(ins.ori, TmpNewElementaryType):
return NewElementaryType(ins.ori.type, ins.lvalue)
if isinstance(ins.ori, TmpNewContract):
op = NewContract(Constant(ins.ori.contract_name), ins.lvalue)
op.call_id = ins.call_id
return op
if isinstance(ins.ori, TmpNewArray):
return NewArray(ins.ori.depth, ins.ori.array_type, ins.lvalue)
if isinstance(ins.called, Structure):
op = NewStructure(ins.called, ins.lvalue)
op.call_id = ins.call_id
return op
if isinstance(ins.called, Event):
return EventCall(ins.called.name)
if isinstance(ins.called, Variable) and isinstance(ins.called.type, FunctionType):
return InternalDynamicCall(ins.lvalue, ins.called, ins.called.type)
raise Exception("Not extracted {} {}".format(type(ins.called), ins))
|
https://github.com/crytic/slither/issues/135
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 210, in _analyze_contracts
self._convert_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 336, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 508, in slithir_generation
self._find_read_write_call()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 551, in _find_read_write_call
self._high_level_calls.append((ir.destination.type.type, ir.function))
AttributeError: 'FunctionType' object has no attribute 'type'
|
AttributeError
|
def __init__(self, lvalue, function, function_type):
assert isinstance(function_type, FunctionType)
assert isinstance(function, Variable)
assert is_valid_lvalue(lvalue) or lvalue is None
super(InternalDynamicCall, self).__init__()
self._function = function
self._function_type = function_type
self._lvalue = lvalue
self._callid = None # only used if gas/value != 0
self._call_value = None
self._call_gas = None
|
def __init__(self, lvalue, function, function_type):
assert isinstance(function_type, FunctionType)
assert isinstance(function, Variable)
assert is_valid_lvalue(lvalue) or lvalue is None
super(InternalDynamicCall, self).__init__()
self._function = function
self._function_type = function_type
self._lvalue = lvalue
|
https://github.com/crytic/slither/issues/135
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 210, in _analyze_contracts
self._convert_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 336, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 508, in slithir_generation
self._find_read_write_call()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 551, in _find_read_write_call
self._high_level_calls.append((ir.destination.type.type, ir.function))
AttributeError: 'FunctionType' object has no attribute 'type'
|
AttributeError
|
def __str__(self):
value = ""
gas = ""
args = [str(a) for a in self.arguments]
if self.call_value:
value = "value:{}".format(self.call_value)
if self.call_gas:
gas = "gas:{}".format(self.call_gas)
if not self.lvalue:
lvalue = ""
elif isinstance(self.lvalue.type, (list,)):
lvalue = "{}({}) = ".format(
self.lvalue, ",".join(str(x) for x in self.lvalue.type)
)
else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type)
txt = "{}INTERNAL_DYNAMIC_CALL {}({}) {} {}"
return txt.format(lvalue, self.function.name, ",".join(args), value, gas)
|
def __str__(self):
args = [str(a) for a in self.arguments]
if not self.lvalue:
lvalue = ""
elif isinstance(self.lvalue.type, (list,)):
lvalue = "{}({}) = ".format(
self.lvalue, ",".join(str(x) for x in self.lvalue.type)
)
else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type)
txt = "{}INTERNAL_DYNAMIC_CALL {}({})"
return txt.format(lvalue, self.function.name, ",".join(args))
|
https://github.com/crytic/slither/issues/135
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 210, in _analyze_contracts
self._convert_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 336, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 508, in slithir_generation
self._find_read_write_call()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 551, in _find_read_write_call
self._high_level_calls.append((ir.destination.type.type, ir.function))
AttributeError: 'FunctionType' object has no attribute 'type'
|
AttributeError
|
def __init__(self, t, length):
assert isinstance(t, Type)
if length:
if isinstance(length, int):
length = Literal(length)
assert isinstance(length, Expression)
super(ArrayType, self).__init__()
self._type = t
self._length = length
|
def __init__(self, t, length):
assert isinstance(t, Type)
if length:
assert isinstance(length, Expression)
super(ArrayType, self).__init__()
self._type = t
self._length = length
|
https://github.com/crytic/slither/issues/139
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 214, in _analyze_contracts
self._convert_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 341, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 506, in slithir_generation
self._irs = convert_expression(expression, self)
File "c:\users\vyper\documents\github\slither\slither\slithir\convert.py", line 734, in convert_expression
visitor = ExpressionToSlithIR(expression, node)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 70, in __init__
self._visit_expression(self.expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 92, in _visit_expression
self._post_visit(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 275, in _post_visit
self._post_index_access(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 163, in _post_index_access
operation = Index(val, left, right, expression.type)
File "c:\users\vyper\documents\github\slither\slither\slithir\operations\index.py", line 13, in __init__
assert is_valid_lvalue(left_variable) or left_variable == SolidityVariableComposed('msg.data')
AssertionError
|
AssertionError
|
def _post_index_access(self, expression):
left = get(expression.expression_left)
right = get(expression.expression_right)
val = ReferenceVariable(self._node)
# access to anonymous array
# such as [0,1][x]
if isinstance(left, list):
init_array_val = TemporaryVariable(self._node)
init_array_right = left
left = init_array_val
operation = InitArray(init_array_right, init_array_val)
self._result.append(operation)
operation = Index(val, left, right, expression.type)
self._result.append(operation)
set_val(expression, val)
|
def _post_index_access(self, expression):
left = get(expression.expression_left)
right = get(expression.expression_right)
val = ReferenceVariable(self._node)
operation = Index(val, left, right, expression.type)
self._result.append(operation)
set_val(expression, val)
|
https://github.com/crytic/slither/issues/139
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 214, in _analyze_contracts
self._convert_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 341, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 506, in slithir_generation
self._irs = convert_expression(expression, self)
File "c:\users\vyper\documents\github\slither\slither\slithir\convert.py", line 734, in convert_expression
visitor = ExpressionToSlithIR(expression, node)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 70, in __init__
self._visit_expression(self.expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 92, in _visit_expression
self._post_visit(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 275, in _post_visit
self._post_index_access(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 163, in _post_index_access
operation = Index(val, left, right, expression.type)
File "c:\users\vyper\documents\github\slither\slither\slithir\operations\index.py", line 13, in __init__
assert is_valid_lvalue(left_variable) or left_variable == SolidityVariableComposed('msg.data')
AssertionError
|
AssertionError
|
def analyze_content(self):
if self._content_was_analyzed:
return
self._content_was_analyzed = True
if self.is_compact_ast:
body = self._functionNotParsed["body"]
if body and body[self.get_key()] == "Block":
self._is_implemented = True
self._parse_cfg(body)
for modifier in self._functionNotParsed["modifiers"]:
self._parse_modifier(modifier)
else:
children = self._functionNotParsed[self.get_children("children")]
self._is_implemented = False
for child in children[2:]:
if child[self.get_key()] == "Block":
self._is_implemented = True
self._parse_cfg(child)
# Parse modifier after parsing all the block
# In the case a local variable is used in the modifier
for child in children[2:]:
if child[self.get_key()] == "ModifierInvocation":
self._parse_modifier(child)
for local_vars in self.variables:
local_vars.analyze(self)
for node in self.nodes:
node.analyze_expressions(self)
self._filter_ternary()
self._remove_alone_endif()
|
def analyze_content(self):
if self._content_was_analyzed:
return
self._content_was_analyzed = True
if self.is_compact_ast:
body = self._functionNotParsed["body"]
if body and body[self.get_key()] == "Block":
self._is_implemented = True
self._parse_cfg(body)
for modifier in self._functionNotParsed["modifiers"]:
self._parse_modifier(modifier)
else:
children = self._functionNotParsed[self.get_children("children")]
self._is_implemented = False
for child in children[2:]:
if child[self.get_key()] == "Block":
self._is_implemented = True
self._parse_cfg(child)
# Parse modifier after parsing all the block
# In the case a local variable is used in the modifier
for child in children[2:]:
if child[self.get_key()] == "ModifierInvocation":
self._parse_modifier(child)
for local_vars in self.variables:
local_vars.analyze(self)
for node in self.nodes:
node.analyze_expressions(self)
ternary_found = True
while ternary_found:
ternary_found = False
for node in self.nodes:
has_cond = HasConditional(node.expression)
if has_cond.result():
st = SplitTernaryExpression(node.expression)
condition = st.condition
assert condition
true_expr = st.true_expression
false_expr = st.false_expression
self.split_ternary_node(node, condition, true_expr, false_expr)
ternary_found = True
break
self._remove_alone_endif()
|
https://github.com/crytic/slither/issues/140
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 341, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 506, in slithir_generation
self._irs = convert_expression(expression, self)
File "c:\users\vyper\documents\github\slither\slither\slithir\convert.py", line 734, in convert_expression
visitor = ExpressionToSlithIR(expression, node)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 70, in __init__
self._visit_expression(self.expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 41, in _visit_expression
self._visit_assignement_operation(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 98, in _visit_assignement_operation
self._visit_expression(expression.expression_right)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 92, in _visit_expression
self._post_visit(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 266, in _post_visit
self._post_conditional_expression(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 151, in _post_conditional_expression
raise Exception('Ternary operator are not convertible to SlithIR {}'.format(expression))
Exception: Ternary operator are not convertible to SlithIR if a != address(0) then a else msg.sender
|
Exception
|
def analyze_content(self):
if self._content_was_analyzed:
return
self._content_was_analyzed = True
if self.is_compact_ast:
body = self._functionNotParsed["body"]
if body and body[self.get_key()] == "Block":
self._is_implemented = True
self._parse_cfg(body)
else:
children = self._functionNotParsed["children"]
self._isImplemented = False
if len(children) > 1:
assert len(children) == 2
block = children[1]
assert block["name"] == "Block"
self._is_implemented = True
self._parse_cfg(block)
for local_vars in self.variables:
local_vars.analyze(self)
for node in self.nodes:
node.analyze_expressions(self)
self._filter_ternary()
self._remove_alone_endif()
self._analyze_read_write()
self._analyze_calls()
|
def analyze_content(self):
if self._content_was_analyzed:
return
self._content_was_analyzed = True
if self.is_compact_ast:
body = self._functionNotParsed["body"]
if body and body[self.get_key()] == "Block":
self._is_implemented = True
self._parse_cfg(body)
else:
children = self._functionNotParsed["children"]
self._isImplemented = False
if len(children) > 1:
assert len(children) == 2
block = children[1]
assert block["name"] == "Block"
self._is_implemented = True
self._parse_cfg(block)
for local_vars in self.variables:
local_vars.analyze(self)
for node in self.nodes:
node.analyze_expressions(self)
self._analyze_read_write()
self._analyze_calls()
|
https://github.com/crytic/slither/issues/140
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 341, in _convert_to_slithir
contract.convert_expression_to_slithir()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 367, in convert_expression_to_slithir
func.generate_slithir_and_analyze()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 927, in generate_slithir_and_analyze
node.slithir_generation()
File "c:\users\vyper\documents\github\slither\slither\core\cfg\node.py", line 506, in slithir_generation
self._irs = convert_expression(expression, self)
File "c:\users\vyper\documents\github\slither\slither\slithir\convert.py", line 734, in convert_expression
visitor = ExpressionToSlithIR(expression, node)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 70, in __init__
self._visit_expression(self.expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 41, in _visit_expression
self._visit_assignement_operation(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 98, in _visit_assignement_operation
self._visit_expression(expression.expression_right)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 92, in _visit_expression
self._post_visit(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\expression\expression.py", line 266, in _post_visit
self._post_conditional_expression(expression)
File "c:\users\vyper\documents\github\slither\slither\visitors\slithir\expression_to_slithir.py", line 151, in _post_conditional_expression
raise Exception('Ternary operator are not convertible to SlithIR {}'.format(expression))
Exception: Ternary operator are not convertible to SlithIR if a != address(0) then a else msg.sender
|
Exception
|
def _parse_dowhile(self, doWhilestatement, node):
node_startDoWhile = self._new_node(NodeType.STARTLOOP, doWhilestatement["src"])
node_condition = self._new_node(NodeType.IFLOOP, doWhilestatement["src"])
if self.is_compact_ast:
node_condition.add_unparsed_expression(doWhilestatement["condition"])
statement = self._parse_statement(doWhilestatement["body"], node_condition)
else:
children = doWhilestatement[self.get_children("children")]
# same order in the AST as while
expression = children[0]
node_condition.add_unparsed_expression(expression)
statement = self._parse_statement(children[1], node_condition)
node_endDoWhile = self._new_node(NodeType.ENDLOOP, doWhilestatement["src"])
link_nodes(node, node_startDoWhile)
# empty block, loop from the start to the condition
if not node_condition.sons:
link_nodes(node_startDoWhile, node_condition)
else:
link_nodes(node_startDoWhile, node_condition.sons[0])
link_nodes(statement, node_condition)
link_nodes(node_condition, node_endDoWhile)
return node_endDoWhile
|
def _parse_dowhile(self, doWhilestatement, node):
node_startDoWhile = self._new_node(NodeType.STARTLOOP, doWhilestatement["src"])
node_condition = self._new_node(NodeType.IFLOOP, doWhilestatement["src"])
if self.is_compact_ast:
node_condition.add_unparsed_expression(doWhilestatement["condition"])
statement = self._parse_statement(doWhilestatement["body"], node_condition)
else:
children = doWhilestatement[self.get_children("children")]
# same order in the AST as while
expression = children[0]
node_condition.add_unparsed_expression(expression)
statement = self._parse_statement(children[1], node_condition)
node_endDoWhile = self._new_node(NodeType.ENDLOOP, doWhilestatement["src"])
link_nodes(node, node_startDoWhile)
link_nodes(node_startDoWhile, node_condition.sons[0])
link_nodes(statement, node_condition)
link_nodes(node_condition, node_endDoWhile)
return node_endDoWhile
|
https://github.com/crytic/slither/issues/133
|
ERROR:root:Traceback (most recent call last):
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 250, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "c:\users\vyper\documents\github\slither\slither\__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "c:\users\vyper\documents\github\slither\slither\slither.py", line 41, in __init__
self._analyze_contracts()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 206, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 290, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\slitherSolc.py", line 330, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\contract.py", line 360, in analyze_content_functions
function.analyze_content()
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 818, in analyze_content
self._parse_cfg(child)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 614, in _parse_cfg
self._parse_block(cfg, node)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 595, in _parse_block
node = self._parse_statement(statement, node)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 525, in _parse_statement
node = self._parse_dowhile(statement, node)
File "c:\users\vyper\documents\github\slither\slither\solc_parsing\declarations\function.py", line 316, in _parse_dowhile
link_nodes(node_startDoWhile, node_condition.sons[0])
IndexError: list index out of range
|
IndexError
|
def copy_expression(self, expression, true_expression, false_expression):
if self.condition:
return
if isinstance(expression, ConditionalExpression):
raise Exception("Nested ternary operator not handled")
if isinstance(
expression, (Literal, Identifier, IndexAccess, NewArray, NewContract)
):
return None
# case of lib
# (.. ? .. : ..).add
if isinstance(expression, MemberAccess):
next_expr = expression.expression
if self.apply_copy(next_expr, true_expression, false_expression, f_expression):
self.copy_expression(
next_expr, true_expression.expression, false_expression.expression
)
elif isinstance(
expression, (AssignmentOperation, BinaryOperation, TupleExpression)
):
true_expression._expressions = []
false_expression._expressions = []
for next_expr in expression.expressions:
if self.apply_copy(
next_expr, true_expression, false_expression, f_expressions
):
# always on last arguments added
self.copy_expression(
next_expr,
true_expression.expressions[-1],
false_expression.expressions[-1],
)
elif isinstance(expression, CallExpression):
next_expr = expression.called
# case of lib
# (.. ? .. : ..).add
if self.apply_copy(next_expr, true_expression, false_expression, f_called):
self.copy_expression(
next_expr, true_expression.called, false_expression.called
)
true_expression._arguments = []
false_expression._arguments = []
for next_expr in expression.arguments:
if self.apply_copy(next_expr, true_expression, false_expression, f_call):
# always on last arguments added
self.copy_expression(
next_expr,
true_expression.arguments[-1],
false_expression.arguments[-1],
)
elif isinstance(expression, TypeConversion):
next_expr = expression.expression
if self.apply_copy(next_expr, true_expression, false_expression, f_expression):
self.copy_expression(
expression.expression,
true_expression.expression,
false_expression.expression,
)
else:
raise Exception(
"Ternary operation not handled {}({})".format(expression, type(expression))
)
|
def copy_expression(self, expression, true_expression, false_expression):
if self.condition:
return
if isinstance(expression, ConditionalExpression):
raise Exception("Nested ternary operator not handled")
if isinstance(expression, (Literal, Identifier, IndexAccess, NewArray)):
return None
# case of lib
# (.. ? .. : ..).add
if isinstance(expression, MemberAccess):
next_expr = expression.expression
if self.apply_copy(next_expr, true_expression, false_expression, f_expression):
self.copy_expression(
next_expr, true_expression.expression, false_expression.expression
)
elif isinstance(
expression, (AssignmentOperation, BinaryOperation, TupleExpression)
):
true_expression._expressions = []
false_expression._expressions = []
for next_expr in expression.expressions:
if self.apply_copy(
next_expr, true_expression, false_expression, f_expressions
):
# always on last arguments added
self.copy_expression(
next_expr,
true_expression.expressions[-1],
false_expression.expressions[-1],
)
elif isinstance(expression, CallExpression):
next_expr = expression.called
# case of lib
# (.. ? .. : ..).add
if self.apply_copy(next_expr, true_expression, false_expression, f_called):
self.copy_expression(
next_expr, true_expression.called, false_expression.called
)
true_expression._arguments = []
false_expression._arguments = []
for next_expr in expression.arguments:
if self.apply_copy(next_expr, true_expression, false_expression, f_call):
# always on last arguments added
self.copy_expression(
next_expr,
true_expression.arguments[-1],
false_expression.arguments[-1],
)
elif isinstance(expression, TypeConversion):
next_expr = expression.expression
if self.apply_copy(next_expr, true_expression, false_expression, f_expression):
self.copy_expression(
expression.expression,
true_expression.expression,
false_expression.expression,
)
else:
raise Exception(
"Ternary operation not handled {}({})".format(expression, type(expression))
)
|
https://github.com/crytic/slither/issues/98
|
$ slither contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol
INFO:Slither:Compilation warnings/errors on contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:27:2: Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(...) { ... }" instead.
function DeDeMasterContract(address _dedeNetworkAddress){
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:61:3: Warning: Use of the "var" keyword is deprecated.
var _dede = DeDeContract(dede);
^-------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:72:3: Warning: Use of the "var" keyword is deprecated.
var _dede = DeDeContract(dede);
^-------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:109:2: Warning: Defining constructors as functions with the same name as the contract is deprecated. Use "constructor(...) { ... }" instead.
function DeDeContract(address _dip, address _scs, address _issuer, uint256 _targetAmount, uint256 _bulletAmount, address _targetAddress, address _bulletAddress, uint256 _validationTime) payable {
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:58:3: Warning: Invoking events without "emit" prefix is deprecated.
Issue(msg.sender, dedeNetworkAddress, _issuer, dede);
^--------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:69:3: Warning: Invoking events without "emit" prefix is deprecated.
Activate(_dede.dip(), _dede.scs(), _dede.issuer(), dede);
^------------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:80:3: Warning: Invoking events without "emit" prefix is deprecated.
Nullify(_dede.dip(), _dede.scs(), _dede.issuer(), dede);
^-----------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:137:4: Warning: "suicide" has been deprecated in favour of "selfdestruct"
suicide(dip); // force send bullet ether to dip
^----------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:141:4: Warning: "suicide" has been deprecated in favour of "selfdestruct"
suicide(scs); // force send target or leftover ether to scs
^----------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:152:3: Warning: "suicide" has been deprecated in favour of "selfdestruct"
suicide(dip);
^----------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:4:2: Warning: No visibility specified. Defaulting to "public".
function totalSupply() constant returns (uint supply);
^----------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:5:2: Warning: No visibility specified. Defaulting to "public".
function balanceOf(address _owner) constant returns (uint balance);
^-----------------------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:6:2: Warning: No visibility specified. Defaulting to "public".
function transfer(address _to, uint _value) returns (bool success);
^-----------------------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:7:2: Warning: No visibility specified. Defaulting to "public".
function transferFrom(address _from, address _to, uint _value) returns (bool success);
^------------------------------------------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:8:2: Warning: No visibility specified. Defaulting to "public".
function approve(address _spender, uint _value) returns (bool success);
^---------------------------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:9:2: Warning: No visibility specified. Defaulting to "public".
function allowance(address _owner, address _spender) constant returns (uint remaining);
^-------------------------------------------------------------------------------------^
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:27:2: Warning: No visibility specified. Defaulting to "public".
function DeDeMasterContract(address _dedeNetworkAddress){
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:32:2: Warning: No visibility specified. Defaulting to "public".
function changeDedeAddress(address newDedeAddress){
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:37:2: Warning: No visibility specified. Defaulting to "public".
function issue(uint256 _targetAmount, uint256 _bulletAmount, address _targetAddress, address _bulletAddress, uint256 _validationTime, address _issuer) payable {
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:60:2: Warning: No visibility specified. Defaulting to "public".
function activate(address dede) payable {
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:71:2: Warning: No visibility specified. Defaulting to "public".
function nullify(address dede){
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:109:2: Warning: No visibility specified. Defaulting to "public".
function DeDeContract(address _dip, address _scs, address _issuer, uint256 _targetAmount, uint256 _bulletAmount, address _targetAddress, address _bulletAddress, uint256 _validationTime) payable {
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:126:2: Warning: No visibility specified. Defaulting to "public".
function activate(address sender) payable {
^ (Relevant source part starts here and spans across multiple lines).
contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol:144:2: Warning: No visibility specified. Defaulting to "public".
function nullify(address sender) {
^ (Relevant source part starts here and spans across multiple lines).
ERROR:root:Error in contracts/0xc6C09Ae980b3d029DEB7419fA1B7859DCe7186D0_DeDeMasterContract.sol
ERROR:root:Traceback (most recent call last):
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/__main__.py", line 226, in main_impl
(results, number_contracts) = process(filename, args, detector_classes, printer_classes)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/__main__.py", line 35, in process
slither = Slither(filename, args.solc, args.disable_solc_warnings, args.solc_args, ast)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/slither.py", line 41, in __init__
self._analyze_contracts()
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/solc_parsing/slitherSolc.py", line 187, in _analyze_contracts
self._analyze_third_part(contracts_to_be_analyzed, libraries)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/solc_parsing/slitherSolc.py", line 269, in _analyze_third_part
self._analyze_variables_modifiers_functions(contract)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/solc_parsing/slitherSolc.py", line 309, in _analyze_variables_modifiers_functions
contract.analyze_content_functions()
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/solc_parsing/declarations/contract.py", line 347, in analyze_content_functions
function.analyze_content()
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/solc_parsing/declarations/function.py", line 825, in analyze_content
st = SplitTernaryExpression(node.expression)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/utils/expression_manipulations.py", line 48, in __init__
self.copy_expression(expression, self.true_expression, self.false_expression)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/utils/expression_manipulations.py", line 90, in copy_expression
false_expression.expressions[-1])
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/utils/expression_manipulations.py", line 100, in copy_expression
false_expression.called)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/utils/expression_manipulations.py", line 100, in copy_expression
false_expression.called)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/utils/expression_manipulations.py", line 79, in copy_expression
false_expression.expression)
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/utils/expression_manipulations.py", line 90, in copy_expression
false_expression.expressions[-1])
File "/home/gustavo/.local/lib/python3.6/site-packages/slither_analyzer-0.3.1-py3.6.egg/slither/utils/expression_manipulations.py", line 120, in copy_expression
raise Exception('Ternary operation not handled {}({})'.format(expression, type(expression)))
Exception: Ternary operation not handled new DeDeContract(<class 'slither.core.expressions.new_contract.NewContract'>)
|
Exception
|
def generate_c_type_stub(
module: ModuleType,
class_name: str,
obj: type,
output: List[str],
imports: List[str],
sigs: Optional[Dict[str, str]] = None,
class_sigs: Optional[Dict[str, str]] = None,
) -> None:
"""Generate stub for a single class using runtime introspection.
The result lines will be appended to 'output'. If necessary, any
required names will be added to 'imports'.
"""
# typeshed gives obj.__dict__ the not quite correct type Dict[str, Any]
# (it could be a mappingproxy!), which makes mypyc mad, so obfuscate it.
obj_dict = getattr(obj, "__dict__") # type: Mapping[str, Any] # noqa
items = sorted(obj_dict.items(), key=lambda x: method_name_sort_key(x[0]))
methods = [] # type: List[str]
types = [] # type: List[str]
static_properties = [] # type: List[str]
rw_properties = [] # type: List[str]
ro_properties = [] # type: List[str]
done = set() # type: Set[str]
for attr, value in items:
if is_c_method(value) or is_c_classmethod(value):
done.add(attr)
if not is_skipped_attribute(attr):
if attr == "__new__":
# TODO: We should support __new__.
if "__init__" in obj_dict:
# Avoid duplicate functions if both are present.
# But is there any case where .__new__() has a
# better signature than __init__() ?
continue
attr = "__init__"
if is_c_classmethod(value):
methods.append("@classmethod")
self_var = "cls"
else:
self_var = "self"
generate_c_function_stub(
module,
attr,
value,
methods,
imports=imports,
self_var=self_var,
sigs=sigs,
class_name=class_name,
class_sigs=class_sigs,
)
elif is_c_property(value):
done.add(attr)
generate_c_property_stub(
attr,
value,
static_properties,
rw_properties,
ro_properties,
is_c_property_readonly(value),
module=module,
imports=imports,
)
elif is_c_type(value):
generate_c_type_stub(
module,
attr,
value,
types,
imports=imports,
sigs=sigs,
class_sigs=class_sigs,
)
done.add(attr)
for attr, value in items:
if is_skipped_attribute(attr):
continue
if attr not in done:
static_properties.append(
"%s: ClassVar[%s] = ..."
% (
attr,
strip_or_import(get_type_fullname(type(value)), module, imports),
)
)
all_bases = type.mro(obj)
if all_bases[-1] is object:
# TODO: Is this always object?
del all_bases[-1]
# remove pybind11_object. All classes generated by pybind11 have pybind11_object in their MRO,
# which only overrides a few functions in object type
if all_bases and all_bases[-1].__name__ == "pybind11_object":
del all_bases[-1]
# remove the class itself
all_bases = all_bases[1:]
# Remove base classes of other bases as redundant.
bases = [] # type: List[type]
for base in all_bases:
if not any(issubclass(b, base) for b in bases):
bases.append(base)
if bases:
bases_str = "(%s)" % ", ".join(
strip_or_import(get_type_fullname(base), module, imports) for base in bases
)
else:
bases_str = ""
if types or static_properties or rw_properties or methods or ro_properties:
output.append("class %s%s:" % (class_name, bases_str))
for line in types:
if (
output
and output[-1]
and not output[-1].startswith("class")
and line.startswith("class")
):
output.append("")
output.append(" " + line)
for line in static_properties:
output.append(" %s" % line)
for line in rw_properties:
output.append(" %s" % line)
for line in methods:
output.append(" %s" % line)
for line in ro_properties:
output.append(" %s" % line)
else:
output.append("class %s%s: ..." % (class_name, bases_str))
|
def generate_c_type_stub(
module: ModuleType,
class_name: str,
obj: type,
output: List[str],
imports: List[str],
sigs: Optional[Dict[str, str]] = None,
class_sigs: Optional[Dict[str, str]] = None,
) -> None:
"""Generate stub for a single class using runtime introspection.
The result lines will be appended to 'output'. If necessary, any
required names will be added to 'imports'.
"""
# typeshed gives obj.__dict__ the not quite correct type Dict[str, Any]
# (it could be a mappingproxy!), which makes mypyc mad, so obfuscate it.
obj_dict = getattr(obj, "__dict__") # type: Mapping[str, Any] # noqa
items = sorted(obj_dict.items(), key=lambda x: method_name_sort_key(x[0]))
methods = [] # type: List[str]
types = [] # type: List[str]
static_properties = [] # type: List[str]
rw_properties = [] # type: List[str]
ro_properties = [] # type: List[str]
done = set() # type: Set[str]
for attr, value in items:
if is_c_method(value) or is_c_classmethod(value):
done.add(attr)
if not is_skipped_attribute(attr):
if attr == "__new__":
# TODO: We should support __new__.
if "__init__" in obj_dict:
# Avoid duplicate functions if both are present.
# But is there any case where .__new__() has a
# better signature than __init__() ?
continue
attr = "__init__"
if is_c_classmethod(value):
methods.append("@classmethod")
self_var = "cls"
else:
self_var = "self"
generate_c_function_stub(
module,
attr,
value,
methods,
imports=imports,
self_var=self_var,
sigs=sigs,
class_name=class_name,
class_sigs=class_sigs,
)
elif is_c_property(value):
done.add(attr)
generate_c_property_stub(
attr,
value,
static_properties,
rw_properties,
ro_properties,
is_c_property_readonly(value),
module=module,
imports=imports,
)
elif is_c_type(value):
generate_c_type_stub(
module,
attr,
value,
types,
imports=imports,
sigs=sigs,
class_sigs=class_sigs,
)
done.add(attr)
for attr, value in items:
if is_skipped_attribute(attr):
continue
if attr not in done:
static_properties.append(
"%s: ClassVar[%s] = ..."
% (
attr,
strip_or_import(get_type_fullname(type(value)), module, imports),
)
)
all_bases = obj.mro()
if all_bases[-1] is object:
# TODO: Is this always object?
del all_bases[-1]
# remove pybind11_object. All classes generated by pybind11 have pybind11_object in their MRO,
# which only overrides a few functions in object type
if all_bases and all_bases[-1].__name__ == "pybind11_object":
del all_bases[-1]
# remove the class itself
all_bases = all_bases[1:]
# Remove base classes of other bases as redundant.
bases = [] # type: List[type]
for base in all_bases:
if not any(issubclass(b, base) for b in bases):
bases.append(base)
if bases:
bases_str = "(%s)" % ", ".join(
strip_or_import(get_type_fullname(base), module, imports) for base in bases
)
else:
bases_str = ""
if types or static_properties or rw_properties or methods or ro_properties:
output.append("class %s%s:" % (class_name, bases_str))
for line in types:
if (
output
and output[-1]
and not output[-1].startswith("class")
and line.startswith("class")
):
output.append("")
output.append(" " + line)
for line in static_properties:
output.append(" %s" % line)
for line in rw_properties:
output.append(" %s" % line)
for line in methods:
output.append(" %s" % line)
for line in ro_properties:
output.append(" %s" % line)
else:
output.append("class %s%s: ..." % (class_name, bases_str))
|
https://github.com/python/mypy/issues/10137
|
PS C:\Users\Gen\Repos> stubgen -m av.enum
Traceback (most recent call last):
File "c:\users\gen\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "c:\users\gen\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\Gen\AppData\Local\Programs\Python\Python39\Scripts\stubgen.exe\__main__.py", line 7, in <module>
File "mypy\stubgen.py", line 1582, in main
File "mypy\stubgen.py", line 1475, in generate_stubs
File "mypy\stubgenc.py", line 64, in generate_stub_for_c_module
File "mypy\stubgenc.py", line 315, in generate_c_type_stub
TypeError: unbound method type.mro() needs an argument
|
TypeError
|
def refresh_suppressed_submodules(
module: str,
path: Optional[str],
deps: Dict[str, Set[str]],
graph: Graph,
fscache: FileSystemCache,
refresh_file: Callable[[str, str], List[str]],
) -> Optional[List[str]]:
"""Look for submodules that are now suppressed in target package.
If a submodule a.b gets added, we need to mark it as suppressed
in modules that contain "from a import b". Previously we assumed
that 'a.b' is not a module but a regular name.
This is only relevant when following imports normally.
Args:
module: target package in which to look for submodules
path: path of the module
refresh_file: function that reads the AST of a module (returns error messages)
Return a list of errors from refresh_file() if it was called. If the
return value is None, we didn't call refresh_file().
"""
messages = None
if path is None or not path.endswith(INIT_SUFFIXES):
# Only packages have submodules.
return None
# Find any submodules present in the directory.
pkgdir = os.path.dirname(path)
try:
entries = fscache.listdir(pkgdir)
except FileNotFoundError:
entries = []
for fnam in entries:
if (
not fnam.endswith((".py", ".pyi"))
or fnam.startswith("__init__.")
or fnam.count(".") != 1
):
continue
shortname = fnam.split(".")[0]
submodule = module + "." + shortname
trigger = make_trigger(submodule)
# We may be missing the required fine-grained deps.
ensure_deps_loaded(module, deps, graph)
if trigger in deps:
for dep in deps[trigger]:
# We can ignore <...> deps since a submodule can't trigger any.
state = graph.get(dep)
if not state:
# Maybe it's a non-top-level target. We only care about the module.
dep_module = module_prefix(graph, dep)
if dep_module is not None:
state = graph.get(dep_module)
if state:
# Is the file may missing an AST in case it's read from cache?
if state.tree is None:
# Create AST for the file. This may produce some new errors
# that we need to propagate.
assert state.path is not None
messages = refresh_file(state.id, state.path)
tree = state.tree
assert tree # Will be fine, due to refresh_file() above
for imp in tree.imports:
if isinstance(imp, ImportFrom):
if (
imp.id == module
and any(name == shortname for name, _ in imp.names)
and submodule not in state.suppressed_set
):
state.suppressed.append(submodule)
state.suppressed_set.add(submodule)
return messages
|
def refresh_suppressed_submodules(
module: str,
path: Optional[str],
deps: Dict[str, Set[str]],
graph: Graph,
fscache: FileSystemCache,
refresh_file: Callable[[str, str], List[str]],
) -> Optional[List[str]]:
"""Look for submodules that are now suppressed in target package.
If a submodule a.b gets added, we need to mark it as suppressed
in modules that contain "from a import b". Previously we assumed
that 'a.b' is not a module but a regular name.
This is only relevant when following imports normally.
Args:
module: target package in which to look for submodules
path: path of the module
refresh_file: function that reads the AST of a module (returns error messages)
Return a list of errors from refresh_file() if it was called. If the
return value is None, we didn't call refresh_file().
"""
messages = None
if path is None or not path.endswith(INIT_SUFFIXES):
# Only packages have submodules.
return None
# Find any submodules present in the directory.
pkgdir = os.path.dirname(path)
for fnam in fscache.listdir(pkgdir):
if (
not fnam.endswith((".py", ".pyi"))
or fnam.startswith("__init__.")
or fnam.count(".") != 1
):
continue
shortname = fnam.split(".")[0]
submodule = module + "." + shortname
trigger = make_trigger(submodule)
# We may be missing the required fine-grained deps.
ensure_deps_loaded(module, deps, graph)
if trigger in deps:
for dep in deps[trigger]:
# We can ignore <...> deps since a submodule can't trigger any.
state = graph.get(dep)
if not state:
# Maybe it's a non-top-level target. We only care about the module.
dep_module = module_prefix(graph, dep)
if dep_module is not None:
state = graph.get(dep_module)
if state:
# Is the file may missing an AST in case it's read from cache?
if state.tree is None:
# Create AST for the file. This may produce some new errors
# that we need to propagate.
assert state.path is not None
messages = refresh_file(state.id, state.path)
tree = state.tree
assert tree # Will be fine, due to refresh_file() above
for imp in tree.imports:
if isinstance(imp, ImportFrom):
if (
imp.id == module
and any(name == shortname for name, _ in imp.names)
and submodule not in state.suppressed_set
):
state.suppressed.append(submodule)
state.suppressed_set.add(submodule)
return messages
|
https://github.com/python/mypy/issues/10035
|
$ dmypy run -- t/t.py
Daemon crashed!
Traceback (most recent call last):
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 221, in serve
resp = self.run_command(command, data)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 264, in run_command
return method(self, **data)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 323, in cmd_run
return self.check(sources, is_tty, terminal_width)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 385, in check
messages = self.fine_grained_increment_follow_imports(sources)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 577, in fine_grained_increment_follow_imports
new_messages = refresh_suppressed_submodules(
File "/Users/jukka/src/mypy/mypy/server/update.py", line 1175, in refresh_suppressed_submodules
for fnam in fscache.listdir(pkgdir):
File "/Users/jukka/src/mypy/mypy/fscache.py", line 172, in listdir
raise err
File "/Users/jukka/src/mypy/mypy/fscache.py", line 168, in listdir
results = os.listdir(path)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/jukka/venv/test1/lib/python3.8/site-packages/six-stubs/moves'
|
FileNotFoundError
|
def fine_grained_increment_follow_imports(
self, sources: List[BuildSource]
) -> List[str]:
"""Like fine_grained_increment, but follow imports."""
t0 = time.time()
# TODO: Support file events
assert self.fine_grained_manager is not None
fine_grained_manager = self.fine_grained_manager
graph = fine_grained_manager.graph
manager = fine_grained_manager.manager
orig_modules = list(graph.keys())
self.update_sources(sources)
changed_paths = self.fswatcher.find_changed()
manager.search_paths = compute_search_paths(
sources, manager.options, manager.data_dir
)
t1 = time.time()
manager.log("fine-grained increment: find_changed: {:.3f}s".format(t1 - t0))
seen = {source.module for source in sources}
# Find changed modules reachable from roots (or in roots) already in graph.
changed, new_files = self.find_reachable_changed_modules(
sources, graph, seen, changed_paths
)
sources.extend(new_files)
# Process changes directly reachable from roots.
messages = fine_grained_manager.update(changed, [])
# Follow deps from changed modules (still within graph).
worklist = changed[:]
while worklist:
module = worklist.pop()
if module[0] not in graph:
continue
sources2 = self.direct_imports(module, graph)
# Filter anything already seen before. This prevents
# infinite looping if there are any self edges. (Self
# edges are maybe a bug, but...)
sources2 = [source for source in sources2 if source.module not in seen]
changed, new_files = self.find_reachable_changed_modules(
sources2, graph, seen, changed_paths
)
self.update_sources(new_files)
messages = fine_grained_manager.update(changed, [])
worklist.extend(changed)
t2 = time.time()
def refresh_file(module: str, path: str) -> List[str]:
return fine_grained_manager.update([(module, path)], [])
for module_id, state in list(graph.items()):
new_messages = refresh_suppressed_submodules(
module_id,
state.path,
fine_grained_manager.deps,
graph,
self.fscache,
refresh_file,
)
if new_messages is not None:
messages = new_messages
t3 = time.time()
# There may be new files that became available, currently treated as
# suppressed imports. Process them.
while True:
new_unsuppressed = self.find_added_suppressed(graph, seen, manager.search_paths)
if not new_unsuppressed:
break
new_files = [BuildSource(mod[1], mod[0]) for mod in new_unsuppressed]
sources.extend(new_files)
self.update_sources(new_files)
messages = fine_grained_manager.update(new_unsuppressed, [])
for module_id, path in new_unsuppressed:
new_messages = refresh_suppressed_submodules(
module_id,
path,
fine_grained_manager.deps,
graph,
self.fscache,
refresh_file,
)
if new_messages is not None:
messages = new_messages
t4 = time.time()
# Find all original modules in graph that were not reached -- they are deleted.
to_delete = []
for module_id in orig_modules:
if module_id not in graph:
continue
if module_id not in seen:
module_path = graph[module_id].path
assert module_path is not None
to_delete.append((module_id, module_path))
if to_delete:
messages = fine_grained_manager.update([], to_delete)
fix_module_deps(graph)
self.previous_sources = find_all_sources_in_build(graph)
self.update_sources(self.previous_sources)
# Store current file state as side effect
self.fswatcher.find_changed()
t5 = time.time()
manager.log("fine-grained increment: update: {:.3f}s".format(t5 - t1))
manager.add_stats(
find_changes_time=t1 - t0,
fg_update_time=t2 - t1,
refresh_suppressed_time=t3 - t2,
find_added_supressed_time=t4 - t3,
cleanup_time=t5 - t4,
)
return messages
|
def fine_grained_increment_follow_imports(
self, sources: List[BuildSource]
) -> List[str]:
"""Like fine_grained_increment, but follow imports."""
t0 = time.time()
# TODO: Support file events
assert self.fine_grained_manager is not None
fine_grained_manager = self.fine_grained_manager
graph = fine_grained_manager.graph
manager = fine_grained_manager.manager
orig_modules = list(graph.keys())
self.update_sources(sources)
changed_paths = self.fswatcher.find_changed()
manager.search_paths = compute_search_paths(
sources, manager.options, manager.data_dir
)
t1 = time.time()
manager.log("fine-grained increment: find_changed: {:.3f}s".format(t1 - t0))
seen = {source.module for source in sources}
# Find changed modules reachable from roots (or in roots) already in graph.
changed, new_files = self.find_reachable_changed_modules(
sources, graph, seen, changed_paths
)
sources.extend(new_files)
# Process changes directly reachable from roots.
messages = fine_grained_manager.update(changed, [])
# Follow deps from changed modules (still within graph).
worklist = changed[:]
while worklist:
module = worklist.pop()
if module[0] not in graph:
continue
sources2 = self.direct_imports(module, graph)
# Filter anything already seen before. This prevents
# infinite looping if there are any self edges. (Self
# edges are maybe a bug, but...)
sources2 = [source for source in sources2 if source.module not in seen]
changed, new_files = self.find_reachable_changed_modules(
sources2, graph, seen, changed_paths
)
self.update_sources(new_files)
messages = fine_grained_manager.update(changed, [])
worklist.extend(changed)
t2 = time.time()
def refresh_file(module: str, path: str) -> List[str]:
return fine_grained_manager.update([(module, path)], [])
for module_id, state in list(graph.items()):
new_messages = refresh_suppressed_submodules(
module_id,
state.path,
fine_grained_manager.deps,
graph,
self.fscache,
refresh_file,
)
if new_messages is not None:
messages = new_messages
t3 = time.time()
# There may be new files that became available, currently treated as
# suppressed imports. Process them.
while True:
new_unsuppressed = self.find_added_suppressed(graph, seen, manager.search_paths)
if not new_unsuppressed:
break
new_files = [BuildSource(mod[1], mod[0]) for mod in new_unsuppressed]
sources.extend(new_files)
self.update_sources(new_files)
messages = fine_grained_manager.update(new_unsuppressed, [])
for module_id, path in new_unsuppressed:
new_messages = refresh_suppressed_submodules(
module_id,
path,
fine_grained_manager.deps,
graph,
self.fscache,
refresh_file,
)
if new_messages is not None:
messages = new_messages
t4 = time.time()
# Find all original modules in graph that were not reached -- they are deleted.
to_delete = []
for module_id in orig_modules:
if module_id not in graph:
continue
if module_id not in seen:
module_path = graph[module_id].path
assert module_path is not None
to_delete.append((module_id, module_path))
if to_delete:
messages = fine_grained_manager.update([], to_delete)
fix_module_deps(graph)
# Store current file state as side effect
self.fswatcher.find_changed()
self.previous_sources = find_all_sources_in_build(graph)
self.update_sources(self.previous_sources)
t5 = time.time()
manager.log("fine-grained increment: update: {:.3f}s".format(t5 - t1))
manager.add_stats(
find_changes_time=t1 - t0,
fg_update_time=t2 - t1,
refresh_suppressed_time=t3 - t2,
find_added_supressed_time=t4 - t3,
cleanup_time=t5 - t4,
)
return messages
|
https://github.com/python/mypy/issues/10029
|
Daemon crashed!
Traceback (most recent call last):
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 221, in serve
resp = self.run_command(command, data)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 264, in run_command
return method(self, **data)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 323, in cmd_run
return self.check(sources, is_tty, terminal_width)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 385, in check
messages = self.fine_grained_increment_follow_imports(sources)
File "/Users/jukka/src/mypy/mypy/dmypy_server.py", line 551, in fine_grained_increment_follow_imports
messages = fine_grained_manager.update(changed, [])
File "/Users/jukka/src/mypy/mypy/server/update.py", line 243, in update
result = self.update_one(changed_modules, initial_set, removed_set)
File "/Users/jukka/src/mypy/mypy/server/update.py", line 309, in update_one
result = self.update_module(next_id, next_path, next_id in removed_set)
File "/Users/jukka/src/mypy/mypy/server/update.py", line 374, in update_module
result = update_module_isolated(module, path, manager, previous_modules, graph,
File "/Users/jukka/src/mypy/mypy/server/update.py", line 603, in update_module_isolated
state.type_check_first_pass()
File "/Users/jukka/src/mypy/mypy/build.py", line 2135, in type_check_first_pass
self.type_checker().check_first_pass()
File "/Users/jukka/src/mypy/mypy/checker.py", line 294, in check_first_pass
self.accept(d)
File "/Users/jukka/src/mypy/mypy/checker.py", line 403, in accept
report_internal_error(err, self.errors.file, stmt.line, self.errors, self.options)
File "/Users/jukka/src/mypy/mypy/errors.py", line 744, in report_internal_error
raise err
File "/Users/jukka/src/mypy/mypy/checker.py", line 401, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1073, in accept
return visitor.visit_assignment_stmt(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 2010, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/Users/jukka/src/mypy/mypy/checker.py", line 2121, in check_assignment
rvalue_type = self.check_simple_assignment(lvalue_type, rvalue, context=rvalue,
File "/Users/jukka/src/mypy/mypy/checker.py", line 2975, in check_simple_assignment
rvalue_type = self.expr_checker.accept(rvalue, lvalue_type,
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 3905, in accept
report_internal_error(err, self.chk.errors.file,
File "/Users/jukka/src/mypy/mypy/errors.py", line 744, in report_internal_error
raise err
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 3903, in accept
typ = node.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1490, in accept
return visitor.visit_name_expr(self)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 179, in visit_name_expr
result = self.analyze_ref_expr(e)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 206, in analyze_ref_expr
result = type_object_type(node, self.named_type)
File "/Users/jukka/src/mypy/mypy/checkmember.py", line 929, in type_object_type
init_index = info.mro.index(init_method.node.info)
ValueError: <TypeInfo datetime.time> is not in list
|
ValueError
|
def infer_sig_from_docstring(
docstr: Optional[str], name: str
) -> Optional[List[FunctionSig]]:
"""Convert function signature to list of TypedFunctionSig
Look for function signatures of function in docstring. Signature is a string of
the format <function_name>(<signature>) -> <return type> or perhaps without
the return type.
Returns empty list, when no signature is found, one signature in typical case,
multiple signatures, if docstring specifies multiple signatures for overload functions.
Return None if the docstring is empty.
Arguments:
* docstr: docstring
* name: name of function for which signatures are to be found
"""
if not docstr:
return None
state = DocStringParser(name)
# Return all found signatures, even if there is a parse error after some are found.
with contextlib.suppress(tokenize.TokenError):
try:
tokens = tokenize.tokenize(io.BytesIO(docstr.encode("utf-8")).readline)
for token in tokens:
state.add_token(token)
except IndentationError:
return None
sigs = state.get_signatures()
def is_unique_args(sig: FunctionSig) -> bool:
"""return true if function argument names are unique"""
return len(sig.args) == len(set((arg.name for arg in sig.args)))
# Return only signatures that have unique argument names. Mypy fails on non-uniqnue arg names.
return [sig for sig in sigs if is_unique_args(sig)]
|
def infer_sig_from_docstring(docstr: str, name: str) -> Optional[List[FunctionSig]]:
"""Convert function signature to list of TypedFunctionSig
Look for function signatures of function in docstring. Signature is a string of
the format <function_name>(<signature>) -> <return type> or perhaps without
the return type.
Returns empty list, when no signature is found, one signature in typical case,
multiple signatures, if docstring specifies multiple signatures for overload functions.
Return None if the docstring is empty.
Arguments:
* docstr: docstring
* name: name of function for which signatures are to be found
"""
if not docstr:
return None
state = DocStringParser(name)
# Return all found signatures, even if there is a parse error after some are found.
with contextlib.suppress(tokenize.TokenError):
try:
tokens = tokenize.tokenize(io.BytesIO(docstr.encode("utf-8")).readline)
for token in tokens:
state.add_token(token)
except IndentationError:
return None
sigs = state.get_signatures()
def is_unique_args(sig: FunctionSig) -> bool:
"""return true if function argument names are unique"""
return len(sig.args) == len(set((arg.name for arg in sig.args)))
# Return only signatures that have unique argument names. Mypy fails on non-uniqnue arg names.
return [sig for sig in sigs if is_unique_args(sig)]
|
https://github.com/python/mypy/issues/9888
|
Traceback (most recent call last):
File "/install/bin/stubgen", line 8, in <module>
sys.exit(main())
File "mypy/stubgen.py", line 1564, in main
File "mypy/stubgen.py", line 1457, in generate_stubs
File "mypy/stubgenc.py", line 64, in generate_stub_for_c_module
File "mypy/stubgenc.py", line 293, in generate_c_type_stub
File "mypy/stubgenc.py", line 164, in generate_c_function_stub
TypeError: str object expected; got None
|
TypeError
|
def is_protocol_implementation(
left: Instance, right: Instance, proper_subtype: bool = False
) -> bool:
"""Check whether 'left' implements the protocol 'right'.
If 'proper_subtype' is True, then check for a proper subtype.
Treat recursive protocols by using the 'assuming' structural subtype matrix
(in sparse representation, i.e. as a list of pairs (subtype, supertype)),
see also comment in nodes.TypeInfo. When we enter a check for classes
(A, P), defined as following::
class P(Protocol):
def f(self) -> P: ...
class A:
def f(self) -> A: ...
this results in A being a subtype of P without infinite recursion.
On every false result, we pop the assumption, thus avoiding an infinite recursion
as well.
"""
assert right.type.is_protocol
# We need to record this check to generate protocol fine-grained dependencies.
TypeState.record_protocol_subtype_check(left.type, right.type)
assuming = right.type.assuming_proper if proper_subtype else right.type.assuming
for l, r in reversed(assuming):
if mypy.sametypes.is_same_type(l, left) and mypy.sametypes.is_same_type(
r, right
):
return True
with pop_on_exit(assuming, left, right):
for member in right.type.protocol_members:
# nominal subtyping currently ignores '__init__' and '__new__' signatures
if member in ("__init__", "__new__"):
continue
ignore_names = member != "__call__" # __call__ can be passed kwargs
# The third argument below indicates to what self type is bound.
# We always bind self to the subtype. (Similarly to nominal types).
supertype = get_proper_type(find_member(member, right, left))
assert supertype is not None
subtype = get_proper_type(find_member(member, left, left))
# Useful for debugging:
# print(member, 'of', left, 'has type', subtype)
# print(member, 'of', right, 'has type', supertype)
if not subtype:
return False
if isinstance(subtype, PartialType):
subtype = (
NoneType()
if subtype.type is None
else Instance(
subtype.type,
[AnyType(TypeOfAny.unannotated)] * len(subtype.type.type_vars),
)
)
if not proper_subtype:
# Nominal check currently ignores arg names
# NOTE: If we ever change this, be sure to also change the call to
# SubtypeVisitor.build_subtype_kind(...) down below.
is_compat = is_subtype(
subtype, supertype, ignore_pos_arg_names=ignore_names
)
else:
is_compat = is_proper_subtype(subtype, supertype)
if not is_compat:
return False
if isinstance(subtype, NoneType) and isinstance(supertype, CallableType):
# We want __hash__ = None idiom to work even without --strict-optional
return False
subflags = get_member_flags(member, left.type)
superflags = get_member_flags(member, right.type)
if IS_SETTABLE in superflags:
# Check opposite direction for settable attributes.
if not is_subtype(supertype, subtype):
return False
if (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags):
return False
if IS_SETTABLE in superflags and IS_SETTABLE not in subflags:
return False
# This rule is copied from nominal check in checker.py
if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags:
return False
if not proper_subtype:
# Nominal check currently ignores arg names, but __call__ is special for protocols
ignore_names = right.type.protocol_members != ["__call__"]
subtype_kind = SubtypeVisitor.build_subtype_kind(
ignore_pos_arg_names=ignore_names
)
else:
subtype_kind = ProperSubtypeVisitor.build_subtype_kind()
TypeState.record_subtype_cache_entry(subtype_kind, left, right)
return True
|
def is_protocol_implementation(
left: Instance, right: Instance, proper_subtype: bool = False
) -> bool:
"""Check whether 'left' implements the protocol 'right'.
If 'proper_subtype' is True, then check for a proper subtype.
Treat recursive protocols by using the 'assuming' structural subtype matrix
(in sparse representation, i.e. as a list of pairs (subtype, supertype)),
see also comment in nodes.TypeInfo. When we enter a check for classes
(A, P), defined as following::
class P(Protocol):
def f(self) -> P: ...
class A:
def f(self) -> A: ...
this results in A being a subtype of P without infinite recursion.
On every false result, we pop the assumption, thus avoiding an infinite recursion
as well.
"""
assert right.type.is_protocol
# We need to record this check to generate protocol fine-grained dependencies.
TypeState.record_protocol_subtype_check(left.type, right.type)
assuming = right.type.assuming_proper if proper_subtype else right.type.assuming
for l, r in reversed(assuming):
if mypy.sametypes.is_same_type(l, left) and mypy.sametypes.is_same_type(
r, right
):
return True
with pop_on_exit(assuming, left, right):
for member in right.type.protocol_members:
# nominal subtyping currently ignores '__init__' and '__new__' signatures
if member in ("__init__", "__new__"):
continue
ignore_names = member != "__call__" # __call__ can be passed kwargs
# The third argument below indicates to what self type is bound.
# We always bind self to the subtype. (Similarly to nominal types).
supertype = get_proper_type(find_member(member, right, left))
assert supertype is not None
subtype = get_proper_type(find_member(member, left, left))
# Useful for debugging:
# print(member, 'of', left, 'has type', subtype)
# print(member, 'of', right, 'has type', supertype)
if not subtype:
return False
if not proper_subtype:
# Nominal check currently ignores arg names
# NOTE: If we ever change this, be sure to also change the call to
# SubtypeVisitor.build_subtype_kind(...) down below.
is_compat = is_subtype(
subtype, supertype, ignore_pos_arg_names=ignore_names
)
else:
is_compat = is_proper_subtype(subtype, supertype)
if not is_compat:
return False
if isinstance(subtype, NoneType) and isinstance(supertype, CallableType):
# We want __hash__ = None idiom to work even without --strict-optional
return False
subflags = get_member_flags(member, left.type)
superflags = get_member_flags(member, right.type)
if IS_SETTABLE in superflags:
# Check opposite direction for settable attributes.
if not is_subtype(supertype, subtype):
return False
if (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags):
return False
if IS_SETTABLE in superflags and IS_SETTABLE not in subflags:
return False
# This rule is copied from nominal check in checker.py
if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags:
return False
if not proper_subtype:
# Nominal check currently ignores arg names, but __call__ is special for protocols
ignore_names = right.type.protocol_members != ["__call__"]
subtype_kind = SubtypeVisitor.build_subtype_kind(
ignore_pos_arg_names=ignore_names
)
else:
subtype_kind = ProperSubtypeVisitor.build_subtype_kind()
TypeState.record_subtype_cache_entry(subtype_kind, left, right)
return True
|
https://github.com/python/mypy/issues/9437
|
/XXXXX/venv/lib/python3.7/site-packages/xarray/core/dataarray.py:2001: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.782
Traceback (most recent call last):
File "mypy/checker.py", line 401, in accept
File "mypy/nodes.py", line 1129, in accept
File "mypy/checker.py", line 3437, in visit_for_stmt
File "mypy/checker.py", line 3470, in analyze_iterable_item_type
File "mypy/checkexpr.py", line 2345, in check_method_call_by_name
File "mypy/checkmember.py", line 126, in analyze_member_access
File "mypy/checkmember.py", line 143, in _analyze_member_access
File "mypy/checkmember.py", line 225, in analyze_instance_member_access
File "mypy/checkmember.py", line 376, in analyze_member_var_access
File "mypy/checkmember.py", line 578, in analyze_var
File "mypy/meet.py", line 50, in meet_types
File "mypy/types.py", line 794, in accept
File "mypy/meet.py", line 497, in visit_instance
File "mypy/meet.py", line 647, in meet
File "mypy/meet.py", line 50, in meet_types
File "mypy/types.py", line 1347, in accept
File "mypy/meet.py", line 584, in visit_tuple_type
File "mypy/typeops.py", line 44, in tuple_fallback
File "mypy/join.py", line 531, in join_type_list
File "mypy/join.py", line 105, in join_types
File "mypy/types.py", line 794, in accept
File "mypy/join.py", line 158, in visit_instance
File "mypy/join.py", line 371, in join_instances
File "mypy/subtypes.py", line 143, in is_subtype_ignoring_tvars
File "mypy/subtypes.py", line 93, in is_subtype
File "mypy/subtypes.py", line 135, in _is_subtype
File "mypy/types.py", line 794, in accept
File "mypy/subtypes.py", line 259, in visit_instance
File "mypy/subtypes.py", line 541, in is_protocol_implementation
File "mypy/subtypes.py", line 93, in is_subtype
File "mypy/subtypes.py", line 135, in _is_subtype
File "mypy/types.py", line 1786, in accept
File "mypy/subtypes.py", line 459, in visit_partial_type
RuntimeError:
/XXXXX/venv/lib/python3.7/site-packages/xarray/core/dataarray.py:2001: : note: use --pdb to drop into pdb
|
RuntimeError
|
def accept(
self,
node: Expression,
type_context: Optional[Type] = None,
allow_none_return: bool = False,
always_allow_any: bool = False,
) -> Type:
"""Type check a node in the given type context. If allow_none_return
is True and this expression is a call, allow it to return None. This
applies only to this expression and not any subexpressions.
"""
if node in self.type_overrides:
return self.type_overrides[node]
self.type_context.append(type_context)
try:
if allow_none_return and isinstance(node, CallExpr):
typ = self.visit_call_expr(node, allow_none_return=True)
elif allow_none_return and isinstance(node, YieldFromExpr):
typ = self.visit_yield_from_expr(node, allow_none_return=True)
elif allow_none_return and isinstance(node, ConditionalExpr):
typ = self.visit_conditional_expr(node, allow_none_return=True)
else:
typ = node.accept(self)
except Exception as err:
report_internal_error(
err, self.chk.errors.file, node.line, self.chk.errors, self.chk.options
)
self.type_context.pop()
assert typ is not None
self.chk.store_type(node, typ)
if isinstance(node, AssignmentExpr) and not has_uninhabited_component(typ):
self.chk.store_type(node.target, typ)
if (
self.chk.options.disallow_any_expr
and not always_allow_any
and not self.chk.is_stub
and self.chk.in_checked_function()
and has_any_type(typ)
and not self.chk.current_node_deferred
):
self.msg.disallowed_any_type(typ, node)
if not self.chk.in_checked_function() or self.chk.current_node_deferred:
return AnyType(TypeOfAny.unannotated)
else:
return typ
|
def accept(
self,
node: Expression,
type_context: Optional[Type] = None,
allow_none_return: bool = False,
always_allow_any: bool = False,
) -> Type:
"""Type check a node in the given type context. If allow_none_return
is True and this expression is a call, allow it to return None. This
applies only to this expression and not any subexpressions.
"""
if node in self.type_overrides:
return self.type_overrides[node]
self.type_context.append(type_context)
try:
if allow_none_return and isinstance(node, CallExpr):
typ = self.visit_call_expr(node, allow_none_return=True)
elif allow_none_return and isinstance(node, YieldFromExpr):
typ = self.visit_yield_from_expr(node, allow_none_return=True)
elif allow_none_return and isinstance(node, ConditionalExpr):
typ = self.visit_conditional_expr(node, allow_none_return=True)
else:
typ = node.accept(self)
except Exception as err:
report_internal_error(
err, self.chk.errors.file, node.line, self.chk.errors, self.chk.options
)
self.type_context.pop()
assert typ is not None
self.chk.store_type(node, typ)
if (
self.chk.options.disallow_any_expr
and not always_allow_any
and not self.chk.is_stub
and self.chk.in_checked_function()
and has_any_type(typ)
and not self.chk.current_node_deferred
):
self.msg.disallowed_any_type(typ, node)
if not self.chk.in_checked_function() or self.chk.current_node_deferred:
return AnyType(TypeOfAny.unannotated)
else:
return typ
|
https://github.com/python/mypy/issues/9054
|
test.py:3: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.790+dev.6ee562a8f3e69ac134f8c501b79b3712c9e24bbd
Traceback (most recent call last):
File "***/bin/mypy", line 8, in <module>
sys.exit(console_entry())
File "***/python3.8/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "***/python3.8/site-packages/mypy/main.py", line 89, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "***/python3.8/site-packages/mypy/build.py", line 180, in build
result = _build(
File "***/python3.8/site-packages/mypy/build.py", line 252, in _build
graph = dispatch(sources, manager, stdout)
File "***/python3.8/site-packages/mypy/build.py", line 2626, in dispatch
process_graph(graph, manager)
File "***/python3.8/site-packages/mypy/build.py", line 2949, in process_graph
process_stale_scc(graph, scc, manager)
File "***/python3.8/site-packages/mypy/build.py", line 3047, in process_stale_scc
graph[id].type_check_first_pass()
File "***/python3.8/site-packages/mypy/build.py", line 2107, in type_check_first_pass
self.type_checker().check_first_pass()
File "***/python3.8/site-packages/mypy/checker.py", line 294, in check_first_pass
self.accept(d)
File "***/python3.8/site-packages/mypy/checker.py", line 401, in accept
stmt.accept(self)
File "***/python3.8/site-packages/mypy/nodes.py", line 677, in accept
return visitor.visit_func_def(self)
File "***/python3.8/site-packages/mypy/checker.py", line 726, in visit_func_def
self._visit_func_def(defn)
File "***/python3.8/site-packages/mypy/checker.py", line 730, in _visit_func_def
self.check_func_item(defn, name=defn.name)
File "***/python3.8/site-packages/mypy/checker.py", line 792, in check_func_item
self.check_func_def(defn, typ, name)
File "***/python3.8/site-packages/mypy/checker.py", line 975, in check_func_def
self.accept(item.body)
File "***/python3.8/site-packages/mypy/checker.py", line 401, in accept
stmt.accept(self)
File "***/python3.8/site-packages/mypy/nodes.py", line 1005, in accept
return visitor.visit_block(self)
File "***/python3.8/site-packages/mypy/checker.py", line 1973, in visit_block
self.accept(s)
File "***/python3.8/site-packages/mypy/checker.py", line 401, in accept
stmt.accept(self)
File "***/python3.8/site-packages/mypy/nodes.py", line 1196, in accept
return visitor.visit_if_stmt(self)
File "***/python3.8/site-packages/mypy/checker.py", line 3212, in visit_if_stmt
if_map, else_map = self.find_isinstance_check(e)
File "***/python3.8/site-packages/mypy/checker.py", line 3928, in find_isinstance_check
if_map, else_map = self.find_isinstance_check_helper(node)
File "***/python3.8/site-packages/mypy/checker.py", line 4104, in find_isinstance_check_helper
return self.find_isinstance_check_helper(node.target)
File "***/python3.8/site-packages/mypy/checker.py", line 4108, in find_isinstance_check_helper
vartype = type_map[node]
KeyError: <mypy.nodes.NameExpr object at 0x7fb2f0768940>
test.py:3: : note: use --pdb to drop into pdb
|
KeyError
|
def console_entry() -> None:
try:
main(None, sys.stdout, sys.stderr)
sys.stdout.flush()
sys.stderr.flush()
except BrokenPipeError:
# Python flushes standard streams on exit; redirect remaining output
# to devnull to avoid another BrokenPipeError at shutdown
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
sys.exit(2)
|
def console_entry() -> None:
main(None, sys.stdout, sys.stderr)
|
https://github.com/python/mypy/issues/9419
|
test.py:3: error: Unsupported operand types for + ("int" and "str")
Traceback (most recent call last):
File "/home/septatrix/.local/bin/mypy", line 8, in <module>
sys.exit(console_entry())
File "/home/septatrix/.local/lib/python3.8/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "mypy/main.py", line 122, in main
BrokenPipeError: [Errno 32] Broken pipe
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
BrokenPipeError: [Errno 32] Broken pipe
|
BrokenPipeError
|
def main(
script_path: Optional[str],
stdout: TextIO,
stderr: TextIO,
args: Optional[List[str]] = None,
) -> None:
"""Main entry point to the type checker.
Args:
script_path: Path to the 'mypy' script (used for finding data files).
args: Custom command-line arguments. If not given, sys.argv[1:] will
be used.
"""
util.check_python_version("mypy")
t0 = time.time()
# To log stat() calls: os.stat = stat_proxy
sys.setrecursionlimit(2**14)
if args is None:
args = sys.argv[1:]
fscache = FileSystemCache()
sources, options = process_options(
args, stdout=stdout, stderr=stderr, fscache=fscache
)
messages = []
formatter = util.FancyFormatter(stdout, stderr, options.show_error_codes)
def flush_errors(new_messages: List[str], serious: bool) -> None:
if options.pretty:
new_messages = formatter.fit_in_terminal(new_messages)
messages.extend(new_messages)
f = stderr if serious else stdout
for msg in new_messages:
if options.color_output:
msg = formatter.colorize(msg)
f.write(msg + "\n")
f.flush()
serious = False
blockers = False
res = None
try:
# Keep a dummy reference (res) for memory profiling below, as otherwise
# the result could be freed.
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
except CompileError as e:
blockers = True
if not e.use_stdout:
serious = True
if (
options.warn_unused_configs
and options.unused_configs
and not options.incremental
):
print(
"Warning: unused section(s) in %s: %s"
% (
options.config_file,
", ".join(
"[mypy-%s]" % glob
for glob in options.per_module_options.keys()
if glob in options.unused_configs
),
),
file=stderr,
)
maybe_write_junit_xml(time.time() - t0, serious, messages, options)
if MEM_PROFILE:
from mypy.memprofile import print_memory_profile
print_memory_profile()
code = 0
if messages:
code = 2 if blockers else 1
if options.error_summary:
if messages:
n_errors, n_files = util.count_stats(messages)
if n_errors:
stdout.write(
formatter.format_error(
n_errors, n_files, len(sources), options.color_output
)
+ "\n"
)
else:
stdout.write(
formatter.format_success(len(sources), options.color_output) + "\n"
)
stdout.flush()
if options.fast_exit:
# Exit without freeing objects -- it's faster.
#
# NOTE: We don't flush all open files on exit (or run other destructors)!
util.hard_exit(code)
elif code:
sys.exit(code)
# HACK: keep res alive so that mypyc won't free it before the hard_exit
list([res])
|
def main(
script_path: Optional[str],
stdout: TextIO,
stderr: TextIO,
args: Optional[List[str]] = None,
) -> None:
"""Main entry point to the type checker.
Args:
script_path: Path to the 'mypy' script (used for finding data files).
args: Custom command-line arguments. If not given, sys.argv[1:] will
be used.
"""
util.check_python_version("mypy")
t0 = time.time()
# To log stat() calls: os.stat = stat_proxy
sys.setrecursionlimit(2**14)
if args is None:
args = sys.argv[1:]
fscache = FileSystemCache()
sources, options = process_options(
args, stdout=stdout, stderr=stderr, fscache=fscache
)
messages = []
formatter = util.FancyFormatter(stdout, stderr, options.show_error_codes)
def flush_errors(new_messages: List[str], serious: bool) -> None:
if options.pretty:
new_messages = formatter.fit_in_terminal(new_messages)
messages.extend(new_messages)
f = stderr if serious else stdout
try:
for msg in new_messages:
if options.color_output:
msg = formatter.colorize(msg)
f.write(msg + "\n")
f.flush()
except BrokenPipeError:
sys.exit(2)
serious = False
blockers = False
res = None
try:
# Keep a dummy reference (res) for memory profiling below, as otherwise
# the result could be freed.
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
except CompileError as e:
blockers = True
if not e.use_stdout:
serious = True
if (
options.warn_unused_configs
and options.unused_configs
and not options.incremental
):
print(
"Warning: unused section(s) in %s: %s"
% (
options.config_file,
", ".join(
"[mypy-%s]" % glob
for glob in options.per_module_options.keys()
if glob in options.unused_configs
),
),
file=stderr,
)
maybe_write_junit_xml(time.time() - t0, serious, messages, options)
if MEM_PROFILE:
from mypy.memprofile import print_memory_profile
print_memory_profile()
code = 0
if messages:
code = 2 if blockers else 1
if options.error_summary:
if messages:
n_errors, n_files = util.count_stats(messages)
if n_errors:
stdout.write(
formatter.format_error(
n_errors, n_files, len(sources), options.color_output
)
+ "\n"
)
else:
stdout.write(
formatter.format_success(len(sources), options.color_output) + "\n"
)
stdout.flush()
if options.fast_exit:
# Exit without freeing objects -- it's faster.
#
# NOTE: We don't flush all open files on exit (or run other destructors)!
util.hard_exit(code)
elif code:
sys.exit(code)
# HACK: keep res alive so that mypyc won't free it before the hard_exit
list([res])
|
https://github.com/python/mypy/issues/9419
|
test.py:3: error: Unsupported operand types for + ("int" and "str")
Traceback (most recent call last):
File "/home/septatrix/.local/bin/mypy", line 8, in <module>
sys.exit(console_entry())
File "/home/septatrix/.local/lib/python3.8/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "mypy/main.py", line 122, in main
BrokenPipeError: [Errno 32] Broken pipe
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
BrokenPipeError: [Errno 32] Broken pipe
|
BrokenPipeError
|
def flush_errors(new_messages: List[str], serious: bool) -> None:
if options.pretty:
new_messages = formatter.fit_in_terminal(new_messages)
messages.extend(new_messages)
f = stderr if serious else stdout
for msg in new_messages:
if options.color_output:
msg = formatter.colorize(msg)
f.write(msg + "\n")
f.flush()
|
def flush_errors(new_messages: List[str], serious: bool) -> None:
if options.pretty:
new_messages = formatter.fit_in_terminal(new_messages)
messages.extend(new_messages)
f = stderr if serious else stdout
try:
for msg in new_messages:
if options.color_output:
msg = formatter.colorize(msg)
f.write(msg + "\n")
f.flush()
except BrokenPipeError:
sys.exit(2)
|
https://github.com/python/mypy/issues/9419
|
test.py:3: error: Unsupported operand types for + ("int" and "str")
Traceback (most recent call last):
File "/home/septatrix/.local/bin/mypy", line 8, in <module>
sys.exit(console_entry())
File "/home/septatrix/.local/lib/python3.8/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "mypy/main.py", line 122, in main
BrokenPipeError: [Errno 32] Broken pipe
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
BrokenPipeError: [Errno 32] Broken pipe
|
BrokenPipeError
|
def visit_super_expr(self, e: SuperExpr) -> Type:
"""Type check a super expression (non-lvalue)."""
# We have an expression like super(T, var).member
# First compute the types of T and var
types = self._super_arg_types(e)
if isinstance(types, tuple):
type_type, instance_type = types
else:
return types
# Now get the MRO
type_info = type_info_from_type(type_type)
if type_info is None:
self.chk.fail(message_registry.UNSUPPORTED_ARG_1_FOR_SUPER, e)
return AnyType(TypeOfAny.from_error)
instance_info = type_info_from_type(instance_type)
if instance_info is None:
self.chk.fail(message_registry.UNSUPPORTED_ARG_2_FOR_SUPER, e)
return AnyType(TypeOfAny.from_error)
mro = instance_info.mro
# The base is the first MRO entry *after* type_info that has a member
# with the right name
try:
index = mro.index(type_info)
except ValueError:
self.chk.fail(message_registry.SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1, e)
return AnyType(TypeOfAny.from_error)
if len(mro) == index + 1:
self.chk.fail(message_registry.TARGET_CLASS_HAS_NO_BASE_CLASS, e)
return AnyType(TypeOfAny.from_error)
for base in mro[index + 1 :]:
if e.name in base.names or base == mro[-1]:
if e.info and e.info.fallback_to_any and base == mro[-1]:
# There's an undefined base class, and we're at the end of the
# chain. That's not an error.
return AnyType(TypeOfAny.special_form)
return analyze_member_access(
name=e.name,
typ=instance_type,
is_lvalue=False,
is_super=True,
is_operator=False,
original_type=instance_type,
override_info=base,
context=e,
msg=self.msg,
chk=self.chk,
in_literal_context=self.is_literal_context(),
)
assert False, "unreachable"
|
def visit_super_expr(self, e: SuperExpr) -> Type:
"""Type check a super expression (non-lvalue)."""
# We have an expression like super(T, var).member
# First compute the types of T and var
types = self._super_arg_types(e)
if isinstance(types, tuple):
type_type, instance_type = types
else:
return types
# Now get the MRO
type_info = type_info_from_type(type_type)
if type_info is None:
self.chk.fail(message_registry.UNSUPPORTED_ARG_1_FOR_SUPER, e)
return AnyType(TypeOfAny.from_error)
instance_info = type_info_from_type(instance_type)
if instance_info is None:
self.chk.fail(message_registry.UNSUPPORTED_ARG_2_FOR_SUPER, e)
return AnyType(TypeOfAny.from_error)
mro = instance_info.mro
# The base is the first MRO entry *after* type_info that has a member
# with the right name
try:
index = mro.index(type_info)
except ValueError:
self.chk.fail(message_registry.SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1, e)
return AnyType(TypeOfAny.from_error)
for base in mro[index + 1 :]:
if e.name in base.names or base == mro[-1]:
if e.info and e.info.fallback_to_any and base == mro[-1]:
# There's an undefined base class, and we're at the end of the
# chain. That's not an error.
return AnyType(TypeOfAny.special_form)
return analyze_member_access(
name=e.name,
typ=instance_type,
is_lvalue=False,
is_super=True,
is_operator=False,
original_type=instance_type,
override_info=base,
context=e,
msg=self.msg,
chk=self.chk,
in_literal_context=self.is_literal_context(),
)
assert False, "unreachable"
|
https://github.com/python/mypy/issues/7580
|
version: 0.740+dev.fd9c1a07a984d66e35b502881aee80529c930501
Traceback (most recent call last):
File "/Users/maxchase/.pyenv/versions/structured-data/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/main.py", line 88, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/build.py", line 229, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/build.py", line 2566, in dispatch
process_graph(graph, manager)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/build.py", line 2875, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/build.py", line 2974, in process_stale_scc
graph[id].type_check_first_pass()
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/build.py", line 2070, in type_check_first_pass
self.type_checker().check_first_pass()
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 289, in check_first_pass
self.accept(d)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 396, in accept
stmt.accept(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/nodes.py", line 668, in accept
return visitor.visit_func_def(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 721, in visit_func_def
self._visit_func_def(defn)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 725, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 787, in check_func_item
self.check_func_def(defn, typ, name)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 958, in check_func_def
self.accept(item.body)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 396, in accept
stmt.accept(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/nodes.py", line 992, in accept
return visitor.visit_block(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 1917, in visit_block
self.accept(s)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 396, in accept
stmt.accept(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/nodes.py", line 668, in accept
return visitor.visit_func_def(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 721, in visit_func_def
self._visit_func_def(defn)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 725, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 787, in check_func_item
self.check_func_def(defn, typ, name)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 958, in check_func_def
self.accept(item.body)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 396, in accept
stmt.accept(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/nodes.py", line 992, in accept
return visitor.visit_block(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 1917, in visit_block
self.accept(s)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 396, in accept
stmt.accept(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/nodes.py", line 1128, in accept
return visitor.visit_return_stmt(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 2940, in visit_return_stmt
self.check_return_stmt(s)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checker.py", line 2973, in check_return_stmt
s.expr, return_type, allow_none_return=allow_none_func_call))
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checkexpr.py", line 3591, in accept
typ = self.visit_call_expr(node, allow_none_return=True)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checkexpr.py", line 264, in visit_call_expr
return self.visit_call_expr_inner(e, allow_none_return=allow_none_return)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checkexpr.py", line 313, in visit_call_expr_inner
callee_type = get_proper_type(self.accept(e.callee, type_context, always_allow_any=True))
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checkexpr.py", line 3595, in accept
typ = node.accept(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/nodes.py", line 1815, in accept
return visitor.visit_super_expr(self)
File "/Users/maxchase/.pyenv/versions/3.7.4/envs/structured-data/lib/python3.7/site-packages/mypy/checkexpr.py", line 3322, in visit_super_expr
assert False, 'unreachable'
AssertionError: unreachable
|
AssertionError
|
def analyze_class_attribute_access(
itype: Instance, name: str, mx: MemberContext
) -> Optional[Type]:
"""original_type is the type of E in the expression E.var"""
node = itype.type.get(name)
if not node:
if itype.type.fallback_to_any:
return AnyType(TypeOfAny.special_form)
return None
is_decorated = isinstance(node.node, Decorator)
is_method = is_decorated or isinstance(node.node, FuncBase)
if mx.is_lvalue:
if is_method:
mx.msg.cant_assign_to_method(mx.context)
if isinstance(node.node, TypeInfo):
mx.msg.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, mx.context)
# If a final attribute was declared on `self` in `__init__`, then it
# can't be accessed on the class object.
if node.implicit and isinstance(node.node, Var) and node.node.is_final:
mx.msg.fail(
message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR.format(node.node.name()),
mx.context,
)
# An assignment to final attribute on class object is also always an error,
# independently of types.
if mx.is_lvalue and not mx.chk.get_final_context():
check_final_member(name, itype.type, mx.msg, mx.context)
if itype.type.is_enum and not (mx.is_lvalue or is_decorated or is_method):
return itype
t = node.type
if t:
if isinstance(t, PartialType):
symnode = node.node
assert isinstance(symnode, Var)
return mx.chk.handle_partial_var_type(t, mx.is_lvalue, symnode, mx.context)
# Find the class where method/variable was defined.
# mypyc hack to workaround mypy misunderstanding multiple inheritance (#3603)
node_node = node.node # type: Any
if isinstance(node_node, Decorator):
super_info = node_node.var.info # type: Optional[TypeInfo]
elif isinstance(node_node, (Var, FuncBase)):
super_info = node_node.info
else:
super_info = None
# Map the type to how it would look as a defining class. For example:
# class C(Generic[T]): ...
# class D(C[Tuple[T, S]]): ...
# D[int, str].method()
# Here itype is D[int, str], isuper is C[Tuple[int, str]].
if not super_info:
isuper = None
else:
isuper = map_instance_to_supertype(itype, super_info)
if isinstance(node.node, Var):
assert isuper is not None
# Check if original variable type has type variables. For example:
# class C(Generic[T]):
# x: T
# C.x # Error, ambiguous access
# C[int].x # Also an error, since C[int] is same as C at runtime
if isinstance(t, TypeVarType) or get_type_vars(t):
# Exception: access on Type[...], including first argument of class methods is OK.
if not isinstance(mx.original_type, TypeType):
mx.msg.fail(
message_registry.GENERIC_INSTANCE_VAR_CLASS_ACCESS, mx.context
)
# Erase non-mapped variables, but keep mapped ones, even if there is an error.
# In the above example this means that we infer following types:
# C.x -> Any
# C[int].x -> int
t = erase_typevars(expand_type_by_instance(t, isuper))
is_classmethod = (
is_decorated and cast(Decorator, node.node).func.is_class
) or (isinstance(node.node, FuncBase) and node.node.is_class)
result = add_class_tvars(
t, itype, isuper, is_classmethod, mx.builtin_type, mx.original_type
)
if not mx.is_lvalue:
result = analyze_descriptor_access(
mx.original_type,
result,
mx.builtin_type,
mx.msg,
mx.context,
chk=mx.chk,
)
return result
elif isinstance(node.node, Var):
mx.not_ready_callback(name, mx.context)
return AnyType(TypeOfAny.special_form)
if isinstance(node.node, TypeVarExpr):
mx.msg.fail(
message_registry.CANNOT_USE_TYPEVAR_AS_EXPRESSION.format(
itype.type.name(), name
),
mx.context,
)
return AnyType(TypeOfAny.from_error)
if isinstance(node.node, TypeInfo):
return type_object_type(node.node, mx.builtin_type)
if isinstance(node.node, MypyFile):
# Reference to a module object.
return mx.builtin_type("types.ModuleType")
if isinstance(node.node, TypeAlias) and isinstance(node.node.target, Instance):
return instance_alias_type(node.node, mx.builtin_type)
if is_decorated:
assert isinstance(node.node, Decorator)
if node.node.type:
return node.node.type
else:
mx.not_ready_callback(name, mx.context)
return AnyType(TypeOfAny.from_error)
else:
return function_type(
cast(FuncBase, node.node), mx.builtin_type("builtins.function")
)
|
def analyze_class_attribute_access(
itype: Instance, name: str, mx: MemberContext
) -> Optional[Type]:
"""original_type is the type of E in the expression E.var"""
node = itype.type.get(name)
if not node:
if itype.type.fallback_to_any:
return AnyType(TypeOfAny.special_form)
return None
is_decorated = isinstance(node.node, Decorator)
is_method = is_decorated or isinstance(node.node, FuncBase)
if mx.is_lvalue:
if is_method:
mx.msg.cant_assign_to_method(mx.context)
if isinstance(node.node, TypeInfo):
mx.msg.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, mx.context)
# If a final attribute was declared on `self` in `__init__`, then it
# can't be accessed on the class object.
if node.implicit and isinstance(node.node, Var) and node.node.is_final:
mx.msg.fail(
message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR.format(node.node.name()),
mx.context,
)
# An assignment to final attribute on class object is also always an error,
# independently of types.
if mx.is_lvalue and not mx.chk.get_final_context():
check_final_member(name, itype.type, mx.msg, mx.context)
if itype.type.is_enum and not (mx.is_lvalue or is_decorated or is_method):
return itype
t = node.type
if t:
if isinstance(t, PartialType):
symnode = node.node
assert isinstance(symnode, Var)
return mx.chk.handle_partial_var_type(t, mx.is_lvalue, symnode, mx.context)
# Find the class where method/variable was defined.
if isinstance(node.node, Decorator):
super_info = node.node.var.info # type: Optional[TypeInfo]
elif isinstance(node.node, (Var, FuncBase)):
super_info = node.node.info
else:
super_info = None
# Map the type to how it would look as a defining class. For example:
# class C(Generic[T]): ...
# class D(C[Tuple[T, S]]): ...
# D[int, str].method()
# Here itype is D[int, str], isuper is C[Tuple[int, str]].
if not super_info:
isuper = None
else:
isuper = map_instance_to_supertype(itype, super_info)
if isinstance(node.node, Var):
assert isuper is not None
# Check if original variable type has type variables. For example:
# class C(Generic[T]):
# x: T
# C.x # Error, ambiguous access
# C[int].x # Also an error, since C[int] is same as C at runtime
if isinstance(t, TypeVarType) or get_type_vars(t):
# Exception: access on Type[...], including first argument of class methods is OK.
if not isinstance(mx.original_type, TypeType):
mx.msg.fail(
message_registry.GENERIC_INSTANCE_VAR_CLASS_ACCESS, mx.context
)
# Erase non-mapped variables, but keep mapped ones, even if there is an error.
# In the above example this means that we infer following types:
# C.x -> Any
# C[int].x -> int
t = erase_typevars(expand_type_by_instance(t, isuper))
is_classmethod = (
is_decorated and cast(Decorator, node.node).func.is_class
) or (isinstance(node.node, FuncBase) and node.node.is_class)
result = add_class_tvars(
t, itype, isuper, is_classmethod, mx.builtin_type, mx.original_type
)
if not mx.is_lvalue:
result = analyze_descriptor_access(
mx.original_type,
result,
mx.builtin_type,
mx.msg,
mx.context,
chk=mx.chk,
)
return result
elif isinstance(node.node, Var):
mx.not_ready_callback(name, mx.context)
return AnyType(TypeOfAny.special_form)
if isinstance(node.node, TypeVarExpr):
mx.msg.fail(
message_registry.CANNOT_USE_TYPEVAR_AS_EXPRESSION.format(
itype.type.name(), name
),
mx.context,
)
return AnyType(TypeOfAny.from_error)
if isinstance(node.node, TypeInfo):
return type_object_type(node.node, mx.builtin_type)
if isinstance(node.node, MypyFile):
# Reference to a module object.
return mx.builtin_type("types.ModuleType")
if isinstance(node.node, TypeAlias) and isinstance(node.node.target, Instance):
return instance_alias_type(node.node, mx.builtin_type)
if is_decorated:
assert isinstance(node.node, Decorator)
if node.node.type:
return node.node.type
else:
mx.not_ready_callback(name, mx.context)
return AnyType(TypeOfAny.from_error)
else:
return function_type(
cast(FuncBase, node.node), mx.builtin_type("builtins.function")
)
|
https://github.com/python/mypy/issues/3603
|
$ mypy i.py
$ python3 i.py
Traceback (most recent call last):
File "i.py", line 13, in <module>
goo(Child())
File "i.py", line 10, in goo
1 + 'boom' # no error from mypy but there's an error at runtime
TypeError: unsupported operand type(s) for +: 'int' and 'str'
|
TypeError
|
def type_object_type(info: TypeInfo, builtin_type: Callable[[str], Instance]) -> Type:
"""Return the type of a type object.
For a generic type G with type variables T and S the type is generally of form
Callable[..., G[T, S]]
where ... are argument types for the __init__/__new__ method (without the self
argument). Also, the fallback type will be 'type' instead of 'function'.
"""
# We take the type from whichever of __init__ and __new__ is first
# in the MRO, preferring __init__ if there is a tie.
init_method = info.get("__init__")
new_method = info.get("__new__")
if not init_method or not is_valid_constructor(init_method.node):
# Must be an invalid class definition.
return AnyType(TypeOfAny.from_error)
# There *should* always be a __new__ method except the test stubs
# lack it, so just copy init_method in that situation
new_method = new_method or init_method
if not is_valid_constructor(new_method.node):
# Must be an invalid class definition.
return AnyType(TypeOfAny.from_error)
# The two is_valid_constructor() checks ensure this.
assert isinstance(new_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator))
assert isinstance(init_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator))
init_index = info.mro.index(init_method.node.info)
new_index = info.mro.index(new_method.node.info)
fallback = info.metaclass_type or builtin_type("builtins.type")
if init_index < new_index:
method = init_method.node # type: Union[FuncBase, Decorator]
elif init_index > new_index:
method = new_method.node
else:
if init_method.node.info.fullname() == "builtins.object":
# Both are defined by object. But if we've got a bogus
# base class, we can't know for sure, so check for that.
if info.fallback_to_any:
# Construct a universal callable as the prototype.
any_type = AnyType(TypeOfAny.special_form)
sig = CallableType(
arg_types=[any_type, any_type],
arg_kinds=[ARG_STAR, ARG_STAR2],
arg_names=["_args", "_kwds"],
ret_type=any_type,
fallback=builtin_type("builtins.function"),
)
return class_callable(sig, info, fallback, None)
# Otherwise prefer __init__ in a tie. It isn't clear that this
# is the right thing, but __new__ caused problems with
# typeshed (#5647).
method = init_method.node
# Construct callable type based on signature of __init__. Adjust
# return type and insert type arguments.
if isinstance(method, FuncBase):
t = function_type(method, fallback)
else:
assert isinstance(
method.type, FunctionLike
) # is_valid_constructor() ensures this
t = method.type
return type_object_type_from_function(t, info, method.info, fallback)
|
def type_object_type(info: TypeInfo, builtin_type: Callable[[str], Instance]) -> Type:
"""Return the type of a type object.
For a generic type G with type variables T and S the type is generally of form
Callable[..., G[T, S]]
where ... are argument types for the __init__/__new__ method (without the self
argument). Also, the fallback type will be 'type' instead of 'function'.
"""
# We take the type from whichever of __init__ and __new__ is first
# in the MRO, preferring __init__ if there is a tie.
init_method = info.get("__init__")
new_method = info.get("__new__")
if not init_method or not is_valid_constructor(init_method.node):
# Must be an invalid class definition.
return AnyType(TypeOfAny.from_error)
# There *should* always be a __new__ method except the test stubs
# lack it, so just copy init_method in that situation
new_method = new_method or init_method
if not is_valid_constructor(new_method.node):
# Must be an invalid class definition.
return AnyType(TypeOfAny.from_error)
# The two is_valid_constructor() checks ensure this.
assert isinstance(new_method.node, (FuncBase, Decorator))
assert isinstance(init_method.node, (FuncBase, Decorator))
init_index = info.mro.index(init_method.node.info)
new_index = info.mro.index(new_method.node.info)
fallback = info.metaclass_type or builtin_type("builtins.type")
if init_index < new_index:
method = init_method.node # type: Union[FuncBase, Decorator]
elif init_index > new_index:
method = new_method.node
else:
if init_method.node.info.fullname() == "builtins.object":
# Both are defined by object. But if we've got a bogus
# base class, we can't know for sure, so check for that.
if info.fallback_to_any:
# Construct a universal callable as the prototype.
any_type = AnyType(TypeOfAny.special_form)
sig = CallableType(
arg_types=[any_type, any_type],
arg_kinds=[ARG_STAR, ARG_STAR2],
arg_names=["_args", "_kwds"],
ret_type=any_type,
fallback=builtin_type("builtins.function"),
)
return class_callable(sig, info, fallback, None)
# Otherwise prefer __init__ in a tie. It isn't clear that this
# is the right thing, but __new__ caused problems with
# typeshed (#5647).
method = init_method.node
# Construct callable type based on signature of __init__. Adjust
# return type and insert type arguments.
if isinstance(method, FuncBase):
t = function_type(method, fallback)
else:
assert isinstance(
method.type, FunctionLike
) # is_valid_constructor() ensures this
t = method.type
return type_object_type_from_function(t, info, method.info, fallback)
|
https://github.com/python/mypy/issues/3603
|
$ mypy i.py
$ python3 i.py
Traceback (most recent call last):
File "i.py", line 13, in <module>
goo(Child())
File "i.py", line 10, in goo
1 + 'boom' # no error from mypy but there's an error at runtime
TypeError: unsupported operand type(s) for +: 'int' and 'str'
|
TypeError
|
def __init__(
self,
name: str,
is_in_init: bool,
is_init_var: bool,
has_default: bool,
line: int,
column: int,
type: Optional[Type],
) -> None:
self.name = name
self.is_in_init = is_in_init
self.is_init_var = is_init_var
self.has_default = has_default
self.line = line
self.column = column
self.type = type
|
def __init__(
self,
name: str,
is_in_init: bool,
is_init_var: bool,
has_default: bool,
line: int,
column: int,
) -> None:
self.name = name
self.is_in_init = is_in_init
self.is_init_var = is_init_var
self.has_default = has_default
self.line = line
self.column = column
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def to_argument(self) -> Argument:
return Argument(
variable=self.to_var(),
type_annotation=self.type,
initializer=None,
kind=ARG_OPT if self.has_default else ARG_POS,
)
|
def to_argument(self, info: TypeInfo) -> Argument:
return Argument(
variable=self.to_var(info),
type_annotation=info[self.name].type,
initializer=None,
kind=ARG_OPT if self.has_default else ARG_POS,
)
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def to_var(self) -> Var:
return Var(self.name, self.type)
|
def to_var(self, info: TypeInfo) -> Var:
return Var(self.name, info[self.name].type)
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def serialize(self) -> JsonDict:
assert self.type
return {
"name": self.name,
"is_in_init": self.is_in_init,
"is_init_var": self.is_init_var,
"has_default": self.has_default,
"line": self.line,
"column": self.column,
"type": self.type.serialize(),
}
|
def serialize(self) -> JsonDict:
return {
"name": self.name,
"is_in_init": self.is_in_init,
"is_init_var": self.is_init_var,
"has_default": self.has_default,
"line": self.line,
"column": self.column,
}
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def deserialize(
cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface
) -> "DataclassAttribute":
data = data.copy()
typ = deserialize_and_fixup_type(data.pop("type"), api)
return cls(type=typ, **data)
|
def deserialize(cls, info: TypeInfo, data: JsonDict) -> "DataclassAttribute":
return cls(**data)
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def transform(self) -> None:
"""Apply all the necessary transformations to the underlying
dataclass so as to ensure it is fully type checked according
to the rules in PEP 557.
"""
ctx = self._ctx
info = self._ctx.cls.info
attributes = self.collect_attributes()
if attributes is None:
# Some definitions are not ready, defer() should be already called.
return
for attr in attributes:
if attr.type is None:
ctx.api.defer()
return
decorator_arguments = {
"init": _get_decorator_bool_argument(self._ctx, "init", True),
"eq": _get_decorator_bool_argument(self._ctx, "eq", True),
"order": _get_decorator_bool_argument(self._ctx, "order", False),
"frozen": _get_decorator_bool_argument(self._ctx, "frozen", False),
}
# If there are no attributes, it may be that the semantic analyzer has not
# processed them yet. In order to work around this, we can simply skip generating
# __init__ if there are no attributes, because if the user truly did not define any,
# then the object default __init__ with an empty signature will be present anyway.
if (
decorator_arguments["init"]
and ("__init__" not in info.names or info.names["__init__"].plugin_generated)
and attributes
):
add_method(
ctx,
"__init__",
args=[attr.to_argument() for attr in attributes if attr.is_in_init],
return_type=NoneType(),
)
if (
decorator_arguments["eq"]
and info.get("__eq__") is None
or decorator_arguments["order"]
):
# Type variable for self types in generated methods.
obj_type = ctx.api.named_type("__builtins__.object")
self_tvar_expr = TypeVarExpr(
SELF_TVAR_NAME, info.fullname + "." + SELF_TVAR_NAME, [], obj_type
)
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
# Add an eq method, but only if the class doesn't already have one.
if decorator_arguments["eq"] and info.get("__eq__") is None:
for method_name in ["__eq__", "__ne__"]:
# The TVar is used to enforce that "other" must have
# the same type as self (covariant). Note the
# "self_type" parameter to add_method.
obj_type = ctx.api.named_type("__builtins__.object")
cmp_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname + "." + SELF_TVAR_NAME, -1, [], obj_type
)
cmp_other_type = TypeVarType(cmp_tvar_def)
cmp_return_type = ctx.api.named_type("__builtins__.bool")
add_method(
ctx,
method_name,
args=[
Argument(
Var("other", cmp_other_type), cmp_other_type, None, ARG_POS
)
],
return_type=cmp_return_type,
self_type=cmp_other_type,
tvar_def=cmp_tvar_def,
)
# Add <, >, <=, >=, but only if the class has an eq method.
if decorator_arguments["order"]:
if not decorator_arguments["eq"]:
ctx.api.fail("eq must be True if order is True", ctx.cls)
for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
# Like for __eq__ and __ne__, we want "other" to match
# the self type.
obj_type = ctx.api.named_type("__builtins__.object")
order_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname + "." + SELF_TVAR_NAME, -1, [], obj_type
)
order_other_type = TypeVarType(order_tvar_def)
order_return_type = ctx.api.named_type("__builtins__.bool")
order_args = [
Argument(
Var("other", order_other_type), order_other_type, None, ARG_POS
)
]
existing_method = info.get(method_name)
if existing_method is not None and not existing_method.plugin_generated:
assert existing_method.node
ctx.api.fail(
"You may not have a custom %s method when order=True" % method_name,
existing_method.node,
)
add_method(
ctx,
method_name,
args=order_args,
return_type=order_return_type,
self_type=order_other_type,
tvar_def=order_tvar_def,
)
if decorator_arguments["frozen"]:
self._freeze(attributes)
self.reset_init_only_vars(info, attributes)
info.metadata["dataclass"] = {
"attributes": [attr.serialize() for attr in attributes],
"frozen": decorator_arguments["frozen"],
}
|
def transform(self) -> None:
"""Apply all the necessary transformations to the underlying
dataclass so as to ensure it is fully type checked according
to the rules in PEP 557.
"""
ctx = self._ctx
info = self._ctx.cls.info
attributes = self.collect_attributes()
if attributes is None:
# Some definitions are not ready, defer() should be already called.
return
for attr in attributes:
node = info.get(attr.name)
if node is None:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var and not attr.is_in_init
continue
if node.type is None:
ctx.api.defer()
return
decorator_arguments = {
"init": _get_decorator_bool_argument(self._ctx, "init", True),
"eq": _get_decorator_bool_argument(self._ctx, "eq", True),
"order": _get_decorator_bool_argument(self._ctx, "order", False),
"frozen": _get_decorator_bool_argument(self._ctx, "frozen", False),
}
# If there are no attributes, it may be that the semantic analyzer has not
# processed them yet. In order to work around this, we can simply skip generating
# __init__ if there are no attributes, because if the user truly did not define any,
# then the object default __init__ with an empty signature will be present anyway.
if (
decorator_arguments["init"]
and ("__init__" not in info.names or info.names["__init__"].plugin_generated)
and attributes
):
add_method(
ctx,
"__init__",
args=[attr.to_argument(info) for attr in attributes if attr.is_in_init],
return_type=NoneType(),
)
if (
decorator_arguments["eq"]
and info.get("__eq__") is None
or decorator_arguments["order"]
):
# Type variable for self types in generated methods.
obj_type = ctx.api.named_type("__builtins__.object")
self_tvar_expr = TypeVarExpr(
SELF_TVAR_NAME, info.fullname + "." + SELF_TVAR_NAME, [], obj_type
)
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
# Add an eq method, but only if the class doesn't already have one.
if decorator_arguments["eq"] and info.get("__eq__") is None:
for method_name in ["__eq__", "__ne__"]:
# The TVar is used to enforce that "other" must have
# the same type as self (covariant). Note the
# "self_type" parameter to add_method.
obj_type = ctx.api.named_type("__builtins__.object")
cmp_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname + "." + SELF_TVAR_NAME, -1, [], obj_type
)
cmp_other_type = TypeVarType(cmp_tvar_def)
cmp_return_type = ctx.api.named_type("__builtins__.bool")
add_method(
ctx,
method_name,
args=[
Argument(
Var("other", cmp_other_type), cmp_other_type, None, ARG_POS
)
],
return_type=cmp_return_type,
self_type=cmp_other_type,
tvar_def=cmp_tvar_def,
)
# Add <, >, <=, >=, but only if the class has an eq method.
if decorator_arguments["order"]:
if not decorator_arguments["eq"]:
ctx.api.fail("eq must be True if order is True", ctx.cls)
for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
# Like for __eq__ and __ne__, we want "other" to match
# the self type.
obj_type = ctx.api.named_type("__builtins__.object")
order_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname + "." + SELF_TVAR_NAME, -1, [], obj_type
)
order_other_type = TypeVarType(order_tvar_def)
order_return_type = ctx.api.named_type("__builtins__.bool")
order_args = [
Argument(
Var("other", order_other_type), order_other_type, None, ARG_POS
)
]
existing_method = info.get(method_name)
if existing_method is not None and not existing_method.plugin_generated:
assert existing_method.node
ctx.api.fail(
"You may not have a custom %s method when order=True" % method_name,
existing_method.node,
)
add_method(
ctx,
method_name,
args=order_args,
return_type=order_return_type,
self_type=order_other_type,
tvar_def=order_tvar_def,
)
if decorator_arguments["frozen"]:
self._freeze(attributes)
self.reset_init_only_vars(info, attributes)
info.metadata["dataclass"] = {
"attributes": [attr.serialize() for attr in attributes],
"frozen": decorator_arguments["frozen"],
}
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def reset_init_only_vars(
self, info: TypeInfo, attributes: List[DataclassAttribute]
) -> None:
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
if attr.is_init_var:
if attr.name in info.names:
del info.names[attr.name]
else:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var
for stmt in info.defn.defs.body:
if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
lvalue = stmt.lvalues[0]
if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
# Reset node so that another semantic analysis pass will
# recreate a symbol node for this attribute.
lvalue.node = None
|
def reset_init_only_vars(
self, info: TypeInfo, attributes: List[DataclassAttribute]
) -> None:
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
if attr.is_init_var:
if attr.name in info.names:
del info.names[attr.name]
else:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var and not attr.is_in_init
for stmt in info.defn.defs.body:
if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
lvalue = stmt.lvalues[0]
if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
# Reset node so that another semantic analysis pass will
# recreate a symbol node for this attribute.
lvalue.node = None
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
return None
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
if not has_default:
# Make all non-default attributes implicit because they are de-facto set
# on self in the generated __init__(), not in the class body.
sym.implicit = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
type=sym.type,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
for data in info.metadata["dataclass"]["attributes"]:
name = data["name"] # type: str
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data, ctx.api)
known_attrs.add(name)
super_attrs.append(attr)
elif all_attrs:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
for attr in all_attrs:
if attr.name == name:
all_attrs.remove(attr)
super_attrs.append(attr)
break
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
# If the issue comes from merging different classes, report it
# at the class definition point.
context = (
Context(line=attr.line, column=attr.column)
if attr in attrs
else ctx.cls
)
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
context,
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
return None
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
if not has_default:
# Make all non-default attributes implicit because they are de-facto set
# on self in the generated __init__(), not in the class body.
sym.implicit = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
for data in info.metadata["dataclass"]["attributes"]:
name = data["name"] # type: str
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data)
if attr.is_init_var:
# InitVars are removed from classes so, in order for them to be inherited
# properly, we need to re-inject them into subclasses' sym tables here.
# To do that, we look 'em up from the parents' __init__. These variables
# are subsequently removed from the sym table at the end of
# DataclassTransformer.transform.
superclass_init = info.get_method("__init__")
if isinstance(superclass_init, FuncDef):
attr_node = _get_arg_from_init(superclass_init, attr.name)
if attr_node is None:
# Continue the loop: we will look it up in the next MRO entry.
# Don't add it to the known or super attrs because we don't know
# anything about it yet
continue
else:
cls.info.names[attr.name] = attr_node
known_attrs.add(name)
super_attrs.append(attr)
elif all_attrs:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
for attr in all_attrs:
if attr.name == name:
all_attrs.remove(attr)
super_attrs.append(attr)
break
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
# If the issue comes from merging different classes, report it
# at the class definition point.
context = (
Context(line=attr.line, column=attr.column)
if attr in attrs
else ctx.cls
)
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
context,
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def _freeze(self, attributes: List[DataclassAttribute]) -> None:
"""Converts all attributes to @property methods in order to
emulate frozen classes.
"""
info = self._ctx.cls.info
for attr in attributes:
sym_node = info.names.get(attr.name)
if sym_node is not None:
var = sym_node.node
assert isinstance(var, Var)
var.is_property = True
else:
var = attr.to_var()
var.info = info
var.is_property = True
var._fullname = info.fullname + "." + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)
|
def _freeze(self, attributes: List[DataclassAttribute]) -> None:
"""Converts all attributes to @property methods in order to
emulate frozen classes.
"""
info = self._ctx.cls.info
for attr in attributes:
sym_node = info.names.get(attr.name)
if sym_node is not None:
var = sym_node.node
assert isinstance(var, Var)
var.is_property = True
else:
var = attr.to_var(info)
var.info = info
var.is_property = True
var._fullname = info.fullname + "." + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)
|
https://github.com/python/mypy/issues/6809
|
bug.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/main.py", line 84, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 163, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 218, in _build
graph = dispatch(sources, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2461, in dispatch
process_graph(graph, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2761, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 2862, in process_stale_scc
graph[id].semantic_analysis()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/build.py", line 1997, in semantic_analysis
self.manager.semantic_analyzer.visit_file(self.tree, self.xpath, self.options, patches)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 309, in visit_file
self.accept(d)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 3791, in accept
node.accept(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/nodes.py", line 896, in accept
return visitor.visit_class_def(self)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 807, in visit_class_def
self.analyze_class(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 825, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 833, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/semanal.py", line 895, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 330, in dataclass_class_maker_callback
transformer.transform()
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 100, in transform
return_type=NoneTyp(),
File "/Users/ezyang/Dev/oss/dl-hmc-calc-env/lib/python3.7/site-packages/mypy/plugins/common.py", line 97, in add_method
assert arg.type_annotation, 'All arguments must be fully typed.'
AssertionError: All arguments must be fully typed.
bug.py:11: : note: use --pdb to drop into pdb
|
AssertionError
|
def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
return None
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
if not has_default:
# Make all non-default attributes implicit because they are de-facto set
# on self in the generated __init__(), not in the class body.
sym.implicit = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
for data in info.metadata["dataclass"]["attributes"]:
name = data["name"] # type: str
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data)
if attr.is_init_var:
# InitVars are removed from classes so, in order for them to be inherited
# properly, we need to re-inject them into subclasses' sym tables here.
# To do that, we look 'em up from the parents' __init__. These variables
# are subsequently removed from the sym table at the end of
# DataclassTransformer.transform.
superclass_init = info.get_method("__init__")
if isinstance(superclass_init, FuncDef):
attr_node = _get_arg_from_init(superclass_init, attr.name)
if attr_node is not None:
cls.info.names[attr.name] = attr_node
known_attrs.add(name)
super_attrs.append(attr)
elif all_attrs:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
for attr in all_attrs:
if attr.name == name:
all_attrs.remove(attr)
super_attrs.append(attr)
break
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
# If the issue comes from merging different classes, report it
# at the class definition point.
context = (
Context(line=attr.line, column=attr.column)
if attr in attrs
else ctx.cls
)
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
context,
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
return None
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
if not has_default:
# Make all non-default attributes implicit because they are de-facto set
# on self in the generated __init__(), not in the class body.
sym.implicit = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
init_method = cls.info.get_method("__init__")
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
for data in info.metadata["dataclass"]["attributes"]:
name = data["name"] # type: str
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data)
if attr.is_init_var and isinstance(init_method, FuncDef):
# InitVars are removed from classes so, in order for them to be inherited
# properly, we need to re-inject them into subclasses' sym tables here.
# To do that, we look 'em up from the parents' __init__. These variables
# are subsequently removed from the sym table at the end of
# DataclassTransformer.transform.
for arg, arg_name in zip(
init_method.arguments, init_method.arg_names
):
if arg_name == attr.name:
cls.info.names[attr.name] = SymbolTableNode(
MDEF, arg.variable
)
known_attrs.add(name)
super_attrs.append(attr)
elif all_attrs:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
for attr in all_attrs:
if attr.name == name:
all_attrs.remove(attr)
super_attrs.append(attr)
break
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
# If the issue comes from merging different classes, report it
# at the class definition point.
context = (
Context(line=attr.line, column=attr.column)
if attr in attrs
else ctx.cls
)
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
context,
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
https://github.com/python/mypy/issues/8022
|
crash_mypy_2.py:14: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.750+dev.596cde6bd8ddcdbbe5ca2b0d0019ec689a7e8b9c
Traceback (most recent call last):
File "/Users/jake/.pyenv/versions/dbt38/bin/mypy", line 11, in <module>
load_entry_point('mypy', 'console_scripts', 'mypy')()
File "/Users/jake/src/mypy/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/Users/jake/src/mypy/mypy/main.py", line 89, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/jake/src/mypy/mypy/build.py", line 166, in build
result = _build(
File "/Users/jake/src/mypy/mypy/build.py", line 235, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/jake/src/mypy/mypy/build.py", line 2620, in dispatch
process_graph(graph, manager)
File "/Users/jake/src/mypy/mypy/build.py", line 2929, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jake/src/mypy/mypy/build.py", line 3022, in process_stale_scc
mypy.semanal_main.semantic_analysis_for_scc(graph, scc, manager.errors)
File "/Users/jake/src/mypy/mypy/semanal_main.py", line 77, in semantic_analysis_for_scc
process_top_levels(graph, scc, patches)
File "/Users/jake/src/mypy/mypy/semanal_main.py", line 198, in process_top_levels
deferred, incomplete, progress = semantic_analyze_target(next_id, state,
File "/Users/jake/src/mypy/mypy/semanal_main.py", line 325, in semantic_analyze_target
analyzer.refresh_partial(refresh_node,
File "/Users/jake/src/mypy/mypy/semanal.py", line 378, in refresh_partial
self.refresh_top_level(node)
File "/Users/jake/src/mypy/mypy/semanal.py", line 389, in refresh_top_level
self.accept(d)
File "/Users/jake/src/mypy/mypy/semanal.py", line 4659, in accept
node.accept(self)
File "/Users/jake/src/mypy/mypy/nodes.py", line 939, in accept
return visitor.visit_class_def(self)
File "/Users/jake/src/mypy/mypy/semanal.py", line 1029, in visit_class_def
self.analyze_class(defn)
File "/Users/jake/src/mypy/mypy/semanal.py", line 1106, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/jake/src/mypy/mypy/semanal.py", line 1115, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/jake/src/mypy/mypy/semanal.py", line 1161, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/jake/src/mypy/mypy/plugins/dataclasses.py", line 374, in dataclass_class_maker_callback
transformer.transform()
File "/Users/jake/src/mypy/mypy/plugins/dataclasses.py", line 87, in transform
assert attr.is_init_var and not attr.is_in_init
|
flush_error
|
def visit_instance(self, template: Instance) -> List[Constraint]:
original_actual = actual = self.actual
res = [] # type: List[Constraint]
if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol:
if template.type.protocol_members == ["__call__"]:
# Special case: a generic callback protocol
if not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
):
template.type.inferring.append(template)
call = mypy.subtypes.find_member(
"__call__", template, actual, is_operator=True
)
assert call is not None
if mypy.subtypes.is_subtype(actual, erase_typevars(call)):
subres = infer_constraints(call, actual, self.direction)
res.extend(subres)
template.type.inferring.pop()
return res
if isinstance(actual, CallableType) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, Overloaded) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, TypedDictType):
actual = actual.as_anonymous().fallback
if isinstance(actual, LiteralType):
actual = actual.fallback
if isinstance(actual, Instance):
instance = actual
erased = erase_typevars(template)
assert isinstance(erased, Instance) # type: ignore
# We always try nominal inference if possible,
# it is much faster than the structural one.
if self.direction == SUBTYPE_OF and template.type.has_base(
instance.type.fullname
):
mapped = map_instance_to_supertype(template, instance.type)
tvars = mapped.type.defn.type_vars
# N.B: We use zip instead of indexing because the lengths might have
# mismatches during daemon reprocessing.
for tvar, mapped_arg, instance_arg in zip(
tvars, mapped.args, instance.args
):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvar.variance != CONTRAVARIANT:
res.extend(
infer_constraints(mapped_arg, instance_arg, self.direction)
)
if tvar.variance != COVARIANT:
res.extend(
infer_constraints(
mapped_arg, instance_arg, neg_op(self.direction)
)
)
return res
elif self.direction == SUPERTYPE_OF and instance.type.has_base(
template.type.fullname
):
mapped = map_instance_to_supertype(instance, template.type)
tvars = template.type.defn.type_vars
# N.B: We use zip instead of indexing because the lengths might have
# mismatches during daemon reprocessing.
for tvar, mapped_arg, template_arg in zip(
tvars, mapped.args, template.args
):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvar.variance != CONTRAVARIANT:
res.extend(
infer_constraints(template_arg, mapped_arg, self.direction)
)
if tvar.variance != COVARIANT:
res.extend(
infer_constraints(
template_arg, mapped_arg, neg_op(self.direction)
)
)
return res
if (
template.type.is_protocol
and self.direction == SUPERTYPE_OF
and
# We avoid infinite recursion for structural subtypes by checking
# whether this type already appeared in the inference chain.
# This is a conservative way break the inference cycles.
# It never produces any "false" constraints but gives up soon
# on purely structural inference cycles, see #3829.
# Note that we use is_protocol_implementation instead of is_subtype
# because some type may be considered a subtype of a protocol
# due to _promote, but still not implement the protocol.
not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
)
and mypy.subtypes.is_protocol_implementation(instance, erased)
):
template.type.inferring.append(template)
self.infer_constraints_from_protocol_members(
res, instance, template, original_actual, template
)
template.type.inferring.pop()
return res
elif (
instance.type.is_protocol
and self.direction == SUBTYPE_OF
and
# We avoid infinite recursion for structural subtypes also here.
not any(
mypy.sametypes.is_same_type(instance, i)
for i in instance.type.inferring
)
and mypy.subtypes.is_protocol_implementation(erased, instance)
):
instance.type.inferring.append(instance)
self.infer_constraints_from_protocol_members(
res, instance, template, template, instance
)
instance.type.inferring.pop()
return res
if isinstance(actual, AnyType):
# IDEA: Include both ways, i.e. add negation as well?
return self.infer_against_any(template.args, actual)
if (
isinstance(actual, TupleType)
and (
is_named_instance(template, "typing.Iterable")
or is_named_instance(template, "typing.Container")
or is_named_instance(template, "typing.Sequence")
or is_named_instance(template, "typing.Reversible")
)
and self.direction == SUPERTYPE_OF
):
for item in actual.items:
cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)
res.extend(cb)
return res
elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF:
return infer_constraints(
template, mypy.typeops.tuple_fallback(actual), self.direction
)
else:
return []
|
def visit_instance(self, template: Instance) -> List[Constraint]:
original_actual = actual = self.actual
res = [] # type: List[Constraint]
if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol:
if template.type.protocol_members == ["__call__"]:
# Special case: a generic callback protocol
if not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
):
template.type.inferring.append(template)
call = mypy.subtypes.find_member(
"__call__", template, actual, is_operator=True
)
assert call is not None
if mypy.subtypes.is_subtype(actual, erase_typevars(call)):
subres = infer_constraints(call, actual, self.direction)
res.extend(subres)
template.type.inferring.pop()
return res
if isinstance(actual, CallableType) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, Overloaded) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, TypedDictType):
actual = actual.as_anonymous().fallback
if isinstance(actual, LiteralType):
actual = actual.fallback
if isinstance(actual, Instance):
instance = actual
erased = erase_typevars(template)
assert isinstance(erased, Instance) # type: ignore
# We always try nominal inference if possible,
# it is much faster than the structural one.
if self.direction == SUBTYPE_OF and template.type.has_base(
instance.type.fullname
):
mapped = map_instance_to_supertype(template, instance.type)
tvars = mapped.type.defn.type_vars
for i in range(len(instance.args)):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvars[i].variance != CONTRAVARIANT:
res.extend(
infer_constraints(
mapped.args[i], instance.args[i], self.direction
)
)
if tvars[i].variance != COVARIANT:
res.extend(
infer_constraints(
mapped.args[i], instance.args[i], neg_op(self.direction)
)
)
return res
elif self.direction == SUPERTYPE_OF and instance.type.has_base(
template.type.fullname
):
mapped = map_instance_to_supertype(instance, template.type)
tvars = template.type.defn.type_vars
for j in range(len(template.args)):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvars[j].variance != CONTRAVARIANT:
res.extend(
infer_constraints(
template.args[j], mapped.args[j], self.direction
)
)
if tvars[j].variance != COVARIANT:
res.extend(
infer_constraints(
template.args[j], mapped.args[j], neg_op(self.direction)
)
)
return res
if (
template.type.is_protocol
and self.direction == SUPERTYPE_OF
and
# We avoid infinite recursion for structural subtypes by checking
# whether this type already appeared in the inference chain.
# This is a conservative way break the inference cycles.
# It never produces any "false" constraints but gives up soon
# on purely structural inference cycles, see #3829.
# Note that we use is_protocol_implementation instead of is_subtype
# because some type may be considered a subtype of a protocol
# due to _promote, but still not implement the protocol.
not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
)
and mypy.subtypes.is_protocol_implementation(instance, erased)
):
template.type.inferring.append(template)
self.infer_constraints_from_protocol_members(
res, instance, template, original_actual, template
)
template.type.inferring.pop()
return res
elif (
instance.type.is_protocol
and self.direction == SUBTYPE_OF
and
# We avoid infinite recursion for structural subtypes also here.
not any(
mypy.sametypes.is_same_type(instance, i)
for i in instance.type.inferring
)
and mypy.subtypes.is_protocol_implementation(erased, instance)
):
instance.type.inferring.append(instance)
self.infer_constraints_from_protocol_members(
res, instance, template, template, instance
)
instance.type.inferring.pop()
return res
if isinstance(actual, AnyType):
# IDEA: Include both ways, i.e. add negation as well?
return self.infer_against_any(template.args, actual)
if (
isinstance(actual, TupleType)
and (
is_named_instance(template, "typing.Iterable")
or is_named_instance(template, "typing.Container")
or is_named_instance(template, "typing.Sequence")
or is_named_instance(template, "typing.Reversible")
)
and self.direction == SUPERTYPE_OF
):
for item in actual.items:
cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)
res.extend(cb)
return res
elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF:
return infer_constraints(
template, mypy.typeops.tuple_fallback(actual), self.direction
)
else:
return []
|
https://github.com/python/mypy/issues/3279
|
$ mypy --quick --show-traceback a.py
b.py:7: error: Revealed type is 'def () -> b.C'
/Users/jukka/src/mypy/b.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.510-dev-c856a53fe06c0ad9193d86ab35fb86693940f273-dirty
Traceback (most recent call last):
File "/Users/jukka/src/mypy/scripts/mypy", line 6, in <module>
main(__file__)
File "/Users/jukka/src/mypy/mypy/main.py", line 46, in main
res = type_check_only(sources, bin_dir, options)
File "/Users/jukka/src/mypy/mypy/main.py", line 93, in type_check_only
options=options)
File "/Users/jukka/src/mypy/mypy/build.py", line 188, in build
graph = dispatch(sources, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1570, in dispatch
process_graph(graph, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1813, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1912, in process_stale_scc
graph[id].type_check_first_pass()
File "/Users/jukka/src/mypy/mypy/build.py", line 1485, in type_check_first_pass
self.type_checker.check_first_pass()
File "/Users/jukka/src/mypy/mypy/checker.py", line 177, in check_first_pass
self.accept(d)
File "/Users/jukka/src/mypy/mypy/checker.py", line 262, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 853, in accept
return visitor.visit_assignment_stmt(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1177, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1239, in check_assignment
rvalue_type = self.check_simple_assignment(lvalue_type, rvalue, lvalue)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1698, in check_simple_assignment
rvalue_type = self.expr_checker.accept(rvalue, lvalue_type)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 2056, in accept
typ = node.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1213, in accept
return visitor.visit_name_expr(self)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 123, in visit_name_expr
return self.narrow_type_from_binder(e, result)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 2271, in narrow_type_from_binder
ans = narrow_declared_type(known_type, restriction)
File "/Users/jukka/src/mypy/mypy/meet.py", line 46, in narrow_declared_type
return meet_types(declared, narrowed)
File "/Users/jukka/src/mypy/mypy/meet.py", line 25, in meet_types
return t.accept(TypeMeetVisitor(s))
File "/Users/jukka/src/mypy/mypy/types.py", line 381, in accept
return visitor.visit_instance(self)
File "/Users/jukka/src/mypy/mypy/meet.py", line 198, in visit_instance
args.append(self.meet(t.args[i], si.args[i]))
IndexError: list index out of range
/Users/jukka/src/mypy/b.py:11: note: use --pdb to drop into pdb
|
IndexError
|
def join_instances(t: Instance, s: Instance) -> ProperType:
"""Calculate the join of two instance types."""
if t.type == s.type:
# Simplest case: join two types with the same base type (but
# potentially different arguments).
if is_subtype(t, s) or is_subtype(s, t):
# Compatible; combine type arguments.
args = [] # type: List[Type]
# N.B: We use zip instead of indexing because the lengths might have
# mismatches during daemon reprocessing.
for ta, sa in zip(t.args, s.args):
args.append(join_types(ta, sa))
return Instance(t.type, args)
else:
# Incompatible; return trivial result object.
return object_from_instance(t)
elif t.type.bases and is_subtype_ignoring_tvars(t, s):
return join_instances_via_supertype(t, s)
else:
# Now t is not a subtype of s, and t != s. Now s could be a subtype
# of t; alternatively, we need to find a common supertype. This works
# in of the both cases.
return join_instances_via_supertype(s, t)
|
def join_instances(t: Instance, s: Instance) -> ProperType:
"""Calculate the join of two instance types."""
if t.type == s.type:
# Simplest case: join two types with the same base type (but
# potentially different arguments).
if is_subtype(t, s) or is_subtype(s, t):
# Compatible; combine type arguments.
args = [] # type: List[Type]
for i in range(len(t.args)):
args.append(join_types(t.args[i], s.args[i]))
return Instance(t.type, args)
else:
# Incompatible; return trivial result object.
return object_from_instance(t)
elif t.type.bases and is_subtype_ignoring_tvars(t, s):
return join_instances_via_supertype(t, s)
else:
# Now t is not a subtype of s, and t != s. Now s could be a subtype
# of t; alternatively, we need to find a common supertype. This works
# in of the both cases.
return join_instances_via_supertype(s, t)
|
https://github.com/python/mypy/issues/3279
|
$ mypy --quick --show-traceback a.py
b.py:7: error: Revealed type is 'def () -> b.C'
/Users/jukka/src/mypy/b.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.510-dev-c856a53fe06c0ad9193d86ab35fb86693940f273-dirty
Traceback (most recent call last):
File "/Users/jukka/src/mypy/scripts/mypy", line 6, in <module>
main(__file__)
File "/Users/jukka/src/mypy/mypy/main.py", line 46, in main
res = type_check_only(sources, bin_dir, options)
File "/Users/jukka/src/mypy/mypy/main.py", line 93, in type_check_only
options=options)
File "/Users/jukka/src/mypy/mypy/build.py", line 188, in build
graph = dispatch(sources, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1570, in dispatch
process_graph(graph, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1813, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1912, in process_stale_scc
graph[id].type_check_first_pass()
File "/Users/jukka/src/mypy/mypy/build.py", line 1485, in type_check_first_pass
self.type_checker.check_first_pass()
File "/Users/jukka/src/mypy/mypy/checker.py", line 177, in check_first_pass
self.accept(d)
File "/Users/jukka/src/mypy/mypy/checker.py", line 262, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 853, in accept
return visitor.visit_assignment_stmt(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1177, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1239, in check_assignment
rvalue_type = self.check_simple_assignment(lvalue_type, rvalue, lvalue)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1698, in check_simple_assignment
rvalue_type = self.expr_checker.accept(rvalue, lvalue_type)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 2056, in accept
typ = node.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1213, in accept
return visitor.visit_name_expr(self)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 123, in visit_name_expr
return self.narrow_type_from_binder(e, result)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 2271, in narrow_type_from_binder
ans = narrow_declared_type(known_type, restriction)
File "/Users/jukka/src/mypy/mypy/meet.py", line 46, in narrow_declared_type
return meet_types(declared, narrowed)
File "/Users/jukka/src/mypy/mypy/meet.py", line 25, in meet_types
return t.accept(TypeMeetVisitor(s))
File "/Users/jukka/src/mypy/mypy/types.py", line 381, in accept
return visitor.visit_instance(self)
File "/Users/jukka/src/mypy/mypy/meet.py", line 198, in visit_instance
args.append(self.meet(t.args[i], si.args[i]))
IndexError: list index out of range
/Users/jukka/src/mypy/b.py:11: note: use --pdb to drop into pdb
|
IndexError
|
def visit_instance(self, t: Instance) -> ProperType:
if isinstance(self.s, Instance):
si = self.s
if t.type == si.type:
if is_subtype(t, self.s) or is_subtype(self.s, t):
# Combine type arguments. We could have used join below
# equivalently.
args = [] # type: List[Type]
# N.B: We use zip instead of indexing because the lengths might have
# mismatches during daemon reprocessing.
for ta, sia in zip(t.args, si.args):
args.append(self.meet(ta, sia))
return Instance(t.type, args)
else:
if state.strict_optional:
return UninhabitedType()
else:
return NoneType()
else:
if is_subtype(t, self.s):
return t
elif is_subtype(self.s, t):
# See also above comment.
return self.s
else:
if state.strict_optional:
return UninhabitedType()
else:
return NoneType()
elif isinstance(self.s, FunctionLike) and t.type.is_protocol:
call = unpack_callback_protocol(t)
if call:
return meet_types(call, self.s)
elif (
isinstance(self.s, FunctionLike)
and self.s.is_type_obj()
and t.type.is_metaclass()
):
if is_subtype(self.s.fallback, t):
return self.s
return self.default(self.s)
elif isinstance(self.s, TypeType):
return meet_types(t, self.s)
elif isinstance(self.s, TupleType):
return meet_types(t, self.s)
elif isinstance(self.s, LiteralType):
return meet_types(t, self.s)
elif isinstance(self.s, TypedDictType):
return meet_types(t, self.s)
return self.default(self.s)
|
def visit_instance(self, t: Instance) -> ProperType:
if isinstance(self.s, Instance):
si = self.s
if t.type == si.type:
if is_subtype(t, self.s) or is_subtype(self.s, t):
# Combine type arguments. We could have used join below
# equivalently.
args = [] # type: List[Type]
for i in range(len(t.args)):
args.append(self.meet(t.args[i], si.args[i]))
return Instance(t.type, args)
else:
if state.strict_optional:
return UninhabitedType()
else:
return NoneType()
else:
if is_subtype(t, self.s):
return t
elif is_subtype(self.s, t):
# See also above comment.
return self.s
else:
if state.strict_optional:
return UninhabitedType()
else:
return NoneType()
elif isinstance(self.s, FunctionLike) and t.type.is_protocol:
call = unpack_callback_protocol(t)
if call:
return meet_types(call, self.s)
elif (
isinstance(self.s, FunctionLike)
and self.s.is_type_obj()
and t.type.is_metaclass()
):
if is_subtype(self.s.fallback, t):
return self.s
return self.default(self.s)
elif isinstance(self.s, TypeType):
return meet_types(t, self.s)
elif isinstance(self.s, TupleType):
return meet_types(t, self.s)
elif isinstance(self.s, LiteralType):
return meet_types(t, self.s)
elif isinstance(self.s, TypedDictType):
return meet_types(t, self.s)
return self.default(self.s)
|
https://github.com/python/mypy/issues/3279
|
$ mypy --quick --show-traceback a.py
b.py:7: error: Revealed type is 'def () -> b.C'
/Users/jukka/src/mypy/b.py:11: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.510-dev-c856a53fe06c0ad9193d86ab35fb86693940f273-dirty
Traceback (most recent call last):
File "/Users/jukka/src/mypy/scripts/mypy", line 6, in <module>
main(__file__)
File "/Users/jukka/src/mypy/mypy/main.py", line 46, in main
res = type_check_only(sources, bin_dir, options)
File "/Users/jukka/src/mypy/mypy/main.py", line 93, in type_check_only
options=options)
File "/Users/jukka/src/mypy/mypy/build.py", line 188, in build
graph = dispatch(sources, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1570, in dispatch
process_graph(graph, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1813, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1912, in process_stale_scc
graph[id].type_check_first_pass()
File "/Users/jukka/src/mypy/mypy/build.py", line 1485, in type_check_first_pass
self.type_checker.check_first_pass()
File "/Users/jukka/src/mypy/mypy/checker.py", line 177, in check_first_pass
self.accept(d)
File "/Users/jukka/src/mypy/mypy/checker.py", line 262, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 853, in accept
return visitor.visit_assignment_stmt(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1177, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1239, in check_assignment
rvalue_type = self.check_simple_assignment(lvalue_type, rvalue, lvalue)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1698, in check_simple_assignment
rvalue_type = self.expr_checker.accept(rvalue, lvalue_type)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 2056, in accept
typ = node.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1213, in accept
return visitor.visit_name_expr(self)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 123, in visit_name_expr
return self.narrow_type_from_binder(e, result)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 2271, in narrow_type_from_binder
ans = narrow_declared_type(known_type, restriction)
File "/Users/jukka/src/mypy/mypy/meet.py", line 46, in narrow_declared_type
return meet_types(declared, narrowed)
File "/Users/jukka/src/mypy/mypy/meet.py", line 25, in meet_types
return t.accept(TypeMeetVisitor(s))
File "/Users/jukka/src/mypy/mypy/types.py", line 381, in accept
return visitor.visit_instance(self)
File "/Users/jukka/src/mypy/mypy/meet.py", line 198, in visit_instance
args.append(self.meet(t.args[i], si.args[i]))
IndexError: list index out of range
/Users/jukka/src/mypy/b.py:11: note: use --pdb to drop into pdb
|
IndexError
|
def visit_lambda_expr(self, e: LambdaExpr) -> Type:
"""Type check lambda expression."""
self.chk.check_default_args(e, body_is_trivial=False)
inferred_type, type_override = self.infer_lambda_type_using_context(e)
if not inferred_type:
self.chk.return_types.append(AnyType(TypeOfAny.special_form))
# Type check everything in the body except for the final return
# statement (it can contain tuple unpacking before return).
with self.chk.scope.push_function(e):
for stmt in e.body.body[:-1]:
stmt.accept(self.chk)
# Only type check the return expression, not the return statement.
# This is important as otherwise the following statements would be
# considered unreachable. There's no useful type context.
ret_type = self.accept(e.expr(), allow_none_return=True)
fallback = self.named_type("builtins.function")
self.chk.return_types.pop()
return callable_type(e, fallback, ret_type)
else:
# Type context available.
self.chk.return_types.append(inferred_type.ret_type)
self.chk.check_func_item(e, type_override=type_override)
if e.expr() not in self.chk.type_map:
# TODO: return expression must be accepted before exiting function scope.
self.accept(e.expr(), allow_none_return=True)
ret_type = self.chk.type_map[e.expr()]
if isinstance(get_proper_type(ret_type), NoneType):
# For "lambda ...: None", just use type from the context.
# Important when the context is Callable[..., None] which
# really means Void. See #1425.
self.chk.return_types.pop()
return inferred_type
self.chk.return_types.pop()
return replace_callable_return_type(inferred_type, ret_type)
|
def visit_lambda_expr(self, e: LambdaExpr) -> Type:
"""Type check lambda expression."""
self.chk.check_default_args(e, body_is_trivial=False)
inferred_type, type_override = self.infer_lambda_type_using_context(e)
if not inferred_type:
self.chk.return_types.append(AnyType(TypeOfAny.special_form))
# Type check everything in the body except for the final return
# statement (it can contain tuple unpacking before return).
for stmt in e.body.body[:-1]:
stmt.accept(self.chk)
# Only type check the return expression, not the return statement.
# This is important as otherwise the following statements would be
# considered unreachable. There's no useful type context.
ret_type = self.accept(e.expr(), allow_none_return=True)
fallback = self.named_type("builtins.function")
self.chk.return_types.pop()
return callable_type(e, fallback, ret_type)
else:
# Type context available.
self.chk.return_types.append(inferred_type.ret_type)
self.chk.check_func_item(e, type_override=type_override)
if e.expr() not in self.chk.type_map:
self.accept(e.expr(), allow_none_return=True)
ret_type = self.chk.type_map[e.expr()]
if isinstance(get_proper_type(ret_type), NoneType):
# For "lambda ...: None", just use type from the context.
# Important when the context is Callable[..., None] which
# really means Void. See #1425.
self.chk.return_types.pop()
return inferred_type
self.chk.return_types.pop()
return replace_callable_return_type(inferred_type, ret_type)
|
https://github.com/python/mypy/issues/8079
|
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jukka/src/mypy/mypy/__main__.py", line 12, in <module>
main(None, sys.stdout, sys.stderr)
File "/Users/jukka/src/mypy/mypy/main.py", line 89, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/jukka/src/mypy/mypy/build.py", line 167, in build
sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr, extra_plugins
File "/Users/jukka/src/mypy/mypy/build.py", line 235, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/jukka/src/mypy/mypy/build.py", line 2620, in dispatch
process_graph(graph, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 2929, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 3028, in process_stale_scc
graph[id].type_check_first_pass()
File "/Users/jukka/src/mypy/mypy/build.py", line 2119, in type_check_first_pass
self.type_checker().check_first_pass()
File "/Users/jukka/src/mypy/mypy/checker.py", line 292, in check_first_pass
self.accept(d)
File "/Users/jukka/src/mypy/mypy/checker.py", line 399, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 939, in accept
return visitor.visit_class_def(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1719, in visit_class_def
self.accept(defn.defs)
File "/Users/jukka/src/mypy/mypy/checker.py", line 399, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1004, in accept
return visitor.visit_block(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 1970, in visit_block
self.accept(s)
File "/Users/jukka/src/mypy/mypy/checker.py", line 399, in accept
stmt.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1062, in accept
return visitor.visit_assignment_stmt(self)
File "/Users/jukka/src/mypy/mypy/checker.py", line 2004, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/Users/jukka/src/mypy/mypy/checker.py", line 2140, in check_assignment
rvalue_type = self.expr_checker.accept(rvalue)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 3646, in accept
typ = node.accept(self)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 1845, in accept
return visitor.visit_lambda_expr(self)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 3251, in visit_lambda_expr
ret_type = self.accept(e.expr(), allow_none_return=True)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 3642, in accept
typ = self.visit_call_expr(node, allow_none_return=True)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 263, in visit_call_expr
return self.visit_call_expr_inner(e, allow_none_return=allow_none_return)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 299, in visit_call_expr_inner
self.try_infer_partial_type(e)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 573, in try_infer_partial_type
var = self.get_partial_self_var(e.callee.expr)
File "/Users/jukka/src/mypy/mypy/checkexpr.py", line 550, in get_partial_self_var
info = self.chk.scope.enclosing_class()
File "/Users/jukka/src/mypy/mypy/checker.py", line 4917, in enclosing_class
assert top, "This method must be called from inside a function"
AssertionError: This method must be called from inside a function
|
AssertionError
|
def analyze_var(
name: str,
var: Var,
itype: Instance,
info: TypeInfo,
mx: MemberContext,
*,
implicit: bool = False,
) -> Type:
"""Analyze access to an attribute via a Var node.
This is conceptually part of analyze_member_access and the arguments are similar.
itype is the class object in which var is defined
original_type is the type of E in the expression E.var
if implicit is True, the original Var was created as an assignment to self
"""
# Found a member variable.
itype = map_instance_to_supertype(itype, var.info)
typ = var.type
if typ:
if isinstance(typ, PartialType):
return mx.chk.handle_partial_var_type(typ, mx.is_lvalue, var, mx.context)
if mx.is_lvalue and var.is_property and not var.is_settable_property:
# TODO allow setting attributes in subclass (although it is probably an error)
mx.msg.read_only_property(name, itype.type, mx.context)
if mx.is_lvalue and var.is_classvar:
mx.msg.cant_assign_to_classvar(name, mx.context)
t = get_proper_type(expand_type_by_instance(typ, itype))
result = t # type: Type
typ = get_proper_type(typ)
if (
var.is_initialized_in_class
and isinstance(typ, FunctionLike)
and not typ.is_type_obj()
):
if mx.is_lvalue:
if var.is_property:
if not var.is_settable_property:
mx.msg.read_only_property(name, itype.type, mx.context)
else:
mx.msg.cant_assign_to_method(mx.context)
if not var.is_staticmethod:
# Class-level function objects and classmethods become bound methods:
# the former to the instance, the latter to the class.
functype = typ
# Use meet to narrow original_type to the dispatched type.
# For example, assume
# * A.f: Callable[[A1], None] where A1 <: A (maybe A1 == A)
# * B.f: Callable[[B1], None] where B1 <: B (maybe B1 == B)
# * x: Union[A1, B1]
# In `x.f`, when checking `x` against A1 we assume x is compatible with A
# and similarly for B1 when checking agains B
dispatched_type = meet.meet_types(mx.original_type, itype)
signature = freshen_function_type_vars(functype)
signature = check_self_arg(
signature,
dispatched_type,
var.is_classmethod,
mx.context,
name,
mx.msg,
)
signature = bind_self(signature, mx.self_type, var.is_classmethod)
expanded_signature = get_proper_type(
expand_type_by_instance(signature, itype)
)
freeze_type_vars(expanded_signature)
if var.is_property:
# A property cannot have an overloaded type => the cast is fine.
assert isinstance(expanded_signature, CallableType)
result = expanded_signature.ret_type
else:
result = expanded_signature
else:
if not var.is_ready:
mx.not_ready_callback(var.name, mx.context)
# Implicit 'Any' type.
result = AnyType(TypeOfAny.special_form)
fullname = "{}.{}".format(var.info.fullname, name)
hook = mx.chk.plugin.get_attribute_hook(fullname)
if result and not mx.is_lvalue and not implicit:
result = analyze_descriptor_access(
mx.original_type, result, mx.builtin_type, mx.msg, mx.context, chk=mx.chk
)
if hook:
result = hook(
AttributeContext(
get_proper_type(mx.original_type), result, mx.context, mx.chk
)
)
return result
|
def analyze_var(
name: str,
var: Var,
itype: Instance,
info: TypeInfo,
mx: MemberContext,
*,
implicit: bool = False,
) -> Type:
"""Analyze access to an attribute via a Var node.
This is conceptually part of analyze_member_access and the arguments are similar.
itype is the class object in which var is defined
original_type is the type of E in the expression E.var
if implicit is True, the original Var was created as an assignment to self
"""
# Found a member variable.
itype = map_instance_to_supertype(itype, var.info)
typ = var.type
if typ:
if isinstance(typ, PartialType):
return mx.chk.handle_partial_var_type(typ, mx.is_lvalue, var, mx.context)
if mx.is_lvalue and var.is_property and not var.is_settable_property:
# TODO allow setting attributes in subclass (although it is probably an error)
mx.msg.read_only_property(name, itype.type, mx.context)
if mx.is_lvalue and var.is_classvar:
mx.msg.cant_assign_to_classvar(name, mx.context)
t = get_proper_type(expand_type_by_instance(typ, itype))
result = t # type: Type
typ = get_proper_type(typ)
if (
var.is_initialized_in_class
and isinstance(typ, FunctionLike)
and not typ.is_type_obj()
):
if mx.is_lvalue:
if var.is_property:
if not var.is_settable_property:
mx.msg.read_only_property(name, itype.type, mx.context)
else:
mx.msg.cant_assign_to_method(mx.context)
if not var.is_staticmethod:
# Class-level function objects and classmethods become bound methods:
# the former to the instance, the latter to the class.
functype = typ
# Use meet to narrow original_type to the dispatched type.
# For example, assume
# * A.f: Callable[[A1], None] where A1 <: A (maybe A1 == A)
# * B.f: Callable[[B1], None] where B1 <: B (maybe B1 == B)
# * x: Union[A1, B1]
# In `x.f`, when checking `x` against A1 we assume x is compatible with A
# and similarly for B1 when checking agains B
dispatched_type = meet.meet_types(mx.original_type, itype)
signature = freshen_function_type_vars(functype)
signature = check_self_arg(
signature,
dispatched_type,
var.is_classmethod,
mx.context,
name,
mx.msg,
)
signature = bind_self(signature, mx.self_type, var.is_classmethod)
expanded_signature = get_proper_type(
expand_type_by_instance(signature, itype)
)
if var.is_property:
# A property cannot have an overloaded type => the cast is fine.
assert isinstance(expanded_signature, CallableType)
result = expanded_signature.ret_type
else:
result = expanded_signature
else:
if not var.is_ready:
mx.not_ready_callback(var.name, mx.context)
# Implicit 'Any' type.
result = AnyType(TypeOfAny.special_form)
fullname = "{}.{}".format(var.info.fullname, name)
hook = mx.chk.plugin.get_attribute_hook(fullname)
if result and not mx.is_lvalue and not implicit:
result = analyze_descriptor_access(
mx.original_type, result, mx.builtin_type, mx.msg, mx.context, chk=mx.chk
)
if hook:
result = hook(
AttributeContext(
get_proper_type(mx.original_type), result, mx.context, mx.chk
)
)
return result
|
https://github.com/python/mypy/issues/8072
|
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jukka/src/mypy/mypy/__main__.py", line 12, in <module>
main(None, sys.stdout, sys.stderr)
File "/Users/jukka/src/mypy/mypy/main.py", line 89, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/jukka/src/mypy/mypy/build.py", line 167, in build
sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr, extra_plugins
File "/Users/jukka/src/mypy/mypy/build.py", line 235, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/jukka/src/mypy/mypy/build.py", line 2620, in dispatch
process_graph(graph, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 2929, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 3047, in process_stale_scc
graph[id].write_cache()
File "/Users/jukka/src/mypy/mypy/build.py", line 2244, in write_cache
self.manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1410, in write_cache
data = tree.serialize()
File "/Users/jukka/src/mypy/mypy/nodes.py", line 302, in serialize
'names': self.names.serialize(self._fullname),
File "/Users/jukka/src/mypy/mypy/nodes.py", line 3083, in serialize
data[key] = value.serialize(fullname, key)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 3021, in serialize
data['node'] = self.node.serialize()
File "/Users/jukka/src/mypy/mypy/nodes.py", line 882, in serialize
'type': None if self.type is None else self.type.serialize(),
File "/Users/jukka/src/mypy/mypy/types.py", line 1218, in serialize
'arg_types': [t.serialize() for t in self.arg_types],
File "/Users/jukka/src/mypy/mypy/types.py", line 1218, in <listcomp>
'arg_types': [t.serialize() for t in self.arg_types],
File "/Users/jukka/src/mypy/mypy/types.py", line 885, in serialize
assert not self.id.is_meta_var()
AssertionError
|
AssertionError
|
def add_class_tvars(
t: ProperType,
isuper: Optional[Instance],
is_classmethod: bool,
original_type: Type,
original_vars: Optional[List[TypeVarDef]] = None,
) -> Type:
"""Instantiate type variables during analyze_class_attribute_access,
e.g T and Q in the following:
class A(Generic[T]):
@classmethod
def foo(cls: Type[Q]) -> Tuple[T, Q]: ...
class B(A[str]): pass
B.foo()
Args:
t: Declared type of the method (or property)
isuper: Current instance mapped to the superclass where method was defined, this
is usually done by map_instance_to_supertype()
is_classmethod: True if this method is decorated with @classmethod
original_type: The value of the type B in the expression B.foo() or the corresponding
component in case of a union (this is used to bind the self-types)
original_vars: Type variables of the class callable on which the method was accessed
Returns:
Expanded method type with added type variables (when needed).
"""
# TODO: verify consistency between Q and T
# We add class type variables if the class method is accessed on class object
# without applied type arguments, this matches the behavior of __init__().
# For example (continuing the example in docstring):
# A # The type of callable is def [T] () -> A[T], _not_ def () -> A[Any]
# A[int] # The type of callable is def () -> A[int]
# and
# A.foo # The type is generic def [T] () -> Tuple[T, A[T]]
# A[int].foo # The type is non-generic def () -> Tuple[int, A[int]]
#
# This behaviour is useful for defining alternative constructors for generic classes.
# To achieve such behaviour, we add the class type variables that are still free
# (i.e. appear in the return type of the class object on which the method was accessed).
if isinstance(t, CallableType):
tvars = original_vars if original_vars is not None else []
if is_classmethod:
t = freshen_function_type_vars(t)
t = bind_self(t, original_type, is_classmethod=True)
assert isuper is not None
t = cast(CallableType, expand_type_by_instance(t, isuper))
freeze_type_vars(t)
return t.copy_modified(variables=tvars + t.variables)
elif isinstance(t, Overloaded):
return Overloaded(
[
cast(
CallableType,
add_class_tvars(
item,
isuper,
is_classmethod,
original_type,
original_vars=original_vars,
),
)
for item in t.items()
]
)
if isuper is not None:
t = cast(ProperType, expand_type_by_instance(t, isuper))
return t
|
def add_class_tvars(
t: ProperType,
isuper: Optional[Instance],
is_classmethod: bool,
original_type: Type,
original_vars: Optional[List[TypeVarDef]] = None,
) -> Type:
"""Instantiate type variables during analyze_class_attribute_access,
e.g T and Q in the following:
class A(Generic[T]):
@classmethod
def foo(cls: Type[Q]) -> Tuple[T, Q]: ...
class B(A[str]): pass
B.foo()
Args:
t: Declared type of the method (or property)
isuper: Current instance mapped to the superclass where method was defined, this
is usually done by map_instance_to_supertype()
is_classmethod: True if this method is decorated with @classmethod
original_type: The value of the type B in the expression B.foo() or the corresponding
component in case of a union (this is used to bind the self-types)
original_vars: Type variables of the class callable on which the method was accessed
Returns:
Expanded method type with added type variables (when needed).
"""
# TODO: verify consistency between Q and T
# We add class type variables if the class method is accessed on class object
# without applied type arguments, this matches the behavior of __init__().
# For example (continuing the example in docstring):
# A # The type of callable is def [T] () -> A[T], _not_ def () -> A[Any]
# A[int] # The type of callable is def () -> A[int]
# and
# A.foo # The type is generic def [T] () -> Tuple[T, A[T]]
# A[int].foo # The type is non-generic def () -> Tuple[int, A[int]]
#
# This behaviour is useful for defining alternative constructors for generic classes.
# To achieve such behaviour, we add the class type variables that are still free
# (i.e. appear in the return type of the class object on which the method was accessed).
if isinstance(t, CallableType):
tvars = original_vars if original_vars is not None else []
if is_classmethod:
t = freshen_function_type_vars(t)
t = bind_self(t, original_type, is_classmethod=True)
assert isuper is not None
t = cast(CallableType, expand_type_by_instance(t, isuper))
return t.copy_modified(variables=tvars + t.variables)
elif isinstance(t, Overloaded):
return Overloaded(
[
cast(
CallableType,
add_class_tvars(
item,
isuper,
is_classmethod,
original_type,
original_vars=original_vars,
),
)
for item in t.items()
]
)
if isuper is not None:
t = cast(ProperType, expand_type_by_instance(t, isuper))
return t
|
https://github.com/python/mypy/issues/8072
|
Traceback (most recent call last):
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jukka/src/mypy/mypy/__main__.py", line 12, in <module>
main(None, sys.stdout, sys.stderr)
File "/Users/jukka/src/mypy/mypy/main.py", line 89, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/jukka/src/mypy/mypy/build.py", line 167, in build
sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr, extra_plugins
File "/Users/jukka/src/mypy/mypy/build.py", line 235, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/jukka/src/mypy/mypy/build.py", line 2620, in dispatch
process_graph(graph, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 2929, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 3047, in process_stale_scc
graph[id].write_cache()
File "/Users/jukka/src/mypy/mypy/build.py", line 2244, in write_cache
self.manager)
File "/Users/jukka/src/mypy/mypy/build.py", line 1410, in write_cache
data = tree.serialize()
File "/Users/jukka/src/mypy/mypy/nodes.py", line 302, in serialize
'names': self.names.serialize(self._fullname),
File "/Users/jukka/src/mypy/mypy/nodes.py", line 3083, in serialize
data[key] = value.serialize(fullname, key)
File "/Users/jukka/src/mypy/mypy/nodes.py", line 3021, in serialize
data['node'] = self.node.serialize()
File "/Users/jukka/src/mypy/mypy/nodes.py", line 882, in serialize
'type': None if self.type is None else self.type.serialize(),
File "/Users/jukka/src/mypy/mypy/types.py", line 1218, in serialize
'arg_types': [t.serialize() for t in self.arg_types],
File "/Users/jukka/src/mypy/mypy/types.py", line 1218, in <listcomp>
'arg_types': [t.serialize() for t in self.arg_types],
File "/Users/jukka/src/mypy/mypy/types.py", line 885, in serialize
assert not self.id.is_meta_var()
AssertionError
|
AssertionError
|
def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
return None
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname() == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
init_method = cls.info.get_method("__init__")
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname()))
for data in info.metadata["dataclass"]["attributes"]:
name = data["name"] # type: str
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data)
if attr.is_init_var and isinstance(init_method, FuncDef):
# InitVars are removed from classes so, in order for them to be inherited
# properly, we need to re-inject them into subclasses' sym tables here.
# To do that, we look 'em up from the parents' __init__. These variables
# are subsequently removed from the sym table at the end of
# DataclassTransformer.transform.
for arg, arg_name in zip(
init_method.arguments, init_method.arg_names
):
if arg_name == attr.name:
cls.info.names[attr.name] = SymbolTableNode(
MDEF, arg.variable
)
known_attrs.add(name)
super_attrs.append(attr)
elif all_attrs:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
for attr in all_attrs:
if attr.name == name:
all_attrs.remove(attr)
super_attrs.append(attr)
break
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
# If the issue comes from merging different classes, report it
# at the class definition point.
context = (
Context(line=attr.line, column=attr.column)
if attr in attrs
else ctx.cls
)
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
context,
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
return None
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname() == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
init_method = cls.info.get_method("__init__")
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname()))
for data in info.metadata["dataclass"]["attributes"]:
name = data["name"] # type: str
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data)
if attr.is_init_var and isinstance(init_method, FuncDef):
# InitVars are removed from classes so, in order for them to be inherited
# properly, we need to re-inject them into subclasses' sym tables here.
# To do that, we look 'em up from the parents' __init__. These variables
# are subsequently removed from the sym table at the end of
# DataclassTransformer.transform.
for arg, arg_name in zip(
init_method.arguments, init_method.arg_names
):
if arg_name == attr.name:
cls.info.names[attr.name] = SymbolTableNode(
MDEF, arg.variable
)
known_attrs.add(name)
super_attrs.append(attr)
else:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
(attr,) = [a for a in all_attrs if a.name == name]
all_attrs.remove(attr)
super_attrs.append(attr)
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
# If the issue comes from merging different classes, report it
# at the class definition point.
context = (
Context(line=attr.line, column=attr.column)
if attr in attrs
else ctx.cls
)
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
context,
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
https://github.com/python/mypy/issues/7792
|
Traceback (most recent call last):
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\__main__.py", line 12, in <module>
main(None, sys.stdout, sys.stderr)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\main.py", line 88, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\build.py", line 230, in _build
graph = dispatch(sources, manager, stdout)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\build.py", line 2567, in dispatch
process_graph(graph, manager)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\build.py", line 2876, in process_graph
process_stale_scc(graph, scc, manager)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\build.py", line 2969, in process_stale_scc
mypy.semanal_main.semantic_analysis_for_scc(graph, scc, manager.errors)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal_main.py", line 77, in semantic_analysis_for_scc
process_top_levels(graph, scc, patches)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal_main.py", line 202, in process_top_levels
patches)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal_main.py", line 330, in semantic_analyze_target
active_type=active_type)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal.py", line 379, in refresh_partial
self.refresh_top_level(node)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal.py", line 390, in refresh_top_level
self.accept(d)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal.py", line 4631, in accept
node.accept(self)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\nodes.py", line 927, in accept
return visitor.visit_class_def(self)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal.py", line 1023, in visit_class_def
self.analyze_class(defn)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal.py", line 1094, in analyze_class
self.analyze_class_body_common(defn)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal.py", line 1103, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\semanal.py", line 1149, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\plugins\dataclasses.py", line 367, in dataclass_class_maker_callback
transformer.transform()
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\plugins\dataclasses.py", line 79, in transform
attributes = self.collect_attributes()
File "C:\Users\anhans\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mypy\plugins\dataclasses.py", line 318, in collect_attributes
(attr,) = [a for a in all_attrs if a.name == name]
ValueError: not enough values to unpack (expected 1, got 0)
a.py:10: : note: use --pdb to drop into pdb
|
ValueError
|
def visit_instance(self, typ: Instance) -> SnapshotItem:
return (
"Instance",
encode_optional_str(typ.type.fullname()),
snapshot_types(typ.args),
("None",)
if typ.last_known_value is None
else snapshot_type(typ.last_known_value),
)
|
def visit_instance(self, typ: Instance) -> SnapshotItem:
return (
"Instance",
typ.type.fullname(),
snapshot_types(typ.args),
None if typ.last_known_value is None else snapshot_type(typ.last_known_value),
)
|
https://github.com/python/mypy/issues/7834
|
Traceback (most recent call last):
File "mypy/suggestions.py", line 212, in restore_after
File "mypy/suggestions.py", line 187, in suggest
File "mypy/suggestions.py", line 355, in get_suggestion
File "mypy/suggestions.py", line 325, in find_best
File "mypy/suggestions.py", line 524, in try_type
File "mypy/server/update.py", line 275, in trigger
File "mypy/server/update.py", line 804, in propagate_changes_using_dependencies
File "mypy/server/update.py", line 951, in reprocess_nodes
File "mypy/server/astdiff.py", line 160, in snapshot_symbol_table
File "mypy/server/astdiff.py", line 174, in snapshot_definition
File "mypy/server/astdiff.py", line 231, in snapshot_type
File "mypy/types.py", line 1061, in accept
File "mypy/server/astdiff.py", line 302, in visit_callable_type
File "mypy/server/astdiff.py", line 242, in snapshot_types
File "mypy/server/astdiff.py", line 231, in snapshot_type
File "mypy/types.py", line 1681, in accept
File "mypy/server/astdiff.py", line 325, in visit_union_type
TypeError: '<' not supported between instances of 'tuple' and 'NoneType'
|
TypeError
|
def visit_callable_type(self, typ: CallableType) -> SnapshotItem:
# FIX generics
return (
"CallableType",
snapshot_types(typ.arg_types),
snapshot_type(typ.ret_type),
tuple([encode_optional_str(name) for name in typ.arg_names]),
tuple(typ.arg_kinds),
typ.is_type_obj(),
typ.is_ellipsis_args,
)
|
def visit_callable_type(self, typ: CallableType) -> SnapshotItem:
# FIX generics
return (
"CallableType",
snapshot_types(typ.arg_types),
snapshot_type(typ.ret_type),
tuple(typ.arg_names),
tuple(typ.arg_kinds),
typ.is_type_obj(),
typ.is_ellipsis_args,
)
|
https://github.com/python/mypy/issues/7834
|
Traceback (most recent call last):
File "mypy/suggestions.py", line 212, in restore_after
File "mypy/suggestions.py", line 187, in suggest
File "mypy/suggestions.py", line 355, in get_suggestion
File "mypy/suggestions.py", line 325, in find_best
File "mypy/suggestions.py", line 524, in try_type
File "mypy/server/update.py", line 275, in trigger
File "mypy/server/update.py", line 804, in propagate_changes_using_dependencies
File "mypy/server/update.py", line 951, in reprocess_nodes
File "mypy/server/astdiff.py", line 160, in snapshot_symbol_table
File "mypy/server/astdiff.py", line 174, in snapshot_definition
File "mypy/server/astdiff.py", line 231, in snapshot_type
File "mypy/types.py", line 1061, in accept
File "mypy/server/astdiff.py", line 302, in visit_callable_type
File "mypy/server/astdiff.py", line 242, in snapshot_types
File "mypy/server/astdiff.py", line 231, in snapshot_type
File "mypy/types.py", line 1681, in accept
File "mypy/server/astdiff.py", line 325, in visit_union_type
TypeError: '<' not supported between instances of 'tuple' and 'NoneType'
|
TypeError
|
def visit_literal_type(self, typ: LiteralType) -> SnapshotItem:
return ("LiteralType", snapshot_type(typ.fallback), typ.value)
|
def visit_literal_type(self, typ: LiteralType) -> SnapshotItem:
return ("LiteralType", typ.value, snapshot_type(typ.fallback))
|
https://github.com/python/mypy/issues/7834
|
Traceback (most recent call last):
File "mypy/suggestions.py", line 212, in restore_after
File "mypy/suggestions.py", line 187, in suggest
File "mypy/suggestions.py", line 355, in get_suggestion
File "mypy/suggestions.py", line 325, in find_best
File "mypy/suggestions.py", line 524, in try_type
File "mypy/server/update.py", line 275, in trigger
File "mypy/server/update.py", line 804, in propagate_changes_using_dependencies
File "mypy/server/update.py", line 951, in reprocess_nodes
File "mypy/server/astdiff.py", line 160, in snapshot_symbol_table
File "mypy/server/astdiff.py", line 174, in snapshot_definition
File "mypy/server/astdiff.py", line 231, in snapshot_type
File "mypy/types.py", line 1061, in accept
File "mypy/server/astdiff.py", line 302, in visit_callable_type
File "mypy/server/astdiff.py", line 242, in snapshot_types
File "mypy/server/astdiff.py", line 231, in snapshot_type
File "mypy/types.py", line 1681, in accept
File "mypy/server/astdiff.py", line 325, in visit_union_type
TypeError: '<' not supported between instances of 'tuple' and 'NoneType'
|
TypeError
|
def parse_section(
prefix: str,
template: Options,
section: Mapping[str, str],
stderr: TextIO = sys.stderr,
) -> Tuple[Dict[str, object], Dict[str, str]]:
"""Parse one section of a config file.
Returns a dict of option values encountered, and a dict of report directories.
"""
results = {} # type: Dict[str, object]
report_dirs = {} # type: Dict[str, str]
for key in section:
invert = False
options_key = key
if key in config_types:
ct = config_types[key]
else:
dv = None
# We have to keep new_semantic_analyzer in Options
# for plugin compatibility but it is not a valid option anymore.
assert hasattr(template, "new_semantic_analyzer")
if key != "new_semantic_analyzer":
dv = getattr(template, key, None)
if dv is None:
if key.endswith("_report"):
report_type = key[:-7].replace("_", "-")
if report_type in defaults.REPORTER_NAMES:
report_dirs[report_type] = section[key]
else:
print(
"%sUnrecognized report type: %s" % (prefix, key),
file=stderr,
)
continue
if key.startswith("x_"):
pass # Don't complain about `x_blah` flags
elif key.startswith("no_") and hasattr(template, key[3:]):
options_key = key[3:]
invert = True
elif key.startswith("allow") and hasattr(template, "dis" + key):
options_key = "dis" + key
invert = True
elif key.startswith("disallow") and hasattr(template, key[3:]):
options_key = key[3:]
invert = True
elif key == "strict":
print(
"%sStrict mode is not supported in configuration files: specify "
"individual flags instead (see 'mypy -h' for the list of flags enabled "
"in strict mode)" % prefix,
file=stderr,
)
else:
print(
"%sUnrecognized option: %s = %s" % (prefix, key, section[key]),
file=stderr,
)
if invert:
dv = getattr(template, options_key, None)
else:
continue
ct = type(dv)
v = None # type: Any
try:
if ct is bool:
v = section.getboolean(key) # type: ignore[attr-defined] # Until better stub
if invert:
v = not v
elif callable(ct):
if invert:
print(
"%sCan not invert non-boolean key %s" % (prefix, options_key),
file=stderr,
)
continue
try:
v = ct(section.get(key))
except argparse.ArgumentTypeError as err:
print("%s%s: %s" % (prefix, key, err), file=stderr)
continue
else:
print(
"%sDon't know what type %s should have" % (prefix, key), file=stderr
)
continue
except ValueError as err:
print("%s%s: %s" % (prefix, key, err), file=stderr)
continue
if key == "silent_imports":
print(
"%ssilent_imports has been replaced by "
"ignore_missing_imports=True; follow_imports=skip" % prefix,
file=stderr,
)
if v:
if "ignore_missing_imports" not in results:
results["ignore_missing_imports"] = True
if "follow_imports" not in results:
results["follow_imports"] = "skip"
if key == "almost_silent":
print(
"%salmost_silent has been replaced by follow_imports=error" % prefix,
file=stderr,
)
if v:
if "follow_imports" not in results:
results["follow_imports"] = "error"
results[options_key] = v
return results, report_dirs
|
def parse_section(
prefix: str,
template: Options,
section: Mapping[str, str],
stderr: TextIO = sys.stderr,
) -> Tuple[Dict[str, object], Dict[str, str]]:
"""Parse one section of a config file.
Returns a dict of option values encountered, and a dict of report directories.
"""
results = {} # type: Dict[str, object]
report_dirs = {} # type: Dict[str, str]
for key in section:
invert = False
options_key = key
if key in config_types:
ct = config_types[key]
else:
dv = getattr(template, key, None)
if dv is None:
if key.endswith("_report"):
report_type = key[:-7].replace("_", "-")
if report_type in defaults.REPORTER_NAMES:
report_dirs[report_type] = section[key]
else:
print(
"%sUnrecognized report type: %s" % (prefix, key),
file=stderr,
)
continue
if key.startswith("x_"):
pass # Don't complain about `x_blah` flags
elif key.startswith("no_") and hasattr(template, key[3:]):
options_key = key[3:]
invert = True
elif key.startswith("allow") and hasattr(template, "dis" + key):
options_key = "dis" + key
invert = True
elif key.startswith("disallow") and hasattr(template, key[3:]):
options_key = key[3:]
invert = True
elif key == "strict":
print(
"%sStrict mode is not supported in configuration files: specify "
"individual flags instead (see 'mypy -h' for the list of flags enabled "
"in strict mode)" % prefix,
file=stderr,
)
else:
print(
"%sUnrecognized option: %s = %s" % (prefix, key, section[key]),
file=stderr,
)
if invert:
dv = getattr(template, options_key, None)
else:
continue
ct = type(dv)
v = None # type: Any
try:
if ct is bool:
v = section.getboolean(key) # type: ignore[attr-defined] # Until better stub
if invert:
v = not v
elif callable(ct):
if invert:
print(
"%sCan not invert non-boolean key %s" % (prefix, options_key),
file=stderr,
)
continue
try:
v = ct(section.get(key))
except argparse.ArgumentTypeError as err:
print("%s%s: %s" % (prefix, key, err), file=stderr)
continue
else:
print(
"%sDon't know what type %s should have" % (prefix, key), file=stderr
)
continue
except ValueError as err:
print("%s%s: %s" % (prefix, key, err), file=stderr)
continue
if key == "silent_imports":
print(
"%ssilent_imports has been replaced by "
"ignore_missing_imports=True; follow_imports=skip" % prefix,
file=stderr,
)
if v:
if "ignore_missing_imports" not in results:
results["ignore_missing_imports"] = True
if "follow_imports" not in results:
results["follow_imports"] = "skip"
if key == "almost_silent":
print(
"%salmost_silent has been replaced by follow_imports=error" % prefix,
file=stderr,
)
if v:
if "follow_imports" not in results:
results["follow_imports"] = "error"
results[options_key] = v
return results, report_dirs
|
https://github.com/python/mypy/issues/7523
|
Traceback (most recent call last):
File "/home/anton/.pyenv/versions/fleet-manager-service/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/home/anton/.pyenv/versions/3.7.0/envs/fleet-manager-service/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/home/anton/.pyenv/versions/3.7.0/envs/fleet-manager-service/lib/python3.7/site-packages/mypy/main.py", line 63, in main
fscache=fscache)
File "/home/anton/.pyenv/versions/3.7.0/envs/fleet-manager-service/lib/python3.7/site-packages/mypy/main.py", line 709, in process_options
parse_config_file(options, config_file, stdout, stderr)
File "/home/anton/.pyenv/versions/3.7.0/envs/fleet-manager-service/lib/python3.7/site-packages/mypy/config_parser.py", line 132, in parse_config_file
setattr(options, k, v)
AttributeError: can't set attribute
|
AttributeError
|
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: str = message_registry.INCOMPATIBLE_TYPES,
subtype_label: Optional[str] = None,
supertype_label: Optional[str] = None,
*,
code: Optional[ErrorCode] = None,
) -> bool:
"""Generate an error if the subtype is not compatible with
supertype."""
if is_subtype(subtype, supertype):
return True
subtype = get_proper_type(subtype)
supertype = get_proper_type(supertype)
if self.should_suppress_optional_error([subtype]):
return False
extra_info = [] # type: List[str]
note_msg = ""
notes = [] # type: List[str]
if subtype_label is not None or supertype_label is not None:
subtype_str, supertype_str = format_type_distinctly(subtype, supertype)
if subtype_label is not None:
extra_info.append(subtype_label + " " + subtype_str)
if supertype_label is not None:
extra_info.append(supertype_label + " " + supertype_str)
note_msg = make_inferred_type_note(context, subtype, supertype, supertype_str)
if isinstance(subtype, Instance) and isinstance(supertype, Instance):
notes = append_invariance_notes([], subtype, supertype)
if extra_info:
msg += " (" + ", ".join(extra_info) + ")"
self.fail(msg, context, code=code)
for note in notes:
self.msg.note(note, context, code=code)
if note_msg:
self.note(note_msg, context, code=code)
if (
isinstance(supertype, Instance)
and supertype.type.is_protocol
and isinstance(subtype, (Instance, TupleType, TypedDictType))
):
self.msg.report_protocol_problems(subtype, supertype, context, code=code)
if isinstance(supertype, CallableType) and isinstance(subtype, Instance):
call = find_member("__call__", subtype, subtype, is_operator=True)
if call:
self.msg.note_call(subtype, call, context, code=code)
if isinstance(subtype, (CallableType, Overloaded)) and isinstance(
supertype, Instance
):
if supertype.type.is_protocol and supertype.type.protocol_members == [
"__call__"
]:
call = find_member("__call__", supertype, subtype, is_operator=True)
assert call is not None
self.msg.note_call(supertype, call, context, code=code)
return False
|
def check_subtype(
self,
subtype: Type,
supertype: Type,
context: Context,
msg: str = message_registry.INCOMPATIBLE_TYPES,
subtype_label: Optional[str] = None,
supertype_label: Optional[str] = None,
*,
code: Optional[ErrorCode] = None,
) -> bool:
"""Generate an error if the subtype is not compatible with
supertype."""
if is_subtype(subtype, supertype):
return True
subtype = get_proper_type(subtype)
supertype = get_proper_type(supertype)
if self.should_suppress_optional_error([subtype]):
return False
extra_info = [] # type: List[str]
note_msg = ""
notes = [] # type: List[str]
if subtype_label is not None or supertype_label is not None:
subtype_str, supertype_str = format_type_distinctly(subtype, supertype)
if subtype_label is not None:
extra_info.append(subtype_label + " " + subtype_str)
if supertype_label is not None:
extra_info.append(supertype_label + " " + supertype_str)
note_msg = make_inferred_type_note(context, subtype, supertype, supertype_str)
if isinstance(subtype, Instance) and isinstance(supertype, Instance):
notes = append_invariance_notes([], subtype, supertype)
if extra_info:
msg += " (" + ", ".join(extra_info) + ")"
self.fail(msg, context, code=code)
for note in notes:
self.msg.note(note, context, code=code)
if note_msg:
self.note(note_msg, context, code=code)
if (
isinstance(supertype, Instance)
and supertype.type.is_protocol
and isinstance(subtype, (Instance, TupleType, TypedDictType))
):
self.msg.report_protocol_problems(subtype, supertype, context, code=code)
if isinstance(supertype, CallableType) and isinstance(subtype, Instance):
call = find_member("__call__", subtype, subtype)
if call:
self.msg.note_call(subtype, call, context, code=code)
if isinstance(subtype, (CallableType, Overloaded)) and isinstance(
supertype, Instance
):
if supertype.type.is_protocol and supertype.type.protocol_members == [
"__call__"
]:
call = find_member("__call__", supertype, subtype)
assert call is not None
self.msg.note_call(supertype, call, context, code=code)
return False
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def iterable_item_type(self, instance: Instance) -> Type:
iterable = map_instance_to_supertype(
instance, self.lookup_typeinfo("typing.Iterable")
)
item_type = iterable.args[0]
if not isinstance(get_proper_type(item_type), AnyType):
# This relies on 'map_instance_to_supertype' returning 'Iterable[Any]'
# in case there is no explicit base class.
return item_type
# Try also structural typing.
iter_type = get_proper_type(
find_member("__iter__", instance, instance, is_operator=True)
)
if iter_type and isinstance(iter_type, CallableType):
ret_type = get_proper_type(iter_type.ret_type)
if isinstance(ret_type, Instance):
iterator = map_instance_to_supertype(
ret_type, self.lookup_typeinfo("typing.Iterator")
)
item_type = iterator.args[0]
return item_type
|
def iterable_item_type(self, instance: Instance) -> Type:
iterable = map_instance_to_supertype(
instance, self.lookup_typeinfo("typing.Iterable")
)
item_type = iterable.args[0]
if not isinstance(get_proper_type(item_type), AnyType):
# This relies on 'map_instance_to_supertype' returning 'Iterable[Any]'
# in case there is no explicit base class.
return item_type
# Try also structural typing.
iter_type = get_proper_type(find_member("__iter__", instance, instance))
if iter_type and isinstance(iter_type, CallableType):
ret_type = get_proper_type(iter_type.ret_type)
if isinstance(ret_type, Instance):
iterator = map_instance_to_supertype(
ret_type, self.lookup_typeinfo("typing.Iterator")
)
item_type = iterator.args[0]
return item_type
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def visit_instance(self, template: Instance) -> List[Constraint]:
original_actual = actual = self.actual
res = [] # type: List[Constraint]
if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol:
if template.type.protocol_members == ["__call__"]:
# Special case: a generic callback protocol
if not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
):
template.type.inferring.append(template)
call = mypy.subtypes.find_member(
"__call__", template, actual, is_operator=True
)
assert call is not None
if mypy.subtypes.is_subtype(actual, erase_typevars(call)):
subres = infer_constraints(call, actual, self.direction)
res.extend(subres)
template.type.inferring.pop()
return res
if isinstance(actual, CallableType) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, Overloaded) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, TypedDictType):
actual = actual.as_anonymous().fallback
if isinstance(actual, Instance):
instance = actual
erased = erase_typevars(template)
assert isinstance(erased, Instance) # type: ignore
# We always try nominal inference if possible,
# it is much faster than the structural one.
if self.direction == SUBTYPE_OF and template.type.has_base(
instance.type.fullname()
):
mapped = map_instance_to_supertype(template, instance.type)
tvars = mapped.type.defn.type_vars
for i in range(len(instance.args)):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvars[i].variance != CONTRAVARIANT:
res.extend(
infer_constraints(
mapped.args[i], instance.args[i], self.direction
)
)
if tvars[i].variance != COVARIANT:
res.extend(
infer_constraints(
mapped.args[i], instance.args[i], neg_op(self.direction)
)
)
return res
elif self.direction == SUPERTYPE_OF and instance.type.has_base(
template.type.fullname()
):
mapped = map_instance_to_supertype(instance, template.type)
tvars = template.type.defn.type_vars
for j in range(len(template.args)):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvars[j].variance != CONTRAVARIANT:
res.extend(
infer_constraints(
template.args[j], mapped.args[j], self.direction
)
)
if tvars[j].variance != COVARIANT:
res.extend(
infer_constraints(
template.args[j], mapped.args[j], neg_op(self.direction)
)
)
return res
if (
template.type.is_protocol
and self.direction == SUPERTYPE_OF
and
# We avoid infinite recursion for structural subtypes by checking
# whether this type already appeared in the inference chain.
# This is a conservative way break the inference cycles.
# It never produces any "false" constraints but gives up soon
# on purely structural inference cycles, see #3829.
# Note that we use is_protocol_implementation instead of is_subtype
# because some type may be considered a subtype of a protocol
# due to _promote, but still not implement the protocol.
not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
)
and mypy.subtypes.is_protocol_implementation(instance, erased)
):
template.type.inferring.append(template)
self.infer_constraints_from_protocol_members(
res, instance, template, original_actual, template
)
template.type.inferring.pop()
return res
elif (
instance.type.is_protocol
and self.direction == SUBTYPE_OF
and
# We avoid infinite recursion for structural subtypes also here.
not any(
mypy.sametypes.is_same_type(instance, i)
for i in instance.type.inferring
)
and mypy.subtypes.is_protocol_implementation(erased, instance)
):
instance.type.inferring.append(instance)
self.infer_constraints_from_protocol_members(
res, instance, template, template, instance
)
instance.type.inferring.pop()
return res
if isinstance(actual, AnyType):
# IDEA: Include both ways, i.e. add negation as well?
return self.infer_against_any(template.args, actual)
if (
isinstance(actual, TupleType)
and (
is_named_instance(template, "typing.Iterable")
or is_named_instance(template, "typing.Container")
or is_named_instance(template, "typing.Sequence")
or is_named_instance(template, "typing.Reversible")
)
and self.direction == SUPERTYPE_OF
):
for item in actual.items:
cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)
res.extend(cb)
return res
elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF:
return infer_constraints(
template, mypy.typeops.tuple_fallback(actual), self.direction
)
else:
return []
|
def visit_instance(self, template: Instance) -> List[Constraint]:
original_actual = actual = self.actual
res = [] # type: List[Constraint]
if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol:
if template.type.protocol_members == ["__call__"]:
# Special case: a generic callback protocol
if not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
):
template.type.inferring.append(template)
call = mypy.subtypes.find_member("__call__", template, actual)
assert call is not None
if mypy.subtypes.is_subtype(actual, erase_typevars(call)):
subres = infer_constraints(call, actual, self.direction)
res.extend(subres)
template.type.inferring.pop()
return res
if isinstance(actual, CallableType) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, Overloaded) and actual.fallback is not None:
actual = actual.fallback
if isinstance(actual, TypedDictType):
actual = actual.as_anonymous().fallback
if isinstance(actual, Instance):
instance = actual
erased = erase_typevars(template)
assert isinstance(erased, Instance) # type: ignore
# We always try nominal inference if possible,
# it is much faster than the structural one.
if self.direction == SUBTYPE_OF and template.type.has_base(
instance.type.fullname()
):
mapped = map_instance_to_supertype(template, instance.type)
tvars = mapped.type.defn.type_vars
for i in range(len(instance.args)):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvars[i].variance != CONTRAVARIANT:
res.extend(
infer_constraints(
mapped.args[i], instance.args[i], self.direction
)
)
if tvars[i].variance != COVARIANT:
res.extend(
infer_constraints(
mapped.args[i], instance.args[i], neg_op(self.direction)
)
)
return res
elif self.direction == SUPERTYPE_OF and instance.type.has_base(
template.type.fullname()
):
mapped = map_instance_to_supertype(instance, template.type)
tvars = template.type.defn.type_vars
for j in range(len(template.args)):
# The constraints for generic type parameters depend on variance.
# Include constraints from both directions if invariant.
if tvars[j].variance != CONTRAVARIANT:
res.extend(
infer_constraints(
template.args[j], mapped.args[j], self.direction
)
)
if tvars[j].variance != COVARIANT:
res.extend(
infer_constraints(
template.args[j], mapped.args[j], neg_op(self.direction)
)
)
return res
if (
template.type.is_protocol
and self.direction == SUPERTYPE_OF
and
# We avoid infinite recursion for structural subtypes by checking
# whether this type already appeared in the inference chain.
# This is a conservative way break the inference cycles.
# It never produces any "false" constraints but gives up soon
# on purely structural inference cycles, see #3829.
# Note that we use is_protocol_implementation instead of is_subtype
# because some type may be considered a subtype of a protocol
# due to _promote, but still not implement the protocol.
not any(
mypy.sametypes.is_same_type(template, t)
for t in template.type.inferring
)
and mypy.subtypes.is_protocol_implementation(instance, erased)
):
template.type.inferring.append(template)
self.infer_constraints_from_protocol_members(
res, instance, template, original_actual, template
)
template.type.inferring.pop()
return res
elif (
instance.type.is_protocol
and self.direction == SUBTYPE_OF
and
# We avoid infinite recursion for structural subtypes also here.
not any(
mypy.sametypes.is_same_type(instance, i)
for i in instance.type.inferring
)
and mypy.subtypes.is_protocol_implementation(erased, instance)
):
instance.type.inferring.append(instance)
self.infer_constraints_from_protocol_members(
res, instance, template, template, instance
)
instance.type.inferring.pop()
return res
if isinstance(actual, AnyType):
# IDEA: Include both ways, i.e. add negation as well?
return self.infer_against_any(template.args, actual)
if (
isinstance(actual, TupleType)
and (
is_named_instance(template, "typing.Iterable")
or is_named_instance(template, "typing.Container")
or is_named_instance(template, "typing.Sequence")
or is_named_instance(template, "typing.Reversible")
)
and self.direction == SUPERTYPE_OF
):
for item in actual.items:
cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)
res.extend(cb)
return res
elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF:
return infer_constraints(
template, mypy.typeops.tuple_fallback(actual), self.direction
)
else:
return []
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def visit_callable_type(self, template: CallableType) -> List[Constraint]:
if isinstance(self.actual, CallableType):
cactual = self.actual
# FIX verify argument counts
# FIX what if one of the functions is generic
res = [] # type: List[Constraint]
# We can't infer constraints from arguments if the template is Callable[..., T] (with
# literal '...').
if not template.is_ellipsis_args:
# The lengths should match, but don't crash (it will error elsewhere).
for t, a in zip(template.arg_types, cactual.arg_types):
# Negate direction due to function argument type contravariance.
res.extend(infer_constraints(t, a, neg_op(self.direction)))
res.extend(
infer_constraints(template.ret_type, cactual.ret_type, self.direction)
)
return res
elif isinstance(self.actual, AnyType):
# FIX what if generic
res = self.infer_against_any(template.arg_types, self.actual)
any_type = AnyType(TypeOfAny.from_another_any, source_any=self.actual)
res.extend(infer_constraints(template.ret_type, any_type, self.direction))
return res
elif isinstance(self.actual, Overloaded):
return self.infer_against_overloaded(self.actual, template)
elif isinstance(self.actual, TypeType):
return infer_constraints(template.ret_type, self.actual.item, self.direction)
elif isinstance(self.actual, Instance):
# Instances with __call__ method defined are considered structural
# subtypes of Callable with a compatible signature.
call = mypy.subtypes.find_member(
"__call__", self.actual, self.actual, is_operator=True
)
if call:
return infer_constraints(template, call, self.direction)
else:
return []
else:
return []
|
def visit_callable_type(self, template: CallableType) -> List[Constraint]:
if isinstance(self.actual, CallableType):
cactual = self.actual
# FIX verify argument counts
# FIX what if one of the functions is generic
res = [] # type: List[Constraint]
# We can't infer constraints from arguments if the template is Callable[..., T] (with
# literal '...').
if not template.is_ellipsis_args:
# The lengths should match, but don't crash (it will error elsewhere).
for t, a in zip(template.arg_types, cactual.arg_types):
# Negate direction due to function argument type contravariance.
res.extend(infer_constraints(t, a, neg_op(self.direction)))
res.extend(
infer_constraints(template.ret_type, cactual.ret_type, self.direction)
)
return res
elif isinstance(self.actual, AnyType):
# FIX what if generic
res = self.infer_against_any(template.arg_types, self.actual)
any_type = AnyType(TypeOfAny.from_another_any, source_any=self.actual)
res.extend(infer_constraints(template.ret_type, any_type, self.direction))
return res
elif isinstance(self.actual, Overloaded):
return self.infer_against_overloaded(self.actual, template)
elif isinstance(self.actual, TypeType):
return infer_constraints(template.ret_type, self.actual.item, self.direction)
elif isinstance(self.actual, Instance):
# Instances with __call__ method defined are considered structural
# subtypes of Callable with a compatible signature.
call = mypy.subtypes.find_member("__call__", self.actual, self.actual)
if call:
return infer_constraints(template, call, self.direction)
else:
return []
else:
return []
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def unpack_callback_protocol(t: Instance) -> Optional[Type]:
assert t.type.is_protocol
if t.type.protocol_members == ["__call__"]:
return find_member("__call__", t, t, is_operator=True)
return None
|
def unpack_callback_protocol(t: Instance) -> Optional[Type]:
assert t.type.is_protocol
if t.type.protocol_members == ["__call__"]:
return find_member("__call__", t, t)
return None
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def incompatible_argument_note(
self,
original_caller_type: ProperType,
callee_type: ProperType,
context: Context,
code: Optional[ErrorCode],
) -> None:
if (
isinstance(original_caller_type, (Instance, TupleType, TypedDictType))
and isinstance(callee_type, Instance)
and callee_type.type.is_protocol
):
self.report_protocol_problems(
original_caller_type, callee_type, context, code=code
)
if isinstance(callee_type, CallableType) and isinstance(
original_caller_type, Instance
):
call = find_member(
"__call__", original_caller_type, original_caller_type, is_operator=True
)
if call:
self.note_call(original_caller_type, call, context, code=code)
|
def incompatible_argument_note(
self,
original_caller_type: ProperType,
callee_type: ProperType,
context: Context,
code: Optional[ErrorCode],
) -> None:
if (
isinstance(original_caller_type, (Instance, TupleType, TypedDictType))
and isinstance(callee_type, Instance)
and callee_type.type.is_protocol
):
self.report_protocol_problems(
original_caller_type, callee_type, context, code=code
)
if isinstance(callee_type, CallableType) and isinstance(
original_caller_type, Instance
):
call = find_member("__call__", original_caller_type, original_caller_type)
if call:
self.note_call(original_caller_type, call, context, code=code)
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def visit_instance(self, left: Instance) -> bool:
if left.type.fallback_to_any:
if isinstance(self.right, NoneType):
# NOTE: `None` is a *non-subclassable* singleton, therefore no class
# can by a subtype of it, even with an `Any` fallback.
# This special case is needed to treat descriptors in classes with
# dynamic base classes correctly, see #5456.
return False
return True
right = self.right
if isinstance(right, TupleType) and mypy.typeops.tuple_fallback(right).type.is_enum:
return self._is_subtype(left, mypy.typeops.tuple_fallback(right))
if isinstance(right, Instance):
if TypeState.is_cached_subtype_check(self._subtype_kind, left, right):
return True
if not self.ignore_promotions:
for base in left.type.mro:
if base._promote and self._is_subtype(base._promote, self.right):
TypeState.record_subtype_cache_entry(
self._subtype_kind, left, right
)
return True
rname = right.type.fullname()
# Always try a nominal check if possible,
# there might be errors that a user wants to silence *once*.
if (
left.type.has_base(rname) or rname == "builtins.object"
) and not self.ignore_declared_variance:
# Map left type to corresponding right instances.
t = map_instance_to_supertype(left, right.type)
nominal = all(
self.check_type_parameter(lefta, righta, tvar.variance)
for lefta, righta, tvar in zip(
t.args, right.args, right.type.defn.type_vars
)
)
if nominal:
TypeState.record_subtype_cache_entry(self._subtype_kind, left, right)
return nominal
if right.type.is_protocol and is_protocol_implementation(left, right):
return True
return False
if isinstance(right, TypeType):
item = right.item
if isinstance(item, TupleType):
item = mypy.typeops.tuple_fallback(item)
if is_named_instance(left, "builtins.type"):
return self._is_subtype(TypeType(AnyType(TypeOfAny.special_form)), right)
if left.type.is_metaclass():
if isinstance(item, AnyType):
return True
if isinstance(item, Instance):
return is_named_instance(item, "builtins.object")
if isinstance(right, CallableType):
# Special case: Instance can be a subtype of Callable.
call = find_member("__call__", left, left, is_operator=True)
if call:
return self._is_subtype(call, right)
return False
else:
return False
|
def visit_instance(self, left: Instance) -> bool:
if left.type.fallback_to_any:
if isinstance(self.right, NoneType):
# NOTE: `None` is a *non-subclassable* singleton, therefore no class
# can by a subtype of it, even with an `Any` fallback.
# This special case is needed to treat descriptors in classes with
# dynamic base classes correctly, see #5456.
return False
return True
right = self.right
if isinstance(right, TupleType) and mypy.typeops.tuple_fallback(right).type.is_enum:
return self._is_subtype(left, mypy.typeops.tuple_fallback(right))
if isinstance(right, Instance):
if TypeState.is_cached_subtype_check(self._subtype_kind, left, right):
return True
if not self.ignore_promotions:
for base in left.type.mro:
if base._promote and self._is_subtype(base._promote, self.right):
TypeState.record_subtype_cache_entry(
self._subtype_kind, left, right
)
return True
rname = right.type.fullname()
# Always try a nominal check if possible,
# there might be errors that a user wants to silence *once*.
if (
left.type.has_base(rname) or rname == "builtins.object"
) and not self.ignore_declared_variance:
# Map left type to corresponding right instances.
t = map_instance_to_supertype(left, right.type)
nominal = all(
self.check_type_parameter(lefta, righta, tvar.variance)
for lefta, righta, tvar in zip(
t.args, right.args, right.type.defn.type_vars
)
)
if nominal:
TypeState.record_subtype_cache_entry(self._subtype_kind, left, right)
return nominal
if right.type.is_protocol and is_protocol_implementation(left, right):
return True
return False
if isinstance(right, TypeType):
item = right.item
if isinstance(item, TupleType):
item = mypy.typeops.tuple_fallback(item)
if is_named_instance(left, "builtins.type"):
return self._is_subtype(TypeType(AnyType(TypeOfAny.special_form)), right)
if left.type.is_metaclass():
if isinstance(item, AnyType):
return True
if isinstance(item, Instance):
return is_named_instance(item, "builtins.object")
if isinstance(right, CallableType):
# Special case: Instance can be a subtype of Callable.
call = find_member("__call__", left, left)
if call:
return self._is_subtype(call, right)
return False
else:
return False
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def visit_callable_type(self, left: CallableType) -> bool:
right = self.right
if isinstance(right, CallableType):
return is_callable_compatible(
left,
right,
is_compat=self._is_subtype,
ignore_pos_arg_names=self.ignore_pos_arg_names,
)
elif isinstance(right, Overloaded):
return all(self._is_subtype(left, item) for item in right.items())
elif isinstance(right, Instance):
if right.type.is_protocol and right.type.protocol_members == ["__call__"]:
# OK, a callable can implement a protocol with a single `__call__` member.
# TODO: we should probably explicitly exclude self-types in this case.
call = find_member("__call__", right, left, is_operator=True)
assert call is not None
if self._is_subtype(left, call):
return True
return self._is_subtype(left.fallback, right)
elif isinstance(right, TypeType):
# This is unsound, we don't check the __init__ signature.
return left.is_type_obj() and self._is_subtype(left.ret_type, right.item)
else:
return False
|
def visit_callable_type(self, left: CallableType) -> bool:
right = self.right
if isinstance(right, CallableType):
return is_callable_compatible(
left,
right,
is_compat=self._is_subtype,
ignore_pos_arg_names=self.ignore_pos_arg_names,
)
elif isinstance(right, Overloaded):
return all(self._is_subtype(left, item) for item in right.items())
elif isinstance(right, Instance):
if right.type.is_protocol and right.type.protocol_members == ["__call__"]:
# OK, a callable can implement a protocol with a single `__call__` member.
# TODO: we should probably explicitly exclude self-types in this case.
call = find_member("__call__", right, left)
assert call is not None
if self._is_subtype(left, call):
return True
return self._is_subtype(left.fallback, right)
elif isinstance(right, TypeType):
# This is unsound, we don't check the __init__ signature.
return left.is_type_obj() and self._is_subtype(left.ret_type, right.item)
else:
return False
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def visit_overloaded(self, left: Overloaded) -> bool:
right = self.right
if isinstance(right, Instance):
if right.type.is_protocol and right.type.protocol_members == ["__call__"]:
# same as for CallableType
call = find_member("__call__", right, left, is_operator=True)
assert call is not None
if self._is_subtype(left, call):
return True
return self._is_subtype(left.fallback, right)
elif isinstance(right, CallableType):
for item in left.items():
if self._is_subtype(item, right):
return True
return False
elif isinstance(right, Overloaded):
# Ensure each overload in the right side (the supertype) is accounted for.
previous_match_left_index = -1
matched_overloads = set()
possible_invalid_overloads = set()
for right_index, right_item in enumerate(right.items()):
found_match = False
for left_index, left_item in enumerate(left.items()):
subtype_match = self._is_subtype(left_item, right_item)
# Order matters: we need to make sure that the index of
# this item is at least the index of the previous one.
if subtype_match and previous_match_left_index <= left_index:
if not found_match:
# Update the index of the previous match.
previous_match_left_index = left_index
found_match = True
matched_overloads.add(left_item)
possible_invalid_overloads.discard(left_item)
else:
# If this one overlaps with the supertype in any way, but it wasn't
# an exact match, then it's a potential error.
if is_callable_compatible(
left_item,
right_item,
is_compat=self._is_subtype,
ignore_return=True,
ignore_pos_arg_names=self.ignore_pos_arg_names,
) or is_callable_compatible(
right_item,
left_item,
is_compat=self._is_subtype,
ignore_return=True,
ignore_pos_arg_names=self.ignore_pos_arg_names,
):
# If this is an overload that's already been matched, there's no
# problem.
if left_item not in matched_overloads:
possible_invalid_overloads.add(left_item)
if not found_match:
return False
if possible_invalid_overloads:
# There were potentially invalid overloads that were never matched to the
# supertype.
return False
return True
elif isinstance(right, UnboundType):
return True
elif isinstance(right, TypeType):
# All the items must have the same type object status, so
# it's sufficient to query only (any) one of them.
# This is unsound, we don't check all the __init__ signatures.
return left.is_type_obj() and self._is_subtype(left.items()[0], right)
else:
return False
|
def visit_overloaded(self, left: Overloaded) -> bool:
right = self.right
if isinstance(right, Instance):
if right.type.is_protocol and right.type.protocol_members == ["__call__"]:
# same as for CallableType
call = find_member("__call__", right, left)
assert call is not None
if self._is_subtype(left, call):
return True
return self._is_subtype(left.fallback, right)
elif isinstance(right, CallableType):
for item in left.items():
if self._is_subtype(item, right):
return True
return False
elif isinstance(right, Overloaded):
# Ensure each overload in the right side (the supertype) is accounted for.
previous_match_left_index = -1
matched_overloads = set()
possible_invalid_overloads = set()
for right_index, right_item in enumerate(right.items()):
found_match = False
for left_index, left_item in enumerate(left.items()):
subtype_match = self._is_subtype(left_item, right_item)
# Order matters: we need to make sure that the index of
# this item is at least the index of the previous one.
if subtype_match and previous_match_left_index <= left_index:
if not found_match:
# Update the index of the previous match.
previous_match_left_index = left_index
found_match = True
matched_overloads.add(left_item)
possible_invalid_overloads.discard(left_item)
else:
# If this one overlaps with the supertype in any way, but it wasn't
# an exact match, then it's a potential error.
if is_callable_compatible(
left_item,
right_item,
is_compat=self._is_subtype,
ignore_return=True,
ignore_pos_arg_names=self.ignore_pos_arg_names,
) or is_callable_compatible(
right_item,
left_item,
is_compat=self._is_subtype,
ignore_return=True,
ignore_pos_arg_names=self.ignore_pos_arg_names,
):
# If this is an overload that's already been matched, there's no
# problem.
if left_item not in matched_overloads:
possible_invalid_overloads.add(left_item)
if not found_match:
return False
if possible_invalid_overloads:
# There were potentially invalid overloads that were never matched to the
# supertype.
return False
return True
elif isinstance(right, UnboundType):
return True
elif isinstance(right, TypeType):
# All the items must have the same type object status, so
# it's sufficient to query only (any) one of them.
# This is unsound, we don't check all the __init__ signatures.
return left.is_type_obj() and self._is_subtype(left.items()[0], right)
else:
return False
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def find_member(
name: str, itype: Instance, subtype: Type, is_operator: bool = False
) -> Optional[Type]:
"""Find the type of member by 'name' in 'itype's TypeInfo.
Fin the member type after applying type arguments from 'itype', and binding
'self' to 'subtype'. Return None if member was not found.
"""
# TODO: this code shares some logic with checkmember.analyze_member_access,
# consider refactoring.
info = itype.type
method = info.get_method(name)
if method:
if method.is_property:
assert isinstance(method, OverloadedFuncDef)
dec = method.items[0]
assert isinstance(dec, Decorator)
return find_node_type(dec.var, itype, subtype)
return find_node_type(method, itype, subtype)
else:
# don't have such method, maybe variable or decorator?
node = info.get(name)
if not node:
v = None
else:
v = node.node
if isinstance(v, Decorator):
v = v.var
if isinstance(v, Var):
return find_node_type(v, itype, subtype)
if (
not v
and name not in ["__getattr__", "__setattr__", "__getattribute__"]
and not is_operator
):
for method_name in ("__getattribute__", "__getattr__"):
# Normally, mypy assumes that instances that define __getattr__ have all
# attributes with the corresponding return type. If this will produce
# many false negatives, then this could be prohibited for
# structural subtyping.
method = info.get_method(method_name)
if method and method.info.fullname() != "builtins.object":
getattr_type = get_proper_type(
find_node_type(method, itype, subtype)
)
if isinstance(getattr_type, CallableType):
return getattr_type.ret_type
if itype.type.fallback_to_any:
return AnyType(TypeOfAny.special_form)
return None
|
def find_member(name: str, itype: Instance, subtype: Type) -> Optional[Type]:
"""Find the type of member by 'name' in 'itype's TypeInfo.
Fin the member type after applying type arguments from 'itype', and binding
'self' to 'subtype'. Return None if member was not found.
"""
# TODO: this code shares some logic with checkmember.analyze_member_access,
# consider refactoring.
info = itype.type
method = info.get_method(name)
if method:
if method.is_property:
assert isinstance(method, OverloadedFuncDef)
dec = method.items[0]
assert isinstance(dec, Decorator)
return find_node_type(dec.var, itype, subtype)
return find_node_type(method, itype, subtype)
else:
# don't have such method, maybe variable or decorator?
node = info.get(name)
if not node:
v = None
else:
v = node.node
if isinstance(v, Decorator):
v = v.var
if isinstance(v, Var):
return find_node_type(v, itype, subtype)
if not v and name not in ["__getattr__", "__setattr__", "__getattribute__"]:
for method_name in ("__getattribute__", "__getattr__"):
# Normally, mypy assumes that instances that define __getattr__ have all
# attributes with the corresponding return type. If this will produce
# many false negatives, then this could be prohibited for
# structural subtyping.
method = info.get_method(method_name)
if method and method.info.fullname() != "builtins.object":
getattr_type = get_proper_type(
find_node_type(method, itype, subtype)
)
if isinstance(getattr_type, CallableType):
return getattr_type.ret_type
if itype.type.fallback_to_any:
return AnyType(TypeOfAny.special_form)
return None
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def visit_instance(self, left: Instance) -> bool:
right = self.right
if isinstance(right, Instance):
if TypeState.is_cached_subtype_check(self._subtype_kind, left, right):
return True
if not self.ignore_promotions:
for base in left.type.mro:
if base._promote and self._is_proper_subtype(base._promote, right):
TypeState.record_subtype_cache_entry(
self._subtype_kind, left, right
)
return True
if left.type.has_base(right.type.fullname()):
def check_argument(leftarg: Type, rightarg: Type, variance: int) -> bool:
if variance == COVARIANT:
return self._is_proper_subtype(leftarg, rightarg)
elif variance == CONTRAVARIANT:
return self._is_proper_subtype(rightarg, leftarg)
else:
return mypy.sametypes.is_same_type(leftarg, rightarg)
# Map left type to corresponding right instances.
left = map_instance_to_supertype(left, right.type)
if self.erase_instances:
erased = erase_type(left)
assert isinstance(erased, Instance)
left = erased
nominal = all(
check_argument(ta, ra, tvar.variance)
for ta, ra, tvar in zip(
left.args, right.args, right.type.defn.type_vars
)
)
if nominal:
TypeState.record_subtype_cache_entry(self._subtype_kind, left, right)
return nominal
if right.type.is_protocol and is_protocol_implementation(
left, right, proper_subtype=True
):
return True
return False
if isinstance(right, CallableType):
call = find_member("__call__", left, left, is_operator=True)
if call:
return self._is_proper_subtype(call, right)
return False
return False
|
def visit_instance(self, left: Instance) -> bool:
right = self.right
if isinstance(right, Instance):
if TypeState.is_cached_subtype_check(self._subtype_kind, left, right):
return True
if not self.ignore_promotions:
for base in left.type.mro:
if base._promote and self._is_proper_subtype(base._promote, right):
TypeState.record_subtype_cache_entry(
self._subtype_kind, left, right
)
return True
if left.type.has_base(right.type.fullname()):
def check_argument(leftarg: Type, rightarg: Type, variance: int) -> bool:
if variance == COVARIANT:
return self._is_proper_subtype(leftarg, rightarg)
elif variance == CONTRAVARIANT:
return self._is_proper_subtype(rightarg, leftarg)
else:
return mypy.sametypes.is_same_type(leftarg, rightarg)
# Map left type to corresponding right instances.
left = map_instance_to_supertype(left, right.type)
if self.erase_instances:
erased = erase_type(left)
assert isinstance(erased, Instance)
left = erased
nominal = all(
check_argument(ta, ra, tvar.variance)
for ta, ra, tvar in zip(
left.args, right.args, right.type.defn.type_vars
)
)
if nominal:
TypeState.record_subtype_cache_entry(self._subtype_kind, left, right)
return nominal
if right.type.is_protocol and is_protocol_implementation(
left, right, proper_subtype=True
):
return True
return False
if isinstance(right, CallableType):
call = find_member("__call__", left, left)
if call:
return self._is_proper_subtype(call, right)
return False
return False
|
https://github.com/python/mypy/issues/7243
|
Traceback (most recent call last):
File "/home/zero323/anaconda3/bin/mypy", line 10, in <module>
sys.exit(console_entry())
...
RecursionError: maximum recursion depth exceeded while calling a Python object
foo.pyi:6: : note: use --pdb to drop into pdb
|
RecursionError
|
def transform(self) -> None:
"""Apply all the necessary transformations to the underlying
dataclass so as to ensure it is fully type checked according
to the rules in PEP 557.
"""
ctx = self._ctx
info = self._ctx.cls.info
attributes = self.collect_attributes()
if attributes is None:
# Some definitions are not ready, defer() should be already called.
return
for attr in attributes:
node = info.get(attr.name)
if node is None:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var and not attr.is_in_init
continue
if node.type is None:
ctx.api.defer()
return
decorator_arguments = {
"init": _get_decorator_bool_argument(self._ctx, "init", True),
"eq": _get_decorator_bool_argument(self._ctx, "eq", True),
"order": _get_decorator_bool_argument(self._ctx, "order", False),
"frozen": _get_decorator_bool_argument(self._ctx, "frozen", False),
}
# If there are no attributes, it may be that the new semantic analyzer has not
# processed them yet. In order to work around this, we can simply skip generating
# __init__ if there are no attributes, because if the user truly did not define any,
# then the object default __init__ with an empty signature will be present anyway.
if (
decorator_arguments["init"]
and ("__init__" not in info.names or info.names["__init__"].plugin_generated)
and attributes
):
add_method(
ctx,
"__init__",
args=[attr.to_argument(info) for attr in attributes if attr.is_in_init],
return_type=NoneType(),
)
if (
decorator_arguments["eq"]
and info.get("__eq__") is None
or decorator_arguments["order"]
):
# Type variable for self types in generated methods.
obj_type = ctx.api.named_type("__builtins__.object")
self_tvar_expr = TypeVarExpr(
SELF_TVAR_NAME, info.fullname() + "." + SELF_TVAR_NAME, [], obj_type
)
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
# Add an eq method, but only if the class doesn't already have one.
if decorator_arguments["eq"] and info.get("__eq__") is None:
for method_name in ["__eq__", "__ne__"]:
# The TVar is used to enforce that "other" must have
# the same type as self (covariant). Note the
# "self_type" parameter to add_method.
obj_type = ctx.api.named_type("__builtins__.object")
cmp_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname() + "." + SELF_TVAR_NAME, -1, [], obj_type
)
cmp_other_type = TypeVarType(cmp_tvar_def)
cmp_return_type = ctx.api.named_type("__builtins__.bool")
add_method(
ctx,
method_name,
args=[
Argument(
Var("other", cmp_other_type), cmp_other_type, None, ARG_POS
)
],
return_type=cmp_return_type,
self_type=cmp_other_type,
tvar_def=cmp_tvar_def,
)
# Add <, >, <=, >=, but only if the class has an eq method.
if decorator_arguments["order"]:
if not decorator_arguments["eq"]:
ctx.api.fail("eq must be True if order is True", ctx.cls)
for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
# Like for __eq__ and __ne__, we want "other" to match
# the self type.
obj_type = ctx.api.named_type("__builtins__.object")
order_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname() + "." + SELF_TVAR_NAME, -1, [], obj_type
)
order_other_type = TypeVarType(order_tvar_def)
order_return_type = ctx.api.named_type("__builtins__.bool")
order_args = [
Argument(
Var("other", order_other_type), order_other_type, None, ARG_POS
)
]
existing_method = info.get(method_name)
if existing_method is not None and not existing_method.plugin_generated:
assert existing_method.node
ctx.api.fail(
"You may not have a custom %s method when order=True" % method_name,
existing_method.node,
)
add_method(
ctx,
method_name,
args=order_args,
return_type=order_return_type,
self_type=order_other_type,
tvar_def=order_tvar_def,
)
if decorator_arguments["frozen"]:
self._freeze(attributes)
self.reset_init_only_vars(info, attributes)
info.metadata["dataclass"] = {
"attributes": OrderedDict((attr.name, attr.serialize()) for attr in attributes),
"frozen": decorator_arguments["frozen"],
}
|
def transform(self) -> None:
"""Apply all the necessary transformations to the underlying
dataclass so as to ensure it is fully type checked according
to the rules in PEP 557.
"""
ctx = self._ctx
info = self._ctx.cls.info
attributes = self.collect_attributes()
if attributes is None:
# Some definitions are not ready, defer() should be already called.
return
for attr in attributes:
if info[attr.name].type is None:
ctx.api.defer()
return
decorator_arguments = {
"init": _get_decorator_bool_argument(self._ctx, "init", True),
"eq": _get_decorator_bool_argument(self._ctx, "eq", True),
"order": _get_decorator_bool_argument(self._ctx, "order", False),
"frozen": _get_decorator_bool_argument(self._ctx, "frozen", False),
}
# If there are no attributes, it may be that the new semantic analyzer has not
# processed them yet. In order to work around this, we can simply skip generating
# __init__ if there are no attributes, because if the user truly did not define any,
# then the object default __init__ with an empty signature will be present anyway.
if (
decorator_arguments["init"]
and ("__init__" not in info.names or info.names["__init__"].plugin_generated)
and attributes
):
add_method(
ctx,
"__init__",
args=[attr.to_argument(info) for attr in attributes if attr.is_in_init],
return_type=NoneType(),
)
if (
decorator_arguments["eq"]
and info.get("__eq__") is None
or decorator_arguments["order"]
):
# Type variable for self types in generated methods.
obj_type = ctx.api.named_type("__builtins__.object")
self_tvar_expr = TypeVarExpr(
SELF_TVAR_NAME, info.fullname() + "." + SELF_TVAR_NAME, [], obj_type
)
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
# Add an eq method, but only if the class doesn't already have one.
if decorator_arguments["eq"] and info.get("__eq__") is None:
for method_name in ["__eq__", "__ne__"]:
# The TVar is used to enforce that "other" must have
# the same type as self (covariant). Note the
# "self_type" parameter to add_method.
obj_type = ctx.api.named_type("__builtins__.object")
cmp_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname() + "." + SELF_TVAR_NAME, -1, [], obj_type
)
cmp_other_type = TypeVarType(cmp_tvar_def)
cmp_return_type = ctx.api.named_type("__builtins__.bool")
add_method(
ctx,
method_name,
args=[
Argument(
Var("other", cmp_other_type), cmp_other_type, None, ARG_POS
)
],
return_type=cmp_return_type,
self_type=cmp_other_type,
tvar_def=cmp_tvar_def,
)
# Add <, >, <=, >=, but only if the class has an eq method.
if decorator_arguments["order"]:
if not decorator_arguments["eq"]:
ctx.api.fail("eq must be True if order is True", ctx.cls)
for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
# Like for __eq__ and __ne__, we want "other" to match
# the self type.
obj_type = ctx.api.named_type("__builtins__.object")
order_tvar_def = TypeVarDef(
SELF_TVAR_NAME, info.fullname() + "." + SELF_TVAR_NAME, -1, [], obj_type
)
order_other_type = TypeVarType(order_tvar_def)
order_return_type = ctx.api.named_type("__builtins__.bool")
order_args = [
Argument(
Var("other", order_other_type), order_other_type, None, ARG_POS
)
]
existing_method = info.get(method_name)
if existing_method is not None and not existing_method.plugin_generated:
assert existing_method.node
ctx.api.fail(
"You may not have a custom %s method when order=True" % method_name,
existing_method.node,
)
add_method(
ctx,
method_name,
args=order_args,
return_type=order_return_type,
self_type=order_other_type,
tvar_def=order_tvar_def,
)
if decorator_arguments["frozen"]:
self._freeze(attributes)
self.reset_init_only_vars(info, attributes)
info.metadata["dataclass"] = {
"attributes": OrderedDict((attr.name, attr.serialize()) for attr in attributes),
"frozen": decorator_arguments["frozen"],
}
|
https://github.com/python/mypy/issues/7320
|
$ ~/src/mypy/venv/bin/mypy test.py --show-traceback
test.py:10: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.730+dev.c610a312853921d09083f7525c183810e4232056
Traceback (most recent call last):
File "/home/josh/src/mypy/venv/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 162, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 2559, in dispatch
process_graph(graph, manager)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 2868, in process_graph
process_stale_scc(graph, scc, manager)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 2961, in process_stale_scc
semantic_analysis_for_scc(graph, scc, manager.errors)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal_main.py", line 77, in semantic_analysis_for_scc
process_top_levels(graph, scc, patches)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal_main.py", line 202, in process_top_levels
patches)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal_main.py", line 330, in semantic_analyze_target
active_type=active_type)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 376, in refresh_partial
self.refresh_top_level(node)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 387, in refresh_top_level
self.accept(d)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 4591, in accept
node.accept(self)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/nodes.py", line 925, in accept
return visitor.visit_class_def(self)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1011, in visit_class_def
self.analyze_class(defn)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1082, in analyze_class
self.analyze_class_body_common(defn)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1091, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1136, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 352, in dataclass_class_maker_callback
transformer.transform()
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 84, in transform
if info[attr.name].type is None:
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/nodes.py", line 2428, in __getitem__
raise KeyError(name)
KeyError: '_dummy'
test.py:10: : note: use --pdb to drop into pdb
|
KeyError
|
def reset_init_only_vars(
self, info: TypeInfo, attributes: List[DataclassAttribute]
) -> None:
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
if attr.is_init_var:
if attr.name in info.names:
del info.names[attr.name]
else:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var and not attr.is_in_init
for stmt in info.defn.defs.body:
if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
lvalue = stmt.lvalues[0]
if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
# Reset node so that another semantic analysis pass will
# recreate a symbol node for this attribute.
lvalue.node = None
|
def reset_init_only_vars(
self, info: TypeInfo, attributes: List[DataclassAttribute]
) -> None:
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
if attr.is_init_var:
del info.names[attr.name]
for stmt in info.defn.defs.body:
if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
lvalue = stmt.lvalues[0]
if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
# Reset node so that another semantic analysis pass will
# recreate a symbol node for this attribute.
lvalue.node = None
|
https://github.com/python/mypy/issues/7320
|
$ ~/src/mypy/venv/bin/mypy test.py --show-traceback
test.py:10: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.730+dev.c610a312853921d09083f7525c183810e4232056
Traceback (most recent call last):
File "/home/josh/src/mypy/venv/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 162, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 2559, in dispatch
process_graph(graph, manager)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 2868, in process_graph
process_stale_scc(graph, scc, manager)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/build.py", line 2961, in process_stale_scc
semantic_analysis_for_scc(graph, scc, manager.errors)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal_main.py", line 77, in semantic_analysis_for_scc
process_top_levels(graph, scc, patches)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal_main.py", line 202, in process_top_levels
patches)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal_main.py", line 330, in semantic_analyze_target
active_type=active_type)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 376, in refresh_partial
self.refresh_top_level(node)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 387, in refresh_top_level
self.accept(d)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 4591, in accept
node.accept(self)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/nodes.py", line 925, in accept
return visitor.visit_class_def(self)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1011, in visit_class_def
self.analyze_class(defn)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1082, in analyze_class
self.analyze_class_body_common(defn)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1091, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/semanal.py", line 1136, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 352, in dataclass_class_maker_callback
transformer.transform()
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/plugins/dataclasses.py", line 84, in transform
if info[attr.name].type is None:
File "/home/josh/src/mypy/venv/lib/python3.7/site-packages/mypy/nodes.py", line 2428, in __getitem__
raise KeyError(name)
KeyError: '_dummy'
test.py:10: : note: use --pdb to drop into pdb
|
KeyError
|
def check_mapping_str_interpolation(
self,
specifiers: List[ConversionSpecifier],
replacements: Expression,
expr: FormatStringExpr,
) -> None:
if isinstance(replacements, DictExpr) and all(
isinstance(k, (StrExpr, BytesExpr, UnicodeExpr)) for k, v in replacements.items
):
mapping = {} # type: Dict[str, Type]
for k, v in replacements.items:
key_str = cast(FormatStringExpr, k).value
mapping[key_str] = self.accept(v)
for specifier in specifiers:
if specifier.type == "%":
# %% is allowed in mappings, no checking is required
continue
assert specifier.key is not None
if specifier.key not in mapping:
self.msg.key_not_in_mapping(specifier.key, replacements)
return
rep_type = mapping[specifier.key]
expected_type = self.conversion_type(specifier.type, replacements, expr)
if expected_type is None:
return
self.chk.check_subtype(
rep_type,
expected_type,
replacements,
message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,
"expression has type",
"placeholder with key '%s' has type" % specifier.key,
)
else:
rep_type = self.accept(replacements)
any_type = AnyType(TypeOfAny.special_form)
dict_type = self.chk.named_generic_type("builtins.dict", [any_type, any_type])
self.chk.check_subtype(
rep_type,
dict_type,
replacements,
message_registry.FORMAT_REQUIRES_MAPPING,
"expression has type",
"expected type for mapping is",
)
|
def check_mapping_str_interpolation(
self,
specifiers: List[ConversionSpecifier],
replacements: Expression,
expr: FormatStringExpr,
) -> None:
if isinstance(replacements, DictExpr) and all(
isinstance(k, (StrExpr, BytesExpr)) for k, v in replacements.items
):
mapping = {} # type: Dict[str, Type]
for k, v in replacements.items:
key_str = cast(StrExpr, k).value
mapping[key_str] = self.accept(v)
for specifier in specifiers:
if specifier.type == "%":
# %% is allowed in mappings, no checking is required
continue
assert specifier.key is not None
if specifier.key not in mapping:
self.msg.key_not_in_mapping(specifier.key, replacements)
return
rep_type = mapping[specifier.key]
expected_type = self.conversion_type(specifier.type, replacements, expr)
if expected_type is None:
return
self.chk.check_subtype(
rep_type,
expected_type,
replacements,
message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,
"expression has type",
"placeholder with key '%s' has type" % specifier.key,
)
else:
rep_type = self.accept(replacements)
any_type = AnyType(TypeOfAny.special_form)
dict_type = self.chk.named_generic_type("builtins.dict", [any_type, any_type])
self.chk.check_subtype(
rep_type,
dict_type,
replacements,
message_registry.FORMAT_REQUIRES_MAPPING,
"expression has type",
"expected type for mapping is",
)
|
https://github.com/python/mypy/issues/7293
|
$ cat example.py
print(b'%(x)s' % {b'x': b'data'})
$ python3 example.py
b'data'
$ mypy example.py --show-traceback
mypy example.py --show-traceback
example.py:1: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.720
Traceback (most recent call last):
File "mypy/checkexpr.py", line 3404, in accept
File "mypy/nodes.py", line 1708, in accept
File "mypy/checkexpr.py", line 1891, in visit_op_expr__ExpressionVisitor_glue
File "mypy/checkexpr.py", line 1906, in visit_op_expr
File "mypy/checkstrformat.py", line 97, in check_str_interpolation
File "mypy/checkstrformat.py", line 178, in check_mapping_str_interpolation
TypeError: StrExpr object expected
example.py:1: : note: use --pdb to drop into pdb
|
TypeError
|
def check_func_def(
self, defn: FuncItem, typ: CallableType, name: Optional[str]
) -> None:
"""Type check a function definition."""
# Expand type variables with value restrictions to ordinary types.
expanded = self.expand_typevars(defn, typ)
for item, typ in expanded:
old_binder = self.binder
self.binder = ConditionalTypeBinder()
with self.binder.top_frame_context():
defn.expanded.append(item)
# We may be checking a function definition or an anonymous
# function. In the first case, set up another reference with the
# precise type.
if isinstance(item, FuncDef):
fdef = item
# Check if __init__ has an invalid, non-None return type.
if (
fdef.info
and fdef.name() in ("__init__", "__init_subclass__")
and not isinstance(typ.ret_type, NoneType)
and not self.dynamic_funcs[-1]
):
self.fail(
message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name()),
item,
)
# Check validity of __new__ signature
if fdef.info and fdef.name() == "__new__":
self.check___new___signature(fdef, typ)
self.check_for_missing_annotations(fdef)
if self.options.disallow_any_unimported:
if fdef.type and isinstance(fdef.type, CallableType):
ret_type = fdef.type.ret_type
if has_any_from_unimported_type(ret_type):
self.msg.unimported_type_becomes_any(
"Return type", ret_type, fdef
)
for idx, arg_type in enumerate(fdef.type.arg_types):
if has_any_from_unimported_type(arg_type):
prefix = 'Argument {} to "{}"'.format(
idx + 1, fdef.name()
)
self.msg.unimported_type_becomes_any(
prefix, arg_type, fdef
)
check_for_explicit_any(
fdef.type,
self.options,
self.is_typeshed_stub,
self.msg,
context=fdef,
)
if name: # Special method names
if defn.info and self.is_reverse_op_method(name):
self.check_reverse_op_method(item, typ, name, defn)
elif name in ("__getattr__", "__getattribute__"):
self.check_getattr_method(typ, defn, name)
elif name == "__setattr__":
self.check_setattr_method(typ, defn)
# Refuse contravariant return type variable
if isinstance(typ.ret_type, TypeVarType):
if typ.ret_type.variance == CONTRAVARIANT:
self.fail(
message_registry.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT,
typ.ret_type,
)
# Check that Generator functions have the appropriate return type.
if defn.is_generator:
if defn.is_async_generator:
if not self.is_async_generator_return_type(typ.ret_type):
self.fail(
message_registry.INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR,
typ,
)
else:
if not self.is_generator_return_type(
typ.ret_type, defn.is_coroutine
):
self.fail(
message_registry.INVALID_RETURN_TYPE_FOR_GENERATOR, typ
)
# Python 2 generators aren't allowed to return values.
if (
self.options.python_version[0] == 2
and isinstance(typ.ret_type, Instance)
and typ.ret_type.type.fullname() == "typing.Generator"
):
if not isinstance(typ.ret_type.args[2], (NoneType, AnyType)):
self.fail(
message_registry.INVALID_GENERATOR_RETURN_ITEM_TYPE, typ
)
# Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`.
if defn.is_awaitable_coroutine:
# Update the return type to AwaitableGenerator.
# (This doesn't exist in typing.py, only in typing.pyi.)
t = typ.ret_type
c = defn.is_coroutine
ty = self.get_generator_yield_type(t, c)
tc = self.get_generator_receive_type(t, c)
if c:
tr = self.get_coroutine_return_type(t)
else:
tr = self.get_generator_return_type(t, c)
ret_type = self.named_generic_type(
"typing.AwaitableGenerator", [ty, tc, tr, t]
)
typ = typ.copy_modified(ret_type=ret_type)
defn.type = typ
# Push return type.
self.return_types.append(typ.ret_type)
# Store argument types.
for i in range(len(typ.arg_types)):
arg_type = typ.arg_types[i]
with self.scope.push_function(defn):
# We temporary push the definition to get the self type as
# visible from *inside* of this function/method.
ref_type = self.scope.active_self_type() # type: Optional[Type]
if (
isinstance(defn, FuncDef)
and ref_type is not None
and i == 0
and not defn.is_static
and typ.arg_kinds[0] not in [nodes.ARG_STAR, nodes.ARG_STAR2]
):
isclass = defn.is_class or defn.name() in (
"__new__",
"__init_subclass__",
)
if isclass:
ref_type = mypy.types.TypeType.make_normalized(ref_type)
erased = erase_to_bound(arg_type)
if not is_subtype_ignoring_tvars(ref_type, erased):
note = None
if typ.arg_names[i] in ["self", "cls"]:
if (
self.options.python_version[0] < 3
and is_same_type(erased, arg_type)
and not isclass
):
msg = message_registry.INVALID_SELF_TYPE_OR_EXTRA_ARG
note = "(Hint: typically annotations omit the type for self)"
else:
msg = message_registry.ERASED_SELF_TYPE_NOT_SUPERTYPE.format(
erased, ref_type
)
else:
msg = message_registry.MISSING_OR_INVALID_SELF_TYPE
self.fail(msg, defn)
if note:
self.note(note, defn)
elif isinstance(arg_type, TypeVarType):
# Refuse covariant parameter type variables
# TODO: check recursively for inner type variables
if arg_type.variance == COVARIANT and defn.name() not in (
"__init__",
"__new__",
):
ctx = arg_type # type: Context
if ctx.line < 0:
ctx = typ
self.fail(
message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx
)
if typ.arg_kinds[i] == nodes.ARG_STAR:
# builtins.tuple[T] is typing.Tuple[T, ...]
arg_type = self.named_generic_type("builtins.tuple", [arg_type])
elif typ.arg_kinds[i] == nodes.ARG_STAR2:
arg_type = self.named_generic_type(
"builtins.dict", [self.str_type(), arg_type]
)
item.arguments[i].variable.type = arg_type
# Type check initialization expressions.
body_is_trivial = self.is_trivial_body(defn.body)
for arg in item.arguments:
if arg.initializer is None:
continue
if body_is_trivial and isinstance(arg.initializer, EllipsisExpr):
continue
name = arg.variable.name()
msg = "Incompatible default for "
if name.startswith("__tuple_arg_"):
msg += "tuple argument {}".format(name[12:])
else:
msg += 'argument "{}"'.format(name)
self.check_simple_assignment(
arg.variable.type,
arg.initializer,
context=arg,
msg=msg,
lvalue_name="argument",
rvalue_name="default",
)
# Type check body in a new scope.
with self.binder.top_frame_context():
with self.scope.push_function(defn):
# We suppress reachability warnings when we use TypeVars with value
# restrictions: we only want to report a warning if a certain statement is
# marked as being suppressed in *all* of the expansions, but we currently
# have no good way of doing this.
#
# TODO: Find a way of working around this limitation
if len(expanded) >= 2:
self.binder.suppress_unreachable_warnings()
self.accept(item.body)
unreachable = self.binder.is_unreachable()
if self.options.warn_no_return and not unreachable:
if defn.is_generator or is_named_instance(
self.return_types[-1], "typing.AwaitableGenerator"
):
return_type = self.get_generator_return_type(
self.return_types[-1], defn.is_coroutine
)
elif defn.is_coroutine:
return_type = self.get_coroutine_return_type(self.return_types[-1])
else:
return_type = self.return_types[-1]
if not isinstance(return_type, (NoneType, AnyType)) and not body_is_trivial:
# Control flow fell off the end of a function that was
# declared to return a non-None type and is not
# entirely pass/Ellipsis/raise NotImplementedError.
if isinstance(return_type, UninhabitedType):
# This is a NoReturn function
self.msg.fail(message_registry.INVALID_IMPLICIT_RETURN, defn)
else:
self.msg.fail(message_registry.MISSING_RETURN_STATEMENT, defn)
self.return_types.pop()
self.binder = old_binder
|
def check_func_def(
self, defn: FuncItem, typ: CallableType, name: Optional[str]
) -> None:
"""Type check a function definition."""
# Expand type variables with value restrictions to ordinary types.
expanded = self.expand_typevars(defn, typ)
for item, typ in expanded:
old_binder = self.binder
self.binder = ConditionalTypeBinder()
with self.binder.top_frame_context():
defn.expanded.append(item)
# We may be checking a function definition or an anonymous
# function. In the first case, set up another reference with the
# precise type.
if isinstance(item, FuncDef):
fdef = item
# Check if __init__ has an invalid, non-None return type.
if (
fdef.info
and fdef.name() in ("__init__", "__init_subclass__")
and not isinstance(typ.ret_type, NoneType)
and not self.dynamic_funcs[-1]
):
self.fail(
message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name()),
item,
)
# Check validity of __new__ signature
if fdef.info and fdef.name() == "__new__":
self.check___new___signature(fdef, typ)
self.check_for_missing_annotations(fdef)
if self.options.disallow_any_unimported:
if fdef.type and isinstance(fdef.type, CallableType):
ret_type = fdef.type.ret_type
if has_any_from_unimported_type(ret_type):
self.msg.unimported_type_becomes_any(
"Return type", ret_type, fdef
)
for idx, arg_type in enumerate(fdef.type.arg_types):
if has_any_from_unimported_type(arg_type):
prefix = 'Argument {} to "{}"'.format(
idx + 1, fdef.name()
)
self.msg.unimported_type_becomes_any(
prefix, arg_type, fdef
)
check_for_explicit_any(
fdef.type,
self.options,
self.is_typeshed_stub,
self.msg,
context=fdef,
)
if name: # Special method names
if defn.info and self.is_reverse_op_method(name):
self.check_reverse_op_method(item, typ, name, defn)
elif name in ("__getattr__", "__getattribute__"):
self.check_getattr_method(typ, defn, name)
elif name == "__setattr__":
self.check_setattr_method(typ, defn)
# Refuse contravariant return type variable
if isinstance(typ.ret_type, TypeVarType):
if typ.ret_type.variance == CONTRAVARIANT:
self.fail(
message_registry.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT,
typ.ret_type,
)
# Check that Generator functions have the appropriate return type.
if defn.is_generator:
if defn.is_async_generator:
if not self.is_async_generator_return_type(typ.ret_type):
self.fail(
message_registry.INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR,
typ,
)
else:
if not self.is_generator_return_type(
typ.ret_type, defn.is_coroutine
):
self.fail(
message_registry.INVALID_RETURN_TYPE_FOR_GENERATOR, typ
)
# Python 2 generators aren't allowed to return values.
if (
self.options.python_version[0] == 2
and isinstance(typ.ret_type, Instance)
and typ.ret_type.type.fullname() == "typing.Generator"
):
if not isinstance(typ.ret_type.args[2], (NoneType, AnyType)):
self.fail(
message_registry.INVALID_GENERATOR_RETURN_ITEM_TYPE, typ
)
# Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`.
if defn.is_awaitable_coroutine:
# Update the return type to AwaitableGenerator.
# (This doesn't exist in typing.py, only in typing.pyi.)
t = typ.ret_type
c = defn.is_coroutine
ty = self.get_generator_yield_type(t, c)
tc = self.get_generator_receive_type(t, c)
if c:
tr = self.get_coroutine_return_type(t)
else:
tr = self.get_generator_return_type(t, c)
ret_type = self.named_generic_type(
"typing.AwaitableGenerator", [ty, tc, tr, t]
)
typ = typ.copy_modified(ret_type=ret_type)
defn.type = typ
# Push return type.
self.return_types.append(typ.ret_type)
# Store argument types.
for i in range(len(typ.arg_types)):
arg_type = typ.arg_types[i]
ref_type = self.scope.active_self_type() # type: Optional[Type]
if (
isinstance(defn, FuncDef)
and ref_type is not None
and i == 0
and not defn.is_static
and typ.arg_kinds[0] not in [nodes.ARG_STAR, nodes.ARG_STAR2]
):
isclass = defn.is_class or defn.name() in (
"__new__",
"__init_subclass__",
)
if isclass:
ref_type = mypy.types.TypeType.make_normalized(ref_type)
erased = erase_to_bound(arg_type)
if not is_subtype_ignoring_tvars(ref_type, erased):
note = None
if typ.arg_names[i] in ["self", "cls"]:
if (
self.options.python_version[0] < 3
and is_same_type(erased, arg_type)
and not isclass
):
msg = message_registry.INVALID_SELF_TYPE_OR_EXTRA_ARG
note = "(Hint: typically annotations omit the type for self)"
else:
msg = message_registry.ERASED_SELF_TYPE_NOT_SUPERTYPE.format(
erased, ref_type
)
else:
msg = message_registry.MISSING_OR_INVALID_SELF_TYPE
self.fail(msg, defn)
if note:
self.note(note, defn)
elif isinstance(arg_type, TypeVarType):
# Refuse covariant parameter type variables
# TODO: check recursively for inner type variables
if arg_type.variance == COVARIANT and defn.name() not in (
"__init__",
"__new__",
):
ctx = arg_type # type: Context
if ctx.line < 0:
ctx = typ
self.fail(
message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx
)
if typ.arg_kinds[i] == nodes.ARG_STAR:
# builtins.tuple[T] is typing.Tuple[T, ...]
arg_type = self.named_generic_type("builtins.tuple", [arg_type])
elif typ.arg_kinds[i] == nodes.ARG_STAR2:
arg_type = self.named_generic_type(
"builtins.dict", [self.str_type(), arg_type]
)
item.arguments[i].variable.type = arg_type
# Type check initialization expressions.
body_is_trivial = self.is_trivial_body(defn.body)
for arg in item.arguments:
if arg.initializer is None:
continue
if body_is_trivial and isinstance(arg.initializer, EllipsisExpr):
continue
name = arg.variable.name()
msg = "Incompatible default for "
if name.startswith("__tuple_arg_"):
msg += "tuple argument {}".format(name[12:])
else:
msg += 'argument "{}"'.format(name)
self.check_simple_assignment(
arg.variable.type,
arg.initializer,
context=arg,
msg=msg,
lvalue_name="argument",
rvalue_name="default",
)
# Type check body in a new scope.
with self.binder.top_frame_context():
with self.scope.push_function(defn):
# We suppress reachability warnings when we use TypeVars with value
# restrictions: we only want to report a warning if a certain statement is
# marked as being suppressed in *all* of the expansions, but we currently
# have no good way of doing this.
#
# TODO: Find a way of working around this limitation
if len(expanded) >= 2:
self.binder.suppress_unreachable_warnings()
self.accept(item.body)
unreachable = self.binder.is_unreachable()
if self.options.warn_no_return and not unreachable:
if defn.is_generator or is_named_instance(
self.return_types[-1], "typing.AwaitableGenerator"
):
return_type = self.get_generator_return_type(
self.return_types[-1], defn.is_coroutine
)
elif defn.is_coroutine:
return_type = self.get_coroutine_return_type(self.return_types[-1])
else:
return_type = self.return_types[-1]
if not isinstance(return_type, (NoneType, AnyType)) and not body_is_trivial:
# Control flow fell off the end of a function that was
# declared to return a non-None type and is not
# entirely pass/Ellipsis/raise NotImplementedError.
if isinstance(return_type, UninhabitedType):
# This is a NoReturn function
self.msg.fail(message_registry.INVALID_IMPLICIT_RETURN, defn)
else:
self.msg.fail(message_registry.MISSING_RETURN_STATEMENT, defn)
self.return_types.pop()
self.binder = old_binder
|
https://github.com/python/mypy/issues/5846
|
Traceback (most recent call last):
File "/home/derrick_chambers/anaconda3/bin/mypy", line 11, in <module>
sys.exit(console_entry())
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/main.py", line 91, in main
res = type_check_only(sources, bin_dir, options, flush_errors, fscache) # noqa
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/main.py", line 148, in type_check_only
fscache=fscache)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 183, in build
flush_errors, fscache)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 356, in _build
graph = dispatch(sources, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2543, in dispatch
process_graph(graph, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2840, in process_graph
process_stale_scc(graph, scc, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2963, in process_stale_scc
graph[id].type_check_first_pass()
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2103, in type_check_first_pass
self.type_checker().check_first_pass()
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 256, in check_first_pass
self.accept(d)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 820, in accept
return visitor.visit_class_def(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1461, in visit_class_def
self.accept(defn.defs)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 885, in accept
return visitor.visit_block(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1607, in visit_block
self.accept(s)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 603, in accept
return visitor.visit_func_def(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 666, in visit_func_def
self._visit_func_def(defn)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 670, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 732, in check_func_item
self.check_func_def(defn, typ, name)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 898, in check_func_def
self.accept(item.body)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 885, in accept
return visitor.visit_block(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1607, in visit_block
self.accept(s)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 933, in accept
return visitor.visit_assignment_stmt(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1614, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1663, in check_assignment
if self.check_compatibility_all_supers(lvalue, lvalue_type, rvalue):
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1755, in check_compatibility_all_supers
base_type, base_node = self.lvalue_type_from_base(lvalue_node, base)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1842, in lvalue_type_from_base
assert self_type is not None, "Internal error: base lookup outside class"
AssertionError: Internal error: base lookup outside class
breakmypy.py:14: : note: use --pdb to drop into pdb
|
AssertionError
|
def enclosing_class(self) -> Optional[TypeInfo]:
"""Is there a class *directly* enclosing this function?"""
top = self.top_function()
assert top, "This method must be called from inside a function"
index = self.stack.index(top)
assert index, "CheckerScope stack must always start with a module"
enclosing = self.stack[index - 1]
if isinstance(enclosing, TypeInfo):
return enclosing
return None
|
def enclosing_class(self) -> Optional[TypeInfo]:
top = self.top_function()
assert top, "This method must be called from inside a function"
index = self.stack.index(top)
assert index, "CheckerScope stack must always start with a module"
enclosing = self.stack[index - 1]
if isinstance(enclosing, TypeInfo):
return enclosing
return None
|
https://github.com/python/mypy/issues/5846
|
Traceback (most recent call last):
File "/home/derrick_chambers/anaconda3/bin/mypy", line 11, in <module>
sys.exit(console_entry())
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/main.py", line 91, in main
res = type_check_only(sources, bin_dir, options, flush_errors, fscache) # noqa
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/main.py", line 148, in type_check_only
fscache=fscache)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 183, in build
flush_errors, fscache)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 356, in _build
graph = dispatch(sources, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2543, in dispatch
process_graph(graph, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2840, in process_graph
process_stale_scc(graph, scc, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2963, in process_stale_scc
graph[id].type_check_first_pass()
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2103, in type_check_first_pass
self.type_checker().check_first_pass()
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 256, in check_first_pass
self.accept(d)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 820, in accept
return visitor.visit_class_def(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1461, in visit_class_def
self.accept(defn.defs)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 885, in accept
return visitor.visit_block(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1607, in visit_block
self.accept(s)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 603, in accept
return visitor.visit_func_def(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 666, in visit_func_def
self._visit_func_def(defn)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 670, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 732, in check_func_item
self.check_func_def(defn, typ, name)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 898, in check_func_def
self.accept(item.body)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 885, in accept
return visitor.visit_block(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1607, in visit_block
self.accept(s)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 933, in accept
return visitor.visit_assignment_stmt(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1614, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1663, in check_assignment
if self.check_compatibility_all_supers(lvalue, lvalue_type, rvalue):
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1755, in check_compatibility_all_supers
base_type, base_node = self.lvalue_type_from_base(lvalue_node, base)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1842, in lvalue_type_from_base
assert self_type is not None, "Internal error: base lookup outside class"
AssertionError: Internal error: base lookup outside class
breakmypy.py:14: : note: use --pdb to drop into pdb
|
AssertionError
|
def active_self_type(self) -> Optional[Union[Instance, TupleType]]:
"""An instance or tuple type representing the current class.
This returns None unless we are in class body or in a method.
In particular, inside a function nested in method this returns None.
"""
info = self.active_class()
if not info and self.top_function():
info = self.enclosing_class()
if info:
return fill_typevars(info)
return None
|
def active_self_type(self) -> Optional[Union[Instance, TupleType]]:
info = self.active_class()
if info:
return fill_typevars(info)
return None
|
https://github.com/python/mypy/issues/5846
|
Traceback (most recent call last):
File "/home/derrick_chambers/anaconda3/bin/mypy", line 11, in <module>
sys.exit(console_entry())
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/main.py", line 91, in main
res = type_check_only(sources, bin_dir, options, flush_errors, fscache) # noqa
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/main.py", line 148, in type_check_only
fscache=fscache)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 183, in build
flush_errors, fscache)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 356, in _build
graph = dispatch(sources, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2543, in dispatch
process_graph(graph, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2840, in process_graph
process_stale_scc(graph, scc, manager)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2963, in process_stale_scc
graph[id].type_check_first_pass()
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/build.py", line 2103, in type_check_first_pass
self.type_checker().check_first_pass()
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 256, in check_first_pass
self.accept(d)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 820, in accept
return visitor.visit_class_def(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1461, in visit_class_def
self.accept(defn.defs)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 885, in accept
return visitor.visit_block(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1607, in visit_block
self.accept(s)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 603, in accept
return visitor.visit_func_def(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 666, in visit_func_def
self._visit_func_def(defn)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 670, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 732, in check_func_item
self.check_func_def(defn, typ, name)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 898, in check_func_def
self.accept(item.body)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 885, in accept
return visitor.visit_block(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1607, in visit_block
self.accept(s)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 355, in accept
stmt.accept(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/nodes.py", line 933, in accept
return visitor.visit_assignment_stmt(self)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1614, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1663, in check_assignment
if self.check_compatibility_all_supers(lvalue, lvalue_type, rvalue):
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1755, in check_compatibility_all_supers
base_type, base_node = self.lvalue_type_from_base(lvalue_node, base)
File "/home/derrick_chambers/anaconda3/lib/python3.7/site-packages/mypy/checker.py", line 1842, in lvalue_type_from_base
assert self_type is not None, "Internal error: base lookup outside class"
AssertionError: Internal error: base lookup outside class
breakmypy.py:14: : note: use --pdb to drop into pdb
|
AssertionError
|
def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
# OverloadedFuncDef refers to any legitimate situation where you have
# more than one declaration for the same function in a row. This occurs
# with a @property with a setter or a deleter, and for a classic
# @overload.
defn._fullname = self.qualified_name(defn.name())
# TODO: avoid modifying items.
defn.items = defn.unanalyzed_items.copy()
first_item = defn.items[0]
first_item.is_overload = True
first_item.accept(self)
if isinstance(first_item, Decorator) and first_item.func.is_property:
# This is a property.
first_item.func.is_overload = True
self.analyze_property_with_multi_part_definition(defn)
typ = function_type(first_item.func, self.builtin_type("builtins.function"))
assert isinstance(typ, CallableType)
types = [typ]
else:
# This is an a normal overload. Find the item signatures, the
# implementation (if outside a stub), and any missing @overload
# decorators.
types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn)
defn.impl = impl
if non_overload_indexes:
self.handle_missing_overload_decorators(
defn, non_overload_indexes, some_overload_decorators=len(types) > 0
)
# If we found an implementation, remove it from the overload item list,
# as it's special.
if impl is not None:
assert impl is defn.items[-1]
defn.items = defn.items[:-1]
elif not non_overload_indexes:
self.handle_missing_overload_implementation(defn)
if types:
defn.type = Overloaded(types)
defn.type.line = defn.line
if not defn.items:
# It was not a real overload after all, but function redefinition. We've
# visited the redefinition(s) already.
if not defn.impl:
# For really broken overloads with no items and no implementation we need to keep
# at least one item to hold basic information like function name.
defn.impl = defn.unanalyzed_items[-1]
return
# We know this is an overload def. Infer properties and perform some checks.
self.process_final_in_overload(defn)
self.process_static_or_class_method_in_overload(defn)
|
def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
# OverloadedFuncDef refers to any legitimate situation where you have
# more than one declaration for the same function in a row. This occurs
# with a @property with a setter or a deleter, and for a classic
# @overload.
defn._fullname = self.qualified_name(defn.name())
# TODO: avoid modifying items.
defn.items = defn.unanalyzed_items.copy()
first_item = defn.items[0]
first_item.is_overload = True
first_item.accept(self)
if isinstance(first_item, Decorator) and first_item.func.is_property:
# This is a property.
first_item.func.is_overload = True
self.analyze_property_with_multi_part_definition(defn)
typ = function_type(first_item.func, self.builtin_type("builtins.function"))
assert isinstance(typ, CallableType)
types = [typ]
else:
# This is an a normal overload. Find the item signatures, the
# implementation (if outside a stub), and any missing @overload
# decorators.
types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn)
defn.impl = impl
if non_overload_indexes:
self.handle_missing_overload_decorators(
defn, non_overload_indexes, some_overload_decorators=len(types) > 0
)
# If we found an implementation, remove it from the overload item list,
# as it's special.
if impl is not None:
assert impl is defn.items[-1]
defn.items = defn.items[:-1]
elif not non_overload_indexes:
self.handle_missing_overload_implementation(defn)
if types:
defn.type = Overloaded(types)
defn.type.line = defn.line
if not defn.items:
# It was not a real overload after all, but function redefinition. We've
# visited the redefinition(s) already.
return
# We know this is an overload def. Infer properties and perform some checks.
self.process_final_in_overload(defn)
self.process_static_or_class_method_in_overload(defn)
|
https://github.com/python/mypy/issues/7209
|
Traceback (most recent call last):
File "/home/hong/src/mypy/.venv/bin/mypy", line 11, in <module>
load_entry_point('mypy', 'console_scripts', 'mypy')()
File "/home/hong/src/mypy/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/home/hong/src/mypy/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/home/hong/src/mypy/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/home/hong/src/mypy/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/home/hong/src/mypy/mypy/build.py", line 2579, in dispatch
process_graph(graph, manager)
File "/home/hong/src/mypy/mypy/build.py", line 2892, in process_graph
process_stale_scc(graph, scc, manager)
File "/home/hong/src/mypy/mypy/build.py", line 2990, in process_stale_scc
semantic_analysis_for_scc(graph, scc, manager.errors)
File "/home/hong/src/mypy/mypy/newsemanal/semanal_main.py", line 78, in semantic_analysis_for_scc
process_functions(graph, scc, patches)
File "/home/hong/src/mypy/mypy/newsemanal/semanal_main.py", line 238, in process_functions
patches)
File "/home/hong/src/mypy/mypy/newsemanal/semanal_main.py", line 274, in process_top_level_function
final_iteration, patches)
File "/home/hong/src/mypy/mypy/newsemanal/semanal_main.py", line 330, in semantic_analyze_target
active_type=active_type)
File "/home/hong/src/mypy/mypy/newsemanal/semanal.py", line 375, in refresh_partial
self.accept(node)
File "/home/hong/src/mypy/mypy/newsemanal/semanal.py", line 4550, in accept
node.accept(self)
File "/home/hong/src/mypy/mypy/nodes.py", line 505, in accept
return visitor.visit_overloaded_func_def(self)
File "/home/hong/src/mypy/mypy/newsemanal/semanal.py", line 641, in visit_overloaded_func_def
self.add_function_to_symbol_table(defn)
File "/home/hong/src/mypy/mypy/newsemanal/semanal.py", line 863, in add_function_to_symbol_table
func._fullname = self.qualified_name(func.name())
File "/home/hong/src/mypy/mypy/nodes.py", line 501, in name
assert self.impl is not None
AssertionError:
/home/hong/tmp/type.pyi:3: : note: use --pdb to drop into pdb
|
AssertionError
|
def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:
result = None # type: Optional[Type]
node = e.node
if isinstance(e, NameExpr) and e.is_special_form:
# A special form definition, nothing to check here.
return AnyType(TypeOfAny.special_form)
if isinstance(node, Var):
# Variable reference.
result = self.analyze_var_ref(node, e)
if isinstance(result, PartialType):
result = self.chk.handle_partial_var_type(result, lvalue, node, e)
elif isinstance(node, FuncDef):
# Reference to a global function.
result = function_type(node, self.named_type("builtins.function"))
elif isinstance(node, OverloadedFuncDef) and node.type is not None:
# node.type is None when there are multiple definitions of a function
# and it's decorated by something that is not typing.overload
# TODO: use a dummy Overloaded instead of AnyType in this case
# like we do in mypy.types.function_type()?
result = node.type
elif isinstance(node, TypeInfo):
# Reference to a type object.
result = type_object_type(node, self.named_type)
if isinstance(result, CallableType) and isinstance(result.ret_type, Instance):
# We need to set correct line and column
# TODO: always do this in type_object_type by passing the original context
result.ret_type.line = e.line
result.ret_type.column = e.column
if isinstance(self.type_context[-1], TypeType):
# This is the type in a Type[] expression, so substitute type
# variables with Any.
result = erasetype.erase_typevars(result)
elif isinstance(node, MypyFile):
# Reference to a module object.
try:
result = self.named_type("types.ModuleType")
except KeyError:
# In test cases might 'types' may not be available.
# Fall back to a dummy 'object' type instead to
# avoid a crash.
result = self.named_type("builtins.object")
elif isinstance(node, Decorator):
result = self.analyze_var_ref(node.var, e)
elif isinstance(node, TypeAlias):
# Something that refers to a type alias appears in runtime context.
# Note that we suppress bogus errors for alias redefinitions,
# they are already reported in semanal.py.
result = self.alias_type_in_runtime_context(
node.target,
node.alias_tvars,
node.no_args,
e,
alias_definition=e.is_alias_rvalue or lvalue,
)
else:
if isinstance(node, PlaceholderNode):
assert False, "PlaceholderNode %r leaked to checker" % node.fullname()
# Unknown reference; use any type implicitly to avoid
# generating extra type errors.
result = AnyType(TypeOfAny.from_error)
assert result is not None
return result
|
def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:
result = None # type: Optional[Type]
node = e.node
if isinstance(e, NameExpr) and e.is_special_form:
# A special form definition, nothing to check here.
return AnyType(TypeOfAny.special_form)
if isinstance(node, Var):
# Variable reference.
result = self.analyze_var_ref(node, e)
if isinstance(result, PartialType):
result = self.chk.handle_partial_var_type(result, lvalue, node, e)
elif isinstance(node, FuncDef):
# Reference to a global function.
result = function_type(node, self.named_type("builtins.function"))
elif isinstance(node, OverloadedFuncDef) and node.type is not None:
# node.type is None when there are multiple definitions of a function
# and it's decorated by something that is not typing.overload
result = node.type
elif isinstance(node, TypeInfo):
# Reference to a type object.
result = type_object_type(node, self.named_type)
if isinstance(result, CallableType) and isinstance(result.ret_type, Instance):
# We need to set correct line and column
# TODO: always do this in type_object_type by passing the original context
result.ret_type.line = e.line
result.ret_type.column = e.column
if isinstance(self.type_context[-1], TypeType):
# This is the type in a Type[] expression, so substitute type
# variables with Any.
result = erasetype.erase_typevars(result)
elif isinstance(node, MypyFile):
# Reference to a module object.
try:
result = self.named_type("types.ModuleType")
except KeyError:
# In test cases might 'types' may not be available.
# Fall back to a dummy 'object' type instead to
# avoid a crash.
result = self.named_type("builtins.object")
elif isinstance(node, Decorator):
result = self.analyze_var_ref(node.var, e)
elif isinstance(node, TypeAlias):
# Something that refers to a type alias appears in runtime context.
# Note that we suppress bogus errors for alias redefinitions,
# they are already reported in semanal.py.
result = self.alias_type_in_runtime_context(
node.target,
node.alias_tvars,
node.no_args,
e,
alias_definition=e.is_alias_rvalue or lvalue,
)
else:
if isinstance(node, PlaceholderNode):
assert False, "PlaceholderNode %r leaked to checker" % node.fullname()
# Unknown reference; use any type implicitly to avoid
# generating extra type errors.
result = AnyType(TypeOfAny.from_error)
assert result is not None
return result
|
https://github.com/python/mypy/issues/7044
|
(tildes) vagrant@ubuntu-xenial:/opt/tildes$ mypy --new-semantic-analyzer --show-traceback test_mypy.py
test_mypy.py:16: error: Cannot assign to a method
test_mypy.py:16: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.720+dev.48916e63403645730a584d6898fbe925d513a841
Traceback (most recent call last):
File "/opt/venvs/tildes/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2567, in dispatch
process_graph(graph, manager)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2880, in process_graph
process_stale_scc(graph, scc, manager)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2987, in process_stale_scc
graph[id].type_check_first_pass()
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2096, in type_check_first_pass
self.type_checker().check_first_pass()
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 281, in check_first_pass
self.accept(d)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 913, in accept
return visitor.visit_class_def(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1596, in visit_class_def
self.accept(defn.defs)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1785, in visit_block
self.accept(s)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 655, in accept
return visitor.visit_func_def(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 703, in visit_func_def
self._visit_func_def(defn)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 707, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 769, in check_func_item
self.check_func_def(defn, typ, name)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 935, in check_func_def
self.accept(item.body)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1785, in visit_block
self.accept(s)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 1036, in accept
return visitor.visit_assignment_stmt(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1793, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1834, in check_assignment
lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 2479, in check_lvalue
True)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkexpr.py", line 1766, in analyze_ordinary_member_access
in_literal_context=self.is_literal_context())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 103, in analyze_member_access
result = _analyze_member_access(name, typ, mx, override_info)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 117, in _analyze_member_access
return analyze_instance_member_access(name, typ, mx, override_info)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 179, in analyze_instance_member_access
signature = function_type(method, mx.builtin_type('builtins.function'))
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/types.py", line 2188, in function_type
assert isinstance(func, mypy.nodes.FuncItem), str(func)
AssertionError: OverloadedFuncDef:7(
Decorator:11(
Var(name)
MemberExpr:11(
NameExpr(name [test_mypy.FirstNameOnly.name])
setter)
FuncDef:12(
name
Args(
Var(self)
Var(value))
def (self: test_mypy.FirstNameOnly, value: builtins.str)
Block:12(
AssignmentStmt:13(
MemberExpr:13(
NameExpr(self [l])
first_name)
NameExpr(value [l]))))))
|
AssertionError
|
def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
# OverloadedFuncDef refers to any legitimate situation where you have
# more than one declaration for the same function in a row. This occurs
# with a @property with a setter or a deleter, and for a classic
# @overload.
defn._fullname = self.qualified_name(defn.name())
# TODO: avoid modifying items.
defn.items = defn.unanalyzed_items.copy()
first_item = defn.items[0]
first_item.is_overload = True
first_item.accept(self)
if isinstance(first_item, Decorator) and first_item.func.is_property:
# This is a property.
first_item.func.is_overload = True
self.analyze_property_with_multi_part_definition(defn)
typ = function_type(first_item.func, self.builtin_type("builtins.function"))
assert isinstance(typ, CallableType)
types = [typ]
else:
# This is an a normal overload. Find the item signatures, the
# implementation (if outside a stub), and any missing @overload
# decorators.
types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn)
defn.impl = impl
if non_overload_indexes:
self.handle_missing_overload_decorators(
defn, non_overload_indexes, some_overload_decorators=len(types) > 0
)
# If we found an implementation, remove it from the overload item list,
# as it's special.
if impl is not None:
assert impl is defn.items[-1]
defn.items = defn.items[:-1]
elif not non_overload_indexes:
self.handle_missing_overload_implementation(defn)
if types:
defn.type = Overloaded(types)
defn.type.line = defn.line
if not defn.items:
# It was not a real overload after all, but function redefinition. We've
# visited the redefinition(s) already.
return
# We know this is an overload def. Infer properties and perform some checks.
self.process_final_in_overload(defn)
self.process_static_or_class_method_in_overload(defn)
|
def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
# OverloadedFuncDef refers to any legitimate situation where you have
# more than one declaration for the same function in a row. This occurs
# with a @property with a setter or a deleter, and for a classic
# @overload.
defn._fullname = self.qualified_name(defn.name())
# TODO: avoid modifying items.
defn.items = defn.unanalyzed_items.copy()
first_item = defn.items[0]
first_item.is_overload = True
first_item.accept(self)
if isinstance(first_item, Decorator) and first_item.func.is_property:
# This is a property.
first_item.func.is_overload = True
self.analyze_property_with_multi_part_definition(defn)
typ = function_type(first_item.func, self.builtin_type("builtins.function"))
assert isinstance(typ, CallableType)
types = [typ]
else:
# This is an a normal overload. Find the item signatures, the
# implementation (if outside a stub), and any missing @overload
# decorators.
types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn)
defn.impl = impl
if non_overload_indexes:
self.handle_missing_overload_decorators(
defn, non_overload_indexes, some_overload_decorators=len(types) > 0
)
# If we found an implementation, remove it from the overload item list,
# as it's special.
if impl is not None:
assert impl is defn.items[-1]
defn.items = defn.items[:-1]
elif not non_overload_indexes:
self.handle_missing_overload_implementation(defn)
if types:
defn.type = Overloaded(types)
defn.type.line = defn.line
if not defn.items:
# It was not a real overload after all, but function redefinition. We've
# visited the redefinition(s) already.
return
# We know this is an overload def. Infer properties and perform some checks.
self.process_final_in_overload(defn)
self.process_static_or_class_method_in_overload(defn)
self.add_symbol(defn.name(), defn, defn)
|
https://github.com/python/mypy/issues/7044
|
(tildes) vagrant@ubuntu-xenial:/opt/tildes$ mypy --new-semantic-analyzer --show-traceback test_mypy.py
test_mypy.py:16: error: Cannot assign to a method
test_mypy.py:16: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.720+dev.48916e63403645730a584d6898fbe925d513a841
Traceback (most recent call last):
File "/opt/venvs/tildes/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2567, in dispatch
process_graph(graph, manager)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2880, in process_graph
process_stale_scc(graph, scc, manager)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2987, in process_stale_scc
graph[id].type_check_first_pass()
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2096, in type_check_first_pass
self.type_checker().check_first_pass()
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 281, in check_first_pass
self.accept(d)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 913, in accept
return visitor.visit_class_def(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1596, in visit_class_def
self.accept(defn.defs)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1785, in visit_block
self.accept(s)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 655, in accept
return visitor.visit_func_def(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 703, in visit_func_def
self._visit_func_def(defn)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 707, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 769, in check_func_item
self.check_func_def(defn, typ, name)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 935, in check_func_def
self.accept(item.body)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1785, in visit_block
self.accept(s)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 1036, in accept
return visitor.visit_assignment_stmt(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1793, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1834, in check_assignment
lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 2479, in check_lvalue
True)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkexpr.py", line 1766, in analyze_ordinary_member_access
in_literal_context=self.is_literal_context())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 103, in analyze_member_access
result = _analyze_member_access(name, typ, mx, override_info)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 117, in _analyze_member_access
return analyze_instance_member_access(name, typ, mx, override_info)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 179, in analyze_instance_member_access
signature = function_type(method, mx.builtin_type('builtins.function'))
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/types.py", line 2188, in function_type
assert isinstance(func, mypy.nodes.FuncItem), str(func)
AssertionError: OverloadedFuncDef:7(
Decorator:11(
Var(name)
MemberExpr:11(
NameExpr(name [test_mypy.FirstNameOnly.name])
setter)
FuncDef:12(
name
Args(
Var(self)
Var(value))
def (self: test_mypy.FirstNameOnly, value: builtins.str)
Block:12(
AssignmentStmt:13(
MemberExpr:13(
NameExpr(self [l])
first_name)
NameExpr(value [l]))))))
|
AssertionError
|
def function_type(func: mypy.nodes.FuncBase, fallback: Instance) -> FunctionLike:
if func.type:
assert isinstance(func.type, FunctionLike)
return func.type
else:
# Implicit type signature with dynamic types.
if isinstance(func, mypy.nodes.FuncItem):
return callable_type(func, fallback)
else:
# Broken overloads can have self.type set to None.
# TODO: should we instead always set the type in semantic analyzer?
assert isinstance(func, mypy.nodes.OverloadedFuncDef)
any_type = AnyType(TypeOfAny.from_error)
dummy = CallableType(
[any_type, any_type],
[ARG_STAR, ARG_STAR2],
[None, None],
any_type,
fallback,
line=func.line,
is_ellipsis_args=True,
)
# Return an Overloaded, because some callers may expect that
# an OverloadedFuncDef has an Overloaded type.
return Overloaded([dummy])
|
def function_type(func: mypy.nodes.FuncBase, fallback: Instance) -> FunctionLike:
if func.type:
assert isinstance(func.type, FunctionLike)
return func.type
else:
# Implicit type signature with dynamic types.
# Overloaded functions always have a signature, so func must be an ordinary function.
assert isinstance(func, mypy.nodes.FuncItem), str(func)
return callable_type(func, fallback)
|
https://github.com/python/mypy/issues/7044
|
(tildes) vagrant@ubuntu-xenial:/opt/tildes$ mypy --new-semantic-analyzer --show-traceback test_mypy.py
test_mypy.py:16: error: Cannot assign to a method
test_mypy.py:16: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.720+dev.48916e63403645730a584d6898fbe925d513a841
Traceback (most recent call last):
File "/opt/venvs/tildes/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2567, in dispatch
process_graph(graph, manager)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2880, in process_graph
process_stale_scc(graph, scc, manager)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2987, in process_stale_scc
graph[id].type_check_first_pass()
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/build.py", line 2096, in type_check_first_pass
self.type_checker().check_first_pass()
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 281, in check_first_pass
self.accept(d)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 913, in accept
return visitor.visit_class_def(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1596, in visit_class_def
self.accept(defn.defs)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1785, in visit_block
self.accept(s)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 655, in accept
return visitor.visit_func_def(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 703, in visit_func_def
self._visit_func_def(defn)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 707, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 769, in check_func_item
self.check_func_def(defn, typ, name)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 935, in check_func_def
self.accept(item.body)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1785, in visit_block
self.accept(s)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 392, in accept
stmt.accept(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/nodes.py", line 1036, in accept
return visitor.visit_assignment_stmt(self)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1793, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 1834, in check_assignment
lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checker.py", line 2479, in check_lvalue
True)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkexpr.py", line 1766, in analyze_ordinary_member_access
in_literal_context=self.is_literal_context())
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 103, in analyze_member_access
result = _analyze_member_access(name, typ, mx, override_info)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 117, in _analyze_member_access
return analyze_instance_member_access(name, typ, mx, override_info)
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/checkmember.py", line 179, in analyze_instance_member_access
signature = function_type(method, mx.builtin_type('builtins.function'))
File "/opt/venvs/tildes/lib/python3.7/site-packages/mypy/types.py", line 2188, in function_type
assert isinstance(func, mypy.nodes.FuncItem), str(func)
AssertionError: OverloadedFuncDef:7(
Decorator:11(
Var(name)
MemberExpr:11(
NameExpr(name [test_mypy.FirstNameOnly.name])
setter)
FuncDef:12(
name
Args(
Var(self)
Var(value))
def (self: test_mypy.FirstNameOnly, value: builtins.str)
Block:12(
AssignmentStmt:13(
MemberExpr:13(
NameExpr(self [l])
first_name)
NameExpr(value [l]))))))
|
AssertionError
|
def attr_class_maker_callback(
ctx: "mypy.plugin.ClassDefContext", auto_attribs_default: bool = False
) -> None:
"""Add necessary dunder methods to classes decorated with attr.s.
attrs is a package that lets you define classes without writing dull boilerplate code.
At a quick glance, the decorator searches the class body for assignments of `attr.ib`s (or
annotated variables if auto_attribs=True), then depending on how the decorator is called,
it will add an __init__ or all the __cmp__ methods. For frozen=True it will turn the attrs
into properties.
See http://www.attrs.org/en/stable/how-does-it-work.html for information on how attrs works.
"""
info = ctx.cls.info
init = _get_decorator_bool_argument(ctx, "init", True)
frozen = _get_frozen(ctx)
cmp = _get_decorator_bool_argument(ctx, "cmp", True)
auto_attribs = _get_decorator_bool_argument(
ctx, "auto_attribs", auto_attribs_default
)
kw_only = _get_decorator_bool_argument(ctx, "kw_only", False)
if ctx.api.options.python_version[0] < 3:
if auto_attribs:
ctx.api.fail("auto_attribs is not supported in Python 2", ctx.reason)
return
if not info.defn.base_type_exprs:
# Note: This will not catch subclassing old-style classes.
ctx.api.fail("attrs only works with new-style classes", info.defn)
return
if kw_only:
ctx.api.fail(KW_ONLY_PYTHON_2_UNSUPPORTED, ctx.reason)
return
attributes = _analyze_class(ctx, auto_attribs, kw_only)
if ctx.api.options.new_semantic_analyzer:
# Check if attribute types are ready.
for attr in attributes:
node = info.get(attr.name)
if node is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
return
if node.type is None and not ctx.api.final_iteration:
ctx.api.defer()
return
# Save the attributes so that subclasses can reuse them.
ctx.cls.info.metadata["attrs"] = {
"attributes": [attr.serialize() for attr in attributes],
"frozen": frozen,
}
adder = MethodAdder(ctx)
if init:
_add_init(ctx, attributes, adder)
if cmp:
_add_cmp(ctx, adder)
if frozen:
_make_frozen(ctx, attributes)
|
def attr_class_maker_callback(
ctx: "mypy.plugin.ClassDefContext", auto_attribs_default: bool = False
) -> None:
"""Add necessary dunder methods to classes decorated with attr.s.
attrs is a package that lets you define classes without writing dull boilerplate code.
At a quick glance, the decorator searches the class body for assignments of `attr.ib`s (or
annotated variables if auto_attribs=True), then depending on how the decorator is called,
it will add an __init__ or all the __cmp__ methods. For frozen=True it will turn the attrs
into properties.
See http://www.attrs.org/en/stable/how-does-it-work.html for information on how attrs works.
"""
info = ctx.cls.info
init = _get_decorator_bool_argument(ctx, "init", True)
frozen = _get_frozen(ctx)
cmp = _get_decorator_bool_argument(ctx, "cmp", True)
auto_attribs = _get_decorator_bool_argument(
ctx, "auto_attribs", auto_attribs_default
)
kw_only = _get_decorator_bool_argument(ctx, "kw_only", False)
if ctx.api.options.python_version[0] < 3:
if auto_attribs:
ctx.api.fail("auto_attribs is not supported in Python 2", ctx.reason)
return
if not info.defn.base_type_exprs:
# Note: This will not catch subclassing old-style classes.
ctx.api.fail("attrs only works with new-style classes", info.defn)
return
if kw_only:
ctx.api.fail(KW_ONLY_PYTHON_2_UNSUPPORTED, ctx.reason)
return
attributes = _analyze_class(ctx, auto_attribs, kw_only)
if ctx.api.options.new_semantic_analyzer:
# Check if attribute types are ready.
for attr in attributes:
if info[attr.name].type is None and not ctx.api.final_iteration:
ctx.api.defer()
return
# Save the attributes so that subclasses can reuse them.
ctx.cls.info.metadata["attrs"] = {
"attributes": [attr.serialize() for attr in attributes],
"frozen": frozen,
}
adder = MethodAdder(ctx)
if init:
_add_init(ctx, attributes, adder)
if cmp:
_add_cmp(ctx, adder)
if frozen:
_make_frozen(ctx, attributes)
|
https://github.com/python/mypy/issues/7076
|
/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/aiohttp/client.py:49: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.720+dev.262fe3dc4d5d14492c6fd4009d91c555c406ac04
Traceback (most recent call last):
File "/Users/skreft/.virtualenvs/zapship/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 2567, in dispatch
process_graph(graph, manager)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 2880, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 2978, in process_stale_scc
semantic_analysis_for_scc(graph, scc, manager.errors)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal_main.py", line 74, in semantic_analysis_for_scc
process_top_levels(graph, scc, patches)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal_main.py", line 193, in process_top_levels
patches)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal_main.py", line 315, in semantic_analyze_target
active_type=active_type)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 360, in refresh_partial
self.refresh_top_level(node)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 371, in refresh_top_level
self.accept(d)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 4435, in accept
node.accept(self)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/nodes.py", line 923, in accept
return visitor.visit_class_def(self)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 978, in visit_class_def
self.analyze_class(defn)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 1049, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 1058, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 1103, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/plugins/attrs.py", line 214, in attr_class_maker_callback
if info[attr.name].type is None and not ctx.api.final_iteration:
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/nodes.py", line 2413, in __getitem__
raise KeyError(name)
KeyError: 'total'
/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/aiohttp/client.py:49: : note: use --pdb to drop into pdb
|
KeyError
|
def collect_attributes(self) -> List[DataclassAttribute]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# This name is likely blocked by a star import. We don't need to defer because
# defer() is already called by mark_incomplete().
assert ctx.api.options.new_semantic_analyzer
continue
node = sym.node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
continue
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
if (
isinstance(node.type, Instance)
and node.type.type.fullname() == "dataclasses.InitVar"
):
is_init_var = True
node.type = node.type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
init_method = cls.info.get_method("__init__")
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname()))
for name, data in info.metadata["dataclass"]["attributes"].items():
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data)
if attr.is_init_var and isinstance(init_method, FuncDef):
# InitVars are removed from classes so, in order for them to be inherited
# properly, we need to re-inject them into subclasses' sym tables here.
# To do that, we look 'em up from the parents' __init__. These variables
# are subsequently removed from the sym table at the end of
# DataclassTransformer.transform.
for arg, arg_name in zip(
init_method.arguments, init_method.arg_names
):
if arg_name == attr.name:
cls.info.names[attr.name] = SymbolTableNode(
MDEF, arg.variable
)
known_attrs.add(name)
super_attrs.append(attr)
else:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
(attr,) = [a for a in all_attrs if a.name == name]
all_attrs.remove(attr)
super_attrs.append(attr)
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
Context(line=attr.line, column=attr.column),
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
def collect_attributes(self) -> List[DataclassAttribute]:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
"""
# First, collect attributes belonging to the current class.
ctx = self._ctx
cls = self._ctx.cls
attrs = [] # type: List[DataclassAttribute]
known_attrs = set() # type: Set[str]
for stmt in cls.defs.body:
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not (isinstance(stmt, AssignmentStmt) and stmt.new_syntax):
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
node = cls.info.names[lhs.name].node
if isinstance(node, PlaceholderNode):
# This node is not ready yet.
continue
assert isinstance(node, Var)
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
if (
isinstance(node.type, Instance)
and node.type.type.fullname() == "dataclasses.InitVar"
):
is_init_var = True
node.type = node.type.args[0]
has_field_call, field_args = _collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = True
else:
is_in_init = bool(ctx.api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = "default" in field_args or "default_factory" in field_args
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
known_attrs.add(lhs.name)
attrs.append(
DataclassAttribute(
name=lhs.name,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
)
)
# Next, collect attributes belonging to any class in the MRO
# as long as those attributes weren't already collected. This
# makes it possible to overwrite attributes in subclasses.
# copy() because we potentially modify all_attrs below and if this code requires debugging
# we'll have unmodified attrs laying around.
all_attrs = attrs.copy()
init_method = cls.info.get_method("__init__")
for info in cls.info.mro[1:-1]:
if "dataclass" not in info.metadata:
continue
super_attrs = []
# Each class depends on the set of attributes in its dataclass ancestors.
ctx.api.add_plugin_dependency(make_wildcard_trigger(info.fullname()))
for name, data in info.metadata["dataclass"]["attributes"].items():
if name not in known_attrs:
attr = DataclassAttribute.deserialize(info, data)
if attr.is_init_var and isinstance(init_method, FuncDef):
# InitVars are removed from classes so, in order for them to be inherited
# properly, we need to re-inject them into subclasses' sym tables here.
# To do that, we look 'em up from the parents' __init__. These variables
# are subsequently removed from the sym table at the end of
# DataclassTransformer.transform.
for arg, arg_name in zip(
init_method.arguments, init_method.arg_names
):
if arg_name == attr.name:
cls.info.names[attr.name] = SymbolTableNode(
MDEF, arg.variable
)
known_attrs.add(name)
super_attrs.append(attr)
else:
# How early in the attribute list an attribute appears is determined by the
# reverse MRO, not simply MRO.
# See https://docs.python.org/3/library/dataclasses.html#inheritance for
# details.
(attr,) = [a for a in all_attrs if a.name == name]
all_attrs.remove(attr)
super_attrs.append(attr)
all_attrs = super_attrs + all_attrs
# Ensure that arguments without a default don't follow
# arguments that have a default.
found_default = False
for attr in all_attrs:
# If we find any attribute that is_in_init but that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default:
ctx.api.fail(
"Attributes without a default cannot follow attributes with one",
Context(line=attr.line, column=attr.column),
)
found_default = found_default or (attr.has_default and attr.is_in_init)
return all_attrs
|
https://github.com/python/mypy/issues/7076
|
/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/aiohttp/client.py:49: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.720+dev.262fe3dc4d5d14492c6fd4009d91c555c406ac04
Traceback (most recent call last):
File "/Users/skreft/.virtualenvs/zapship/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 2567, in dispatch
process_graph(graph, manager)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 2880, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/build.py", line 2978, in process_stale_scc
semantic_analysis_for_scc(graph, scc, manager.errors)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal_main.py", line 74, in semantic_analysis_for_scc
process_top_levels(graph, scc, patches)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal_main.py", line 193, in process_top_levels
patches)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal_main.py", line 315, in semantic_analyze_target
active_type=active_type)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 360, in refresh_partial
self.refresh_top_level(node)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 371, in refresh_top_level
self.accept(d)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 4435, in accept
node.accept(self)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/nodes.py", line 923, in accept
return visitor.visit_class_def(self)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 978, in visit_class_def
self.analyze_class(defn)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 1049, in analyze_class
self.analyze_class_body_common(defn)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 1058, in analyze_class_body_common
self.apply_class_plugin_hooks(defn)
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/newsemanal/semanal.py", line 1103, in apply_class_plugin_hooks
hook(ClassDefContext(defn, decorator, self))
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/plugins/attrs.py", line 214, in attr_class_maker_callback
if info[attr.name].type is None and not ctx.api.final_iteration:
File "/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/mypy/nodes.py", line 2413, in __getitem__
raise KeyError(name)
KeyError: 'total'
/Users/skreft/.virtualenvs/zapship/lib/python3.6/site-packages/aiohttp/client.py:49: : note: use --pdb to drop into pdb
|
KeyError
|
def calculate_class_mro(
self, defn: ClassDef, obj_type: Optional[Callable[[], Instance]] = None
) -> None:
"""Calculate method resolution order for a class.
`obj_type` may be omitted in the third pass when all classes are already analyzed.
It exists just to fill in empty base class list during second pass in case of
an import cycle.
"""
try:
calculate_mro(defn.info, obj_type)
except MroError:
self.fail_blocker(
"Cannot determine consistent method resolution "
'order (MRO) for "%s"' % defn.name,
defn,
)
defn.info.mro = []
# Allow plugins to alter the MRO to handle the fact that `def mro()`
# on metaclasses permits MRO rewriting.
if defn.fullname:
hook = self.plugin.get_customize_class_mro_hook(defn.fullname)
if hook:
hook(ClassDefContext(defn, FakeExpression(), self))
|
def calculate_class_mro(
self, defn: ClassDef, obj_type: Optional[Callable[[], Instance]] = None
) -> None:
"""Calculate method resolution order for a class.
`obj_type` may be omitted in the third pass when all classes are already analyzed.
It exists just to fill in empty base class list during second pass in case of
an import cycle.
"""
try:
calculate_mro(defn.info, obj_type)
except MroError:
self.fail_blocker(
"Cannot determine consistent method resolution "
'order (MRO) for "%s"' % defn.name,
defn,
)
defn.info.mro = []
# Allow plugins to alter the MRO to handle the fact that `def mro()`
# on metaclasses permits MRO rewriting.
if defn.fullname:
hook = self.plugin.get_customize_class_mro_hook(defn.fullname)
if hook:
hook(ClassDefContext(defn, Expression(), self))
|
https://github.com/python/mypy/issues/6706
|
tmp/sample.py:1: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "ve/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "mypy/semanal.py", line 3791, in accept
File "mypy/nodes.py", line 895, in accept__Node_glue
File "mypy/nodes.py", line 896, in accept
File "mypy/semanal.py", line 804, in visit_class_def__StatementVisitor_glue
File "mypy/semanal.py", line 807, in visit_class_def
File "mypy/semanal.py", line 819, in analyze_class
File "mypy/semanal.py", line 1229, in analyze_base_classes
File "mypy/semanal.py", line 1250, in calculate_class_mro
TypeError: interpreted classes cannot inherit from compiled
tmp/sample.py:1: : note: use --pdb to drop into pdb
|
TypeError
|
def save_namedtuple_body(self, named_tuple_info: TypeInfo) -> Iterator[None]:
"""Preserve the generated body of class-based named tuple and then restore it.
Temporarily clear the names dict so we don't get errors about duplicate names
that were already set in build_namedtuple_typeinfo (we already added the tuple
field names while generating the TypeInfo, and actual duplicates are
already reported).
"""
nt_names = named_tuple_info.names
named_tuple_info.names = SymbolTable()
yield
# Make sure we didn't use illegal names, then reset the names in the typeinfo.
for prohibited in NAMEDTUPLE_PROHIBITED_NAMES:
if prohibited in named_tuple_info.names:
if nt_names.get(prohibited) is named_tuple_info.names[prohibited]:
continue
ctx = named_tuple_info.names[prohibited].node
assert ctx is not None
self.fail(
'Cannot overwrite NamedTuple attribute "{}"'.format(prohibited), ctx
)
# Restore the names in the original symbol table. This ensures that the symbol
# table contains the field objects created by build_namedtuple_typeinfo. Exclude
# __doc__, which can legally be overwritten by the class.
for key, value in nt_names.items():
if key in named_tuple_info.names:
if key == "__doc__":
continue
# Keep existing (user-provided) definitions under mangled names, so they
# get semantically analyzed.
r_key = get_unique_redefinition_name(key, named_tuple_info.names)
named_tuple_info.names[r_key] = named_tuple_info.names[key]
named_tuple_info.names[key] = value
|
def save_namedtuple_body(self, named_tuple_info: TypeInfo) -> Iterator[None]:
"""Preserve the generated body of class-based named tuple and then restore it.
Temporarily clear the names dict so we don't get errors about duplicate names
that were already set in build_namedtuple_typeinfo (we already added the tuple
field names while generating the TypeInfo, and actual duplicates are
already reported).
"""
nt_names = named_tuple_info.names
named_tuple_info.names = SymbolTable()
yield
# Make sure we didn't use illegal names, then reset the names in the typeinfo.
for prohibited in NAMEDTUPLE_PROHIBITED_NAMES:
if prohibited in named_tuple_info.names:
if nt_names.get(prohibited) is named_tuple_info.names[prohibited]:
continue
ctx = named_tuple_info.names[prohibited].node
assert ctx is not None
self.fail(
'Cannot overwrite NamedTuple attribute "{}"'.format(prohibited), ctx
)
# Restore the names in the original symbol table. This ensures that the symbol
# table contains the field objects created by build_namedtuple_typeinfo. Exclude
# __doc__, which can legally be overwritten by the class.
named_tuple_info.names.update(
{
key: value
for key, value in nt_names.items()
if key not in named_tuple_info.names or key != "__doc__"
}
)
|
https://github.com/python/mypy/issues/6973
|
mypy . --new-semantic-analyzer --show-traceback
./test.py: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.710+dev.16ade15bcd2a5b6b02ad2c76b6b13efa6c2ddf0a
Traceback (most recent call last):
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/main.py", line 88, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 168, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 228, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 2574, in dispatch
process_graph(graph, manager)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 2887, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 2985, in process_stale_scc
semantic_analysis_for_scc(graph, scc, manager.errors)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_main.py", line 80, in semantic_analysis_for_scc
check_type_arguments(graph, scc, errors)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_main.py", line 338, in check_type_arguments
state.tree.accept(analyzer)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 130, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 1832, in wrap_context
yield
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_main.py", line 338, in check_type_arguments
state.tree.accept(analyzer)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 281, in accept
return visitor.visit_mypy_file(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 33, in visit_mypy_file
super().visit_mypy_file(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 33, in visit_mypy_file
d.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 913, in accept
return visitor.visit_class_def(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 44, in visit_class_def
super().visit_class_def(defn)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/mixedtraverser.py", line 28, in visit_class_def
super().visit_class_def(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 65, in visit_class_def
o.defs.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 48, in visit_block
super().visit_block(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 37, in visit_block
s.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 655, in accept
return visitor.visit_func_def(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 52, in visit_func_def
self.visit_func(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 40, in visit_func
super().visit_func(defn)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/mixedtraverser.py", line 23, in visit_func
self.visit_optional_type(o.type)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/mixedtraverser.py", line 91, in visit_optional_type
t.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/types.py", line 975, in accept
return visitor.visit_callable_type(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/typetraverser.py", line 52, in visit_callable_type
t.fallback.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/types.py", line 666, in accept
return visitor.visit_instance(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 54, in visit_instance
for (i, arg), tvar in zip(enumerate(t.args), info.defn.type_vars):
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 2600, in __getattribute__
raise AssertionError(object.__getattribute__(self, 'msg'))
AssertionError: fallback can't be filled out until semanal
./test.py: : note: use --pdb to drop into pdb
|
AssertionError
|
def add_method(
ctx: ClassDefContext,
name: str,
args: List[Argument],
return_type: Type,
self_type: Optional[Type] = None,
tvar_def: Optional[TypeVarDef] = None,
) -> None:
"""Adds a new method to a class."""
info = ctx.cls.info
# First remove any previously generated methods with the same name
# to avoid clashes and problems in new semantic analyzer.
if name in info.names:
sym = info.names[name]
if sym.plugin_generated and isinstance(sym.node, FuncDef):
ctx.cls.defs.body.remove(sym.node)
self_type = self_type or fill_typevars(info)
function_type = ctx.api.named_type("__builtins__.function")
args = [Argument(Var("self"), self_type, None, ARG_POS)] + args
arg_types, arg_names, arg_kinds = [], [], []
for arg in args:
assert arg.type_annotation, "All arguments must be fully typed."
arg_types.append(arg.type_annotation)
arg_names.append(arg.variable.name())
arg_kinds.append(arg.kind)
signature = CallableType(
arg_types, arg_kinds, arg_names, return_type, function_type
)
if tvar_def:
signature.variables = [tvar_def]
func = FuncDef(name, args, Block([PassStmt()]))
func.info = info
func.type = set_callable_name(signature, func)
func._fullname = info.fullname() + "." + name
func.line = info.line
# NOTE: we would like the plugin generated node to dominate, but we still
# need to keep any existing definitions so they get semantically analyzed.
if name in info.names:
# Get a nice unique name instead.
r_name = get_unique_redefinition_name(name, info.names)
info.names[r_name] = info.names[name]
info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True)
info.defn.defs.body.append(func)
|
def add_method(
ctx: ClassDefContext,
name: str,
args: List[Argument],
return_type: Type,
self_type: Optional[Type] = None,
tvar_def: Optional[TypeVarDef] = None,
) -> None:
"""Adds a new method to a class."""
info = ctx.cls.info
# First remove any previously generated methods with the same name
# to avoid clashes and problems in new semantic analyzer.
if name in info.names:
sym = info.names[name]
if sym.plugin_generated and isinstance(sym.node, FuncDef):
ctx.cls.defs.body.remove(sym.node)
self_type = self_type or fill_typevars(info)
function_type = ctx.api.named_type("__builtins__.function")
args = [Argument(Var("self"), self_type, None, ARG_POS)] + args
arg_types, arg_names, arg_kinds = [], [], []
for arg in args:
assert arg.type_annotation, "All arguments must be fully typed."
arg_types.append(arg.type_annotation)
arg_names.append(arg.variable.name())
arg_kinds.append(arg.kind)
signature = CallableType(
arg_types, arg_kinds, arg_names, return_type, function_type
)
if tvar_def:
signature.variables = [tvar_def]
func = FuncDef(name, args, Block([PassStmt()]))
func.info = info
func.type = set_callable_name(signature, func)
func._fullname = info.fullname() + "." + name
func.line = info.line
info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True)
info.defn.defs.body.append(func)
|
https://github.com/python/mypy/issues/6973
|
mypy . --new-semantic-analyzer --show-traceback
./test.py: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.710+dev.16ade15bcd2a5b6b02ad2c76b6b13efa6c2ddf0a
Traceback (most recent call last):
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/main.py", line 88, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 168, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 228, in _build
graph = dispatch(sources, manager, stdout)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 2574, in dispatch
process_graph(graph, manager)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 2887, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 2985, in process_stale_scc
semantic_analysis_for_scc(graph, scc, manager.errors)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_main.py", line 80, in semantic_analysis_for_scc
check_type_arguments(graph, scc, errors)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_main.py", line 338, in check_type_arguments
state.tree.accept(analyzer)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 130, in __exit__
self.gen.throw(type, value, traceback)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/build.py", line 1832, in wrap_context
yield
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_main.py", line 338, in check_type_arguments
state.tree.accept(analyzer)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 281, in accept
return visitor.visit_mypy_file(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 33, in visit_mypy_file
super().visit_mypy_file(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 33, in visit_mypy_file
d.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 913, in accept
return visitor.visit_class_def(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 44, in visit_class_def
super().visit_class_def(defn)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/mixedtraverser.py", line 28, in visit_class_def
super().visit_class_def(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 65, in visit_class_def
o.defs.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 978, in accept
return visitor.visit_block(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 48, in visit_block
super().visit_block(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 37, in visit_block
s.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 655, in accept
return visitor.visit_func_def(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/traverser.py", line 52, in visit_func_def
self.visit_func(o)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 40, in visit_func
super().visit_func(defn)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/mixedtraverser.py", line 23, in visit_func
self.visit_optional_type(o.type)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/mixedtraverser.py", line 91, in visit_optional_type
t.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/types.py", line 975, in accept
return visitor.visit_callable_type(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/typetraverser.py", line 52, in visit_callable_type
t.fallback.accept(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/types.py", line 666, in accept
return visitor.visit_instance(self)
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/newsemanal/semanal_typeargs.py", line 54, in visit_instance
for (i, arg), tvar in zip(enumerate(t.args), info.defn.type_vars):
File "/Users/reinoud/Envs/tmp-4caf160a3041c9e/lib/python3.7/site-packages/mypy/nodes.py", line 2600, in __getattribute__
raise AssertionError(object.__getattribute__(self, 'msg'))
AssertionError: fallback can't be filled out until semanal
./test.py: : note: use --pdb to drop into pdb
|
AssertionError
|
def analyze_unbound_type_without_type_info(
self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool
) -> Type:
"""Figure out what an unbound type that doesn't refer to a TypeInfo node means.
This is something unusual. We try our best to find out what it is.
"""
name = sym.fullname
if name is None:
assert sym.node is not None
name = sym.node.name()
# Option 1:
# Something with an Any type -- make it an alias for Any in a type
# context. This is slightly problematic as it allows using the type 'Any'
# as a base class -- however, this will fail soon at runtime so the problem
# is pretty minor.
if isinstance(sym.node, Var) and isinstance(sym.node.type, AnyType):
return AnyType(
TypeOfAny.from_unimported_type,
missing_import_name=sym.node.type.missing_import_name,
)
# Option 2:
# Unbound type variable. Currently these may be still valid,
# for example when defining a generic type alias.
unbound_tvar = (
isinstance(sym.node, TypeVarExpr) and self.tvar_scope.get_binding(sym) is None
)
if self.allow_unbound_tvars and unbound_tvar:
return t
# Option 3:
# Enum value. Note: we only want to return a LiteralType when
# we're using this enum value specifically within context of
# a "Literal[...]" type. So, if `defining_literal` is not set,
# we bail out early with an error.
#
# If, in the distant future, we decide to permit things like
# `def foo(x: Color.RED) -> None: ...`, we can remove that
# check entirely.
if isinstance(sym.node, Var) and sym.node.info and sym.node.info.is_enum:
value = sym.node.name()
base_enum_short_name = sym.node.info.name()
if not defining_literal:
msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format(
base_enum_short_name, value
)
self.fail(msg, t)
return AnyType(TypeOfAny.from_error)
return LiteralType(
value=value,
fallback=Instance(sym.node.info, [], line=t.line, column=t.column),
line=t.line,
column=t.column,
)
# None of the above options worked. We parse the args (if there are any)
# to make sure there are no remaining semanal-only types, then give up.
t = t.copy_modified(args=self.anal_array(t.args))
self.fail('Invalid type "{}"'.format(name), t)
# TODO: Would it be better to always return Any instead of UnboundType
# in case of an error? On one hand, UnboundType has a name so error messages
# are more detailed, on the other hand, some of them may be bogus.
return t
|
def analyze_unbound_type_without_type_info(
self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool
) -> Type:
"""Figure out what an unbound type that doesn't refer to a TypeInfo node means.
This is something unusual. We try our best to find out what it is.
"""
name = sym.fullname
if name is None:
assert sym.node is not None
name = sym.node.name()
# Option 1:
# Something with an Any type -- make it an alias for Any in a type
# context. This is slightly problematic as it allows using the type 'Any'
# as a base class -- however, this will fail soon at runtime so the problem
# is pretty minor.
if isinstance(sym.node, Var) and isinstance(sym.node.type, AnyType):
return AnyType(
TypeOfAny.from_unimported_type,
missing_import_name=sym.node.type.missing_import_name,
)
# Option 2:
# Unbound type variable. Currently these may be still valid,
# for example when defining a generic type alias.
unbound_tvar = (
isinstance(sym.node, TypeVarExpr) and self.tvar_scope.get_binding(sym) is None
)
if self.allow_unbound_tvars and unbound_tvar:
return t
# Option 3:
# Enum value. Note: we only want to return a LiteralType when
# we're using this enum value specifically within context of
# a "Literal[...]" type. So, if `defining_literal` is not set,
# we bail out early with an error.
#
# If, in the distant future, we decide to permit things like
# `def foo(x: Color.RED) -> None: ...`, we can remove that
# check entirely.
if isinstance(sym.node, Var) and sym.node.info and sym.node.info.is_enum:
value = sym.node.name()
base_enum_short_name = sym.node.info.name()
if not defining_literal:
msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format(
base_enum_short_name, value
)
self.fail(msg, t)
return AnyType(TypeOfAny.from_error)
return LiteralType(
value=value,
fallback=Instance(sym.node.info, [], line=t.line, column=t.column),
line=t.line,
column=t.column,
)
# None of the above options worked, we give up.
self.fail('Invalid type "{}"'.format(name), t)
# TODO: Would it be better to always return Any instead of UnboundType
# in case of an error? On one hand, UnboundType has a name so error messages
# are more detailed, on the other hand, some of them may be bogus.
return t
|
https://github.com/python/mypy/issues/6913
|
resource_manager.py:51: error: Invalid type "mypy_extensions.TypedDict"
resource_manager.py: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/home/babywolf/dev/sd/.venv/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/home/babywolf/dev/sd/.venv/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "mypy/build.py", line 1767, in __mypyc_generator_helper__
File "mypy/build.py", line 2052, in finish_passes
File "mypy/build.py", line 2066, in _patch_indirect_dependencies
File "mypy/indirection.py", line 25, in find_modules
File "mypy/indirection.py", line 34, in _visit
File "mypy/types.py", line 298, in accept
File "mypy/indirection.py", line 39, in visit_unbound_type__TypeVisitor_glue
File "mypy/indirection.py", line 40, in visit_unbound_type
File "mypy/indirection.py", line 34, in _visit
File "mypy/types.py", line 1419, in accept
File "mypy/indirection.py", line 93, in visit_raw_expression_type__SyntheticTypeVisitor_glue
File "mypy/indirection.py", line 94, in visit_raw_expression_type
AssertionError: Unexpected RawExpressionType after semantic analysis phase
resource_manager.py: : note: use --pdb to drop into pdb
|
AssertionError
|
def analyze_unbound_type_without_type_info(
self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool
) -> Type:
"""Figure out what an unbound type that doesn't refer to a TypeInfo node means.
This is something unusual. We try our best to find out what it is.
"""
name = sym.fullname
if name is None:
assert sym.node is not None
name = sym.node.name()
# Option 1:
# Something with an Any type -- make it an alias for Any in a type
# context. This is slightly problematic as it allows using the type 'Any'
# as a base class -- however, this will fail soon at runtime so the problem
# is pretty minor.
if isinstance(sym.node, Var) and isinstance(sym.node.type, AnyType):
return AnyType(
TypeOfAny.from_unimported_type,
missing_import_name=sym.node.type.missing_import_name,
)
# Option 2:
# Unbound type variable. Currently these may be still valid,
# for example when defining a generic type alias.
unbound_tvar = isinstance(sym.node, TypeVarExpr) and (
not self.tvar_scope or self.tvar_scope.get_binding(sym) is None
)
if self.allow_unbound_tvars and unbound_tvar and not self.third_pass:
return t
# Option 3:
# Enum value. Note: we only want to return a LiteralType when
# we're using this enum value specifically within context of
# a "Literal[...]" type. So, if `defining_literal` is not set,
# we bail out early with an error.
#
# If, in the distant future, we decide to permit things like
# `def foo(x: Color.RED) -> None: ...`, we can remove that
# check entirely.
if (
isinstance(sym.node, Var)
and not t.args
and sym.node.info
and sym.node.info.is_enum
):
value = sym.node.name()
base_enum_short_name = sym.node.info.name()
if not defining_literal:
msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format(
base_enum_short_name, value
)
self.fail(msg, t)
return AnyType(TypeOfAny.from_error)
return LiteralType(
value=value,
fallback=Instance(sym.node.info, [], line=t.line, column=t.column),
line=t.line,
column=t.column,
)
# Option 4:
# If it is not something clearly bad (like a known function, variable,
# type variable, or module), and it is still not too late, we try deferring
# this type using a forward reference wrapper. It will be revisited in
# the third pass.
allow_forward_ref = not (
self.third_pass
or isinstance(sym.node, (FuncDef, Decorator, MypyFile, TypeVarExpr))
or (isinstance(sym.node, Var) and sym.node.is_ready)
)
if allow_forward_ref:
# We currently can't support subscripted forward refs in functions;
# see https://github.com/python/mypy/pull/3952#discussion_r139950690
# for discussion.
if t.args and not self.global_scope:
if not self.in_dynamic_func:
self.fail('Unsupported forward reference to "{}"'.format(t.name), t)
return AnyType(TypeOfAny.from_error)
return ForwardRef(t)
# None of the above options worked. We parse the args (if there are any)
# to make sure there are no remaining semanal-only types, then give up.
t = t.copy_modified(args=self.anal_array(t.args))
self.fail('Invalid type "{}"'.format(name), t)
if self.third_pass and isinstance(sym.node, TypeVarExpr):
self.note_func("Forward references to type variables are prohibited", t)
return AnyType(TypeOfAny.from_error)
# TODO: Would it be better to always return Any instead of UnboundType
# in case of an error? On one hand, UnboundType has a name so error messages
# are more detailed, on the other hand, some of them may be bogus.
return t
|
def analyze_unbound_type_without_type_info(
self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool
) -> Type:
"""Figure out what an unbound type that doesn't refer to a TypeInfo node means.
This is something unusual. We try our best to find out what it is.
"""
name = sym.fullname
if name is None:
assert sym.node is not None
name = sym.node.name()
# Option 1:
# Something with an Any type -- make it an alias for Any in a type
# context. This is slightly problematic as it allows using the type 'Any'
# as a base class -- however, this will fail soon at runtime so the problem
# is pretty minor.
if isinstance(sym.node, Var) and isinstance(sym.node.type, AnyType):
return AnyType(
TypeOfAny.from_unimported_type,
missing_import_name=sym.node.type.missing_import_name,
)
# Option 2:
# Unbound type variable. Currently these may be still valid,
# for example when defining a generic type alias.
unbound_tvar = isinstance(sym.node, TypeVarExpr) and (
not self.tvar_scope or self.tvar_scope.get_binding(sym) is None
)
if self.allow_unbound_tvars and unbound_tvar and not self.third_pass:
return t
# Option 3:
# Enum value. Note: we only want to return a LiteralType when
# we're using this enum value specifically within context of
# a "Literal[...]" type. So, if `defining_literal` is not set,
# we bail out early with an error.
#
# If, in the distant future, we decide to permit things like
# `def foo(x: Color.RED) -> None: ...`, we can remove that
# check entirely.
if (
isinstance(sym.node, Var)
and not t.args
and sym.node.info
and sym.node.info.is_enum
):
value = sym.node.name()
base_enum_short_name = sym.node.info.name()
if not defining_literal:
msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format(
base_enum_short_name, value
)
self.fail(msg, t)
return AnyType(TypeOfAny.from_error)
return LiteralType(
value=value,
fallback=Instance(sym.node.info, [], line=t.line, column=t.column),
line=t.line,
column=t.column,
)
# Option 4:
# If it is not something clearly bad (like a known function, variable,
# type variable, or module), and it is still not too late, we try deferring
# this type using a forward reference wrapper. It will be revisited in
# the third pass.
allow_forward_ref = not (
self.third_pass
or isinstance(sym.node, (FuncDef, Decorator, MypyFile, TypeVarExpr))
or (isinstance(sym.node, Var) and sym.node.is_ready)
)
if allow_forward_ref:
# We currently can't support subscripted forward refs in functions;
# see https://github.com/python/mypy/pull/3952#discussion_r139950690
# for discussion.
if t.args and not self.global_scope:
if not self.in_dynamic_func:
self.fail('Unsupported forward reference to "{}"'.format(t.name), t)
return AnyType(TypeOfAny.from_error)
return ForwardRef(t)
# None of the above options worked, we give up.
self.fail('Invalid type "{}"'.format(name), t)
if self.third_pass and isinstance(sym.node, TypeVarExpr):
self.note_func("Forward references to type variables are prohibited", t)
return AnyType(TypeOfAny.from_error)
# TODO: Would it be better to always return Any instead of UnboundType
# in case of an error? On one hand, UnboundType has a name so error messages
# are more detailed, on the other hand, some of them may be bogus.
return t
|
https://github.com/python/mypy/issues/6913
|
resource_manager.py:51: error: Invalid type "mypy_extensions.TypedDict"
resource_manager.py: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.701
Traceback (most recent call last):
File "/home/babywolf/dev/sd/.venv/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/home/babywolf/dev/sd/.venv/lib/python3.7/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "mypy/build.py", line 1767, in __mypyc_generator_helper__
File "mypy/build.py", line 2052, in finish_passes
File "mypy/build.py", line 2066, in _patch_indirect_dependencies
File "mypy/indirection.py", line 25, in find_modules
File "mypy/indirection.py", line 34, in _visit
File "mypy/types.py", line 298, in accept
File "mypy/indirection.py", line 39, in visit_unbound_type__TypeVisitor_glue
File "mypy/indirection.py", line 40, in visit_unbound_type
File "mypy/indirection.py", line 34, in _visit
File "mypy/types.py", line 1419, in accept
File "mypy/indirection.py", line 93, in visit_raw_expression_type__SyntheticTypeVisitor_glue
File "mypy/indirection.py", line 94, in visit_raw_expression_type
AssertionError: Unexpected RawExpressionType after semantic analysis phase
resource_manager.py: : note: use --pdb to drop into pdb
|
AssertionError
|
def false_only(t: Type) -> Type:
"""
Restricted version of t with only False-ish values
"""
if not t.can_be_false:
if state.strict_optional:
# All values of t are True-ish, so there are no false values in it
return UninhabitedType(line=t.line)
else:
# When strict optional checking is disabled, everything can be
# False-ish since anything can be None
return NoneType(line=t.line)
elif not t.can_be_true:
# All values of t are already False-ish, so false_only is idempotent in this case
return t
elif isinstance(t, UnionType):
# The false version of a union type is the union of the false versions of its components
new_items = [false_only(item) for item in t.items]
return UnionType.make_simplified_union(new_items, line=t.line, column=t.column)
else:
new_t = copy_type(t)
new_t.can_be_true = False
return new_t
|
def false_only(t: Type) -> Type:
"""
Restricted version of t with only False-ish values
"""
if not t.can_be_false:
# All values of t are True-ish, so there are no false values in it
return UninhabitedType(line=t.line)
elif not t.can_be_true:
# All values of t are already False-ish, so false_only is idempotent in this case
return t
elif isinstance(t, UnionType):
# The false version of a union type is the union of the false versions of its components
new_items = [false_only(item) for item in t.items]
return UnionType.make_simplified_union(new_items, line=t.line, column=t.column)
else:
new_t = copy_type(t)
new_t.can_be_true = False
return new_t
|
https://github.com/python/mypy/issues/3601
|
$ mypy n.py
n.py:11: error: Incompatible types in assignment (expression has type "int", variable has type "str")
$ python3 n.py
Traceback (most recent call last):
File "n.py", line 23, in <module>
Foo()
File "n.py", line 15, in __init__
self.mypy_does_not_typecheck_this() # no error
AttributeError: 'Foo' object has no attribute 'mypy_does_not_typecheck_this'
|
AttributeError
|
def flatten(t: Expression) -> List[Expression]:
"""Flatten a nested sequence of tuples/lists into one list of nodes."""
if isinstance(t, TupleExpr) or isinstance(t, ListExpr):
return [b for a in t.items for b in flatten(a)]
elif isinstance(t, StarExpr):
return flatten(t.expr)
else:
return [t]
|
def flatten(t: Expression) -> List[Expression]:
"""Flatten a nested sequence of tuples/lists into one list of nodes."""
if isinstance(t, TupleExpr) or isinstance(t, ListExpr):
return [b for a in t.items for b in flatten(a)]
else:
return [t]
|
https://github.com/python/mypy/issues/4986
|
mypy --show-traceback test.py
test.py:3: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.560
Traceback (most recent call last):
File "/Users/trevorbaca/.virtualenvs/abjad3/bin/mypy", line 11, in <module>
sys.exit(console_entry())
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/__main__.py", line 7, in console_entry
main(None)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/main.py", line 66, in main
res = type_check_only(sources, bin_dir, options)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/main.py", line 119, in type_check_only
options=options)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/build.py", line 218, in build
graph = dispatch(sources, manager)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/build.py", line 1997, in dispatch
process_graph(graph, manager)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/build.py", line 2299, in process_graph
process_stale_scc(graph, scc, manager)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/build.py", line 2475, in process_stale_scc
graph[id].type_check_first_pass()
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/build.py", line 1876, in type_check_first_pass
self.type_checker().check_first_pass()
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/checker.py", line 196, in check_first_pass
self.accept(d)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/checker.py", line 286, in accept
stmt.accept(self)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/nodes.py", line 921, in accept
return visitor.visit_if_stmt(self)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/checker.py", line 2181, in visit_if_stmt
t = self.expr_checker.accept(e)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/checkexpr.py", line 2365, in accept
typ = node.accept(self)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/nodes.py", line 1245, in accept
return visitor.visit_call_expr(self)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/checkexpr.py", line 271, in visit_call_expr
self.check_runtime_protocol_test(e)
File "/Users/trevorbaca/.virtualenvs/abjad3/lib/python3.6/site-packages/mypy/checkexpr.py", line 283, in check_runtime_protocol_test
tp = self.chk.type_map[expr]
KeyError: <mypy.nodes.StarExpr object at 0x10cb639b0>
test.py:3: : note: use --pdb to drop into pdb
|
KeyError
|
def find_module_path_and_all_py3(
module: str,
) -> Optional[Tuple[str, Optional[List[str]]]]:
"""Find module and determine __all__ for a Python 3 module.
Return None if the module is a C module. Return (module_path, __all__) if
it is a Python module. Raise CantImport if import failed.
"""
# TODO: Support custom interpreters.
try:
mod = importlib.import_module(module)
except Exception:
raise CantImport(module)
if is_c_module(mod):
return None
module_all = getattr(mod, "__all__", None)
if module_all is not None:
module_all = list(module_all)
return mod.__file__, module_all
|
def find_module_path_and_all_py3(
module: str,
) -> Optional[Tuple[str, Optional[List[str]]]]:
"""Find module and determine __all__ for a Python 3 module.
Return None if the module is a C module. Return (module_path, __all__) if
it is a Python module. Raise CantImport if import failed.
"""
# TODO: Support custom interpreters.
try:
mod = importlib.import_module(module)
except Exception:
raise CantImport(module)
if is_c_module(mod):
return None
return mod.__file__, getattr(mod, "__all__", None)
|
https://github.com/python/mypy/issues/6639
|
Traceback (most recent call last):
File "/Users/peter/.local/share/virtualenvs/testpy-XO9km9Nb/bin/stubgen", line 10, in <module>
sys.exit(main())
File "mypy/stubgen.py", line 1191, in main
File "mypy/stubgen.py", line 1075, in generate_stubs
File "mypy/stubgen.py", line 899, in collect_build_targets
File "mypy/stubgen.py", line 930, in find_module_paths_using_imports
TypeError: tuple object expected
|
TypeError
|
def add_unknown_symbol(
self,
name: str,
context: Context,
is_import: bool = False,
target_name: Optional[str] = None,
) -> None:
"""Add symbol that we don't know what it points to (due to error, for example)."""
var = Var(name)
if self.options.logical_deps and target_name is not None:
# This makes it possible to add logical fine-grained dependencies
# from a missing module. We can't use this by default, since in a
# few places we assume that the full name points to a real
# definition, but this name may point to nothing.
var._fullname = target_name
elif self.type:
var._fullname = self.type.fullname() + "." + name
var.info = self.type
else:
var._fullname = self.qualified_name(name)
var.is_ready = True
if is_import:
any_type = AnyType(
TypeOfAny.from_unimported_type, missing_import_name=var._fullname
)
else:
any_type = AnyType(TypeOfAny.from_error)
var.type = any_type
var.is_suppressed_import = is_import
self.add_symbol(name, var, context)
|
def add_unknown_symbol(
self,
name: str,
context: Context,
is_import: bool = False,
target_name: Optional[str] = None,
) -> None:
"""Add symbol that we don't know what it points to (due to error, for example)."""
var = Var(name)
if self.options.logical_deps and target_name is not None:
# This makes it possible to add logical fine-grained dependencies
# from a missing module. We can't use this by default, since in a
# few places we assume that the full name points to a real
# definition, but this name may point to nothing.
var._fullname = target_name
elif self.type:
var._fullname = self.type.fullname() + "." + name
else:
var._fullname = self.qualified_name(name)
var.is_ready = True
if is_import:
any_type = AnyType(
TypeOfAny.from_unimported_type, missing_import_name=var._fullname
)
else:
any_type = AnyType(TypeOfAny.from_error)
var.type = any_type
var.is_suppressed_import = is_import
self.add_symbol(name, var, context)
|
https://github.com/python/mypy/issues/6367
|
test.py:4: error: Cannot find module named 'dill'
test.py:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports
test.py:13: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.670
Traceback (most recent call last):
File "c:\miniconda3\envs\refactoring\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\miniconda3\envs\refactoring\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Miniconda3\envs\refactoring\Scripts\mypy.exe\__main__.py", line 9, in <module>
sys.exit(console_entry())
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\__main__.py", line 7, in console_entry
main(None)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\main.py", line 91, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 162, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 217, in _build
graph = dispatch(sources, manager)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 2360, in dispatch
process_graph(graph, manager)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 2660, in process_graph
process_stale_scc(graph, scc, manager)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 2767, in process_stale_scc
graph[id].type_check_first_pass()
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 1919, in type_check_first_pass
self.type_checker().check_first_pass()
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 282, in check_first_pass
self.accept(d)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 846, in accept
return visitor.visit_class_def(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1537, in visit_class_def
self.accept(defn.defs)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 606, in accept
return visitor.visit_func_def(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 704, in visit_func_def
self._visit_func_def(defn)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 708, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 770, in check_func_item
self.check_func_def(defn, typ, name)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 932, in check_func_def
self.accept(item.body)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 1102, in accept
return visitor.visit_if_stmt(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 2734, in visit_if_stmt
self.accept(b)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 1102, in accept
return visitor.visit_if_stmt(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 2734, in visit_if_stmt
self.accept(b)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 969, in accept
return visitor.visit_assignment_stmt(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1709, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1828, in check_assignment
in_final_declaration=inferred.is_final,
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkexpr.py", line 3188, in accept
typ = node.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 1398, in accept
return visitor.visit_member_expr(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkexpr.py", line 1761, in visit_member_expr
result = self.analyze_ordinary_member_access(e, is_lvalue)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkexpr.py", line 1776, in analyze_ordinary_member_access
in_literal_context=self.is_literal_context())
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 101, in analyze_member_access
result = _analyze_member_access(name, typ, mx, override_info)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 115, in _analyze_member_access
return analyze_instance_member_access(name, typ, mx, override_info)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 188, in analyze_instance_member_access
return analyze_member_var_access(name, typ, info, mx)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 327, in analyze_member_var_access
return analyze_var(name, v, itype, info, mx, implicit=implicit)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 470, in analyze_var
itype = map_instance_to_supertype(itype, var.info)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\maptype.py", line 20, in map_instance_to_supertype
if not superclass.type_vars:
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 2525, in __getattribute__
raise AssertionError(object.__getattribute__(self, 'msg'))
AssertionError: Var is lacking info
test.py:13: : note: use --pdb to drop into pdb
|
AssertionError
|
def add_unknown_symbol(
self,
name: str,
context: Context,
is_import: bool = False,
target_name: Optional[str] = None,
) -> None:
var = Var(name)
if self.options.logical_deps and target_name is not None:
# This makes it possible to add logical fine-grained dependencies
# from a missing module. We can't use this by default, since in a
# few places we assume that the full name points to a real
# definition, but this name may point to nothing.
var._fullname = target_name
elif self.type:
var._fullname = self.type.fullname() + "." + name
var.info = self.type
else:
var._fullname = self.qualified_name(name)
var.is_ready = True
if is_import:
any_type = AnyType(
TypeOfAny.from_unimported_type, missing_import_name=var._fullname
)
else:
any_type = AnyType(TypeOfAny.from_error)
var.type = any_type
var.is_suppressed_import = is_import
self.add_symbol(name, SymbolTableNode(GDEF, var), context)
|
def add_unknown_symbol(
self,
name: str,
context: Context,
is_import: bool = False,
target_name: Optional[str] = None,
) -> None:
var = Var(name)
if self.options.logical_deps and target_name is not None:
# This makes it possible to add logical fine-grained dependencies
# from a missing module. We can't use this by default, since in a
# few places we assume that the full name points to a real
# definition, but this name may point to nothing.
var._fullname = target_name
elif self.type:
var._fullname = self.type.fullname() + "." + name
else:
var._fullname = self.qualified_name(name)
var.is_ready = True
if is_import:
any_type = AnyType(
TypeOfAny.from_unimported_type, missing_import_name=var._fullname
)
else:
any_type = AnyType(TypeOfAny.from_error)
var.type = any_type
var.is_suppressed_import = is_import
self.add_symbol(name, SymbolTableNode(GDEF, var), context)
|
https://github.com/python/mypy/issues/6367
|
test.py:4: error: Cannot find module named 'dill'
test.py:4: note: See https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports
test.py:13: error: INTERNAL ERROR -- please report a bug at https://github.com/python/mypy/issues version: 0.670
Traceback (most recent call last):
File "c:\miniconda3\envs\refactoring\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "c:\miniconda3\envs\refactoring\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\Miniconda3\envs\refactoring\Scripts\mypy.exe\__main__.py", line 9, in <module>
sys.exit(console_entry())
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\__main__.py", line 7, in console_entry
main(None)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\main.py", line 91, in main
res = build.build(sources, options, None, flush_errors, fscache)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 162, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 217, in _build
graph = dispatch(sources, manager)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 2360, in dispatch
process_graph(graph, manager)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 2660, in process_graph
process_stale_scc(graph, scc, manager)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 2767, in process_stale_scc
graph[id].type_check_first_pass()
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\build.py", line 1919, in type_check_first_pass
self.type_checker().check_first_pass()
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 282, in check_first_pass
self.accept(d)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 846, in accept
return visitor.visit_class_def(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1537, in visit_class_def
self.accept(defn.defs)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 606, in accept
return visitor.visit_func_def(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 704, in visit_func_def
self._visit_func_def(defn)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 708, in _visit_func_def
self.check_func_item(defn, name=defn.name())
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 770, in check_func_item
self.check_func_def(defn, typ, name)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 932, in check_func_def
self.accept(item.body)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 1102, in accept
return visitor.visit_if_stmt(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 2734, in visit_if_stmt
self.accept(b)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 1102, in accept
return visitor.visit_if_stmt(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 2734, in visit_if_stmt
self.accept(b)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 911, in accept
return visitor.visit_block(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1701, in visit_block
self.accept(s)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 393, in accept
stmt.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 969, in accept
return visitor.visit_assignment_stmt(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1709, in visit_assignment_stmt
self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checker.py", line 1828, in check_assignment
in_final_declaration=inferred.is_final,
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkexpr.py", line 3188, in accept
typ = node.accept(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 1398, in accept
return visitor.visit_member_expr(self)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkexpr.py", line 1761, in visit_member_expr
result = self.analyze_ordinary_member_access(e, is_lvalue)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkexpr.py", line 1776, in analyze_ordinary_member_access
in_literal_context=self.is_literal_context())
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 101, in analyze_member_access
result = _analyze_member_access(name, typ, mx, override_info)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 115, in _analyze_member_access
return analyze_instance_member_access(name, typ, mx, override_info)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 188, in analyze_instance_member_access
return analyze_member_var_access(name, typ, info, mx)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 327, in analyze_member_var_access
return analyze_var(name, v, itype, info, mx, implicit=implicit)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\checkmember.py", line 470, in analyze_var
itype = map_instance_to_supertype(itype, var.info)
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\maptype.py", line 20, in map_instance_to_supertype
if not superclass.type_vars:
File "c:\miniconda3\envs\refactoring\lib\site-packages\mypy\nodes.py", line 2525, in __getattribute__
raise AssertionError(object.__getattribute__(self, 'msg'))
AssertionError: Var is lacking info
test.py:13: : note: use --pdb to drop into pdb
|
AssertionError
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.