Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix bug with inferring bad arguments to overloads #5660

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 12 additions & 33 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ def check_call(self, callee: Type, args: List[Expression],
callee = self.infer_function_type_arguments(
callee, args, arg_kinds, formal_to_actual, context)

arg_types = self.infer_arg_types_in_context2(
arg_types = self.infer_arg_types_in_context(
callee, args, arg_kinds, formal_to_actual)

self.check_argument_count(callee, arg_types, arg_kinds,
Expand Down Expand Up @@ -655,13 +655,7 @@ def check_call(self, callee: Type, args: List[Expression],
callee = callee.copy_modified(ret_type=ret_type)
return callee.ret_type, callee
elif isinstance(callee, Overloaded):
# Type check arguments in empty context. They will be checked again
# later in a context derived from the signature; these types are
# only used to pick a signature variant.
self.msg.disable_errors()
arg_types = self.infer_arg_types_in_context(None, args)
self.msg.enable_errors()

arg_types = self.infer_arg_types_in_empty_context(args)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At first I was sceptical about this, but after some thinking and playing it seems to me this is actually OK. Because under the hood all relevant possibilities (even the union math) go through infer_overload_return_type, that calls check_call with a CallableType item that, in turn, will trigger infer_arg_types_in_context using current matching overload item arg type as context. So it should be fine.

return self.check_overload_call(callee=callee,
args=args,
arg_types=arg_types,
Expand All @@ -672,7 +666,7 @@ def check_call(self, callee: Type, args: List[Expression],
context=context,
arg_messages=arg_messages)
elif isinstance(callee, AnyType) or not self.chk.in_checked_function():
self.infer_arg_types_in_context(None, args)
self.infer_arg_types_in_empty_context(args)
if isinstance(callee, AnyType):
return (AnyType(TypeOfAny.from_another_any, source_any=callee),
AnyType(TypeOfAny.from_another_any, source_any=callee))
Expand Down Expand Up @@ -744,38 +738,23 @@ def analyze_type_type_callee(self, item: Type, context: Context) -> Type:
self.msg.unsupported_type_type(item, context)
return AnyType(TypeOfAny.from_error)

def infer_arg_types_in_context(self, callee: Optional[CallableType],
args: List[Expression]) -> List[Type]:
"""Infer argument expression types using a callable type as context.
def infer_arg_types_in_empty_context(self, args: List[Expression]) -> List[Type]:
"""Infer argument expression types in an empty context.

For example, if callee argument 2 has type List[int], infer the
argument expression with List[int] type context.
In short, we basically recurse on each argument without considering
in what context the argument was called.
"""
# TODO Always called with callee as None, i.e. empty context.
res = [] # type: List[Type]

fixed = len(args)
if callee:
fixed = min(fixed, callee.max_fixed_args())

ctx = None
for i, arg in enumerate(args):
if i < fixed:
if callee and i < len(callee.arg_types):
ctx = callee.arg_types[i]
arg_type = self.accept(arg, ctx)
else:
if callee and callee.is_var_arg:
arg_type = self.accept(arg, callee.arg_types[-1])
else:
arg_type = self.accept(arg)
for arg in args:
arg_type = self.accept(arg)
if has_erased_component(arg_type):
res.append(NoneTyp())
else:
res.append(arg_type)
return res

def infer_arg_types_in_context2(
def infer_arg_types_in_context(
self, callee: CallableType, args: List[Expression], arg_kinds: List[int],
formal_to_actual: List[List[int]]) -> List[Type]:
"""Infer argument expression types using a callable type as context.
Expand Down Expand Up @@ -859,7 +838,7 @@ def infer_function_type_arguments(self, callee_type: CallableType,
# inferred again later.
self.msg.disable_errors()

arg_types = self.infer_arg_types_in_context2(
arg_types = self.infer_arg_types_in_context(
callee_type, args, arg_kinds, formal_to_actual)

self.msg.enable_errors()
Expand Down Expand Up @@ -933,7 +912,7 @@ def infer_function_type_arguments_pass2(
inferred_args[i] = None
callee_type = self.apply_generic_arguments(callee_type, inferred_args, context)

arg_types = self.infer_arg_types_in_context2(
arg_types = self.infer_arg_types_in_context(
callee_type, args, arg_kinds, formal_to_actual)

inferred_args = infer_function_type_arguments(
Expand Down
73 changes: 73 additions & 0 deletions test-data/unit/check-overloading.test
Original file line number Diff line number Diff line change
Expand Up @@ -4873,3 +4873,76 @@ def g(name: str) -> int:

reveal_type(f) # E: Revealed type is 'def (name: builtins.str) -> builtins.int'
reveal_type(g) # E: Revealed type is 'def (name: builtins.str) -> builtins.int'

[case testOverloadBadArgumentsInferredToAny1]
from typing import Union, Any, overload

def bar(x: int) -> Union[int, Any]: ...

@overload
def foo(x: str) -> None: ...
@overload
def foo(x: int) -> None: ...
def foo(x) -> None: pass

foo(bar('lol')) # E: Argument 1 to "bar" has incompatible type "str"; expected "int"

[case testOverloadBadArgumentsInferredToAny2]
from typing import Union, Iterable, Tuple, TypeVar, Generic, overload, Any

class A:
def foo(self) -> Iterable[int]: pass

def bar(x: int) -> Union[A, int]: ...

_T = TypeVar('_T')

@overload
def foo() -> None: ...
@overload
def foo(iterable: Iterable[_T]) -> None: ...
def foo(iterable = None) -> None: pass

foo(bar('lol').foo()) # E: Argument 1 to "bar" has incompatible type "str"; expected "int" \
# E: Item "int" of "Union[A, int]" has no attribute "foo"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add few tests about situations where absence of context can cause troubles (so that this will not regress). For example something like this:

def g(x: Optional[T] = None) -> List[T]: ...

@overload
def f(x: int) -> int: ...
@overload
def f(x: List[int]) -> List[int]: ...
def f(x):
    pass

reveal_type(f(g()))

I would also add something like

@overload
def g(x: List[str]) -> List[str]: ...
@overload
def g(x: List[int]) -> List[int]: ...
def g(x):
    pass

@overload
def f(x: int) -> int: ...
@overload
def f(x: List[int]) -> List[int]: ...
def f(x):
    pass

reveal_type(f(g([])))

but this one unfortunately causes an error both on master and with this PR. Probably this is something we should fix, but I am afraid this may depend on #4872 (but this is just a guess).

[case testOverloadInferringArgumentsUsingContext1]
from typing import Optional, List, overload, TypeVar
T = TypeVar('T')

def g(x: Optional[T] = None) -> List[T]: ...

@overload
def f(x: int) -> int: ...
@overload
def f(x: List[int]) -> List[int]: ...
def f(x): pass

reveal_type(f(g())) # E: Revealed type is 'builtins.list[builtins.int]'
[builtins fixtures/list.pyi]

[case testOverloadInferringArgumentsUsingContext2-skip]
# This test case ought to work, but is maybe blocked by
# https://github.com/python/mypy/issues/4872?
#
# See https://github.com/python/mypy/pull/5660#discussion_r219669409 for
# more context.

from typing import Optional, List, overload, TypeVar
T = TypeVar('T')
@overload
def g(x: List[str]) -> List[str]: ...
@overload
def g(x: List[int]) -> List[int]: ...
def g(x):
pass

@overload
def f(x: int) -> int: ...
@overload
def f(x: List[int]) -> List[int]: ...
def f(x):
pass

reveal_type(f(g([]))) # E: Revealed type is 'builtins.list[builtins.int]'
[builtins fixtures/list.pyi]