Skip to content
Open
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
258 changes: 155 additions & 103 deletions mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import mypy.typeops
from mypy.argmap import ArgTypeExpander
from mypy.erasetype import erase_typevars
from mypy.expandtype import expand_type_by_instance
from mypy.expandtype import expand_type, expand_type_by_instance
from mypy.maptype import map_instance_to_supertype
from mypy.nodes import (
ARG_OPT,
Expand Down Expand Up @@ -136,121 +136,165 @@ def infer_constraints_for_callable(
incomplete_star_mapping = True # type: ignore[unreachable]
break

for i, actuals in enumerate(formal_to_actual):
if isinstance(callee.arg_types[i], UnpackType):
unpack_type = callee.arg_types[i]
assert isinstance(unpack_type, UnpackType)

# In this case we are binding all the actuals to *args,
# and we want a constraint that the typevar tuple being unpacked
# is equal to a type list of all the actuals.
actual_types = []

unpacked_type = get_proper_type(unpack_type.type)
if isinstance(unpacked_type, TypeVarTupleType):
tuple_instance = unpacked_type.tuple_fallback
elif isinstance(unpacked_type, TupleType):
tuple_instance = unpacked_type.partial_fallback
else:
assert False, "mypy bug: unhandled constraint inference case"

for actual in actuals:
actual_arg_type = arg_types[actual]
if actual_arg_type is None:
continue
pushed_hint = False
if param_spec is not None and not incomplete_star_mapping:
hint_types: list[Type] = []
hint_names: list[str | None] = []
hint_kinds: list[ArgKind] = []
hint_complete = True
for i, actuals in enumerate(formal_to_actual):
if callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):
for actual in actuals:
actual_arg_type = arg_types[actual]
if actual_arg_type is None:
hint_complete = False
break
hint_types.append(
mapper.expand_actual_type(
actual_arg_type, arg_kinds[actual], None, arg_kinds[actual]
)
)
actual_kind = arg_kinds[actual]
hint_kinds.append(
ARG_POS if actual_kind not in (ARG_STAR, ARG_STAR2) else actual_kind
)
hint_names.append(arg_names[actual] if arg_names else None)
if not hint_complete:
break
if hint_complete:
type_state.param_spec_hints.append(
{
param_spec.id: Parameters(
arg_types=hint_types,
arg_kinds=hint_kinds,
arg_names=hint_names,
imprecise_arg_kinds=True,
)
}
)
pushed_hint = True

try:
for i, actuals in enumerate(formal_to_actual):
if isinstance(callee.arg_types[i], UnpackType):
unpack_type = callee.arg_types[i]
assert isinstance(unpack_type, UnpackType)

# In this case we are binding all the actuals to *args,
# and we want a constraint that the typevar tuple being unpacked
# is equal to a type list of all the actuals.
actual_types = []

unpacked_type = get_proper_type(unpack_type.type)
if isinstance(unpacked_type, TypeVarTupleType):
tuple_instance = unpacked_type.tuple_fallback
elif isinstance(unpacked_type, TupleType):
tuple_instance = unpacked_type.partial_fallback
else:
assert False, "mypy bug: unhandled constraint inference case"

expanded_actual = mapper.expand_actual_type(
actual_arg_type,
arg_kinds[actual],
callee.arg_names[i],
callee.arg_kinds[i],
allow_unpack=True,
)
for actual in actuals:
actual_arg_type = arg_types[actual]
if actual_arg_type is None:
continue

if arg_kinds[actual] != ARG_STAR or isinstance(
get_proper_type(actual_arg_type), TupleType
):
actual_types.append(expanded_actual)
else:
# If we are expanding an iterable inside * actual, append a homogeneous item instead
actual_types.append(
UnpackType(tuple_instance.copy_modified(args=[expanded_actual]))
expanded_actual = mapper.expand_actual_type(
actual_arg_type,
arg_kinds[actual],
callee.arg_names[i],
callee.arg_kinds[i],
allow_unpack=True,
)

if isinstance(unpacked_type, TypeVarTupleType):
constraints.append(
Constraint(
unpacked_type,
SUPERTYPE_OF,
TupleType(actual_types, unpacked_type.tuple_fallback),
)
)
elif isinstance(unpacked_type, TupleType):
# Prefixes get converted to positional args, so technically the only case we
# should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out
# not to hold we can always handle the prefixes too.
inner_unpack = unpacked_type.items[0]
assert isinstance(inner_unpack, UnpackType)
inner_unpacked_type = get_proper_type(inner_unpack.type)
suffix_len = len(unpacked_type.items) - 1
if isinstance(inner_unpacked_type, TypeVarTupleType):
# Variadic item can be either *Ts...
if arg_kinds[actual] != ARG_STAR or isinstance(
get_proper_type(actual_arg_type), TupleType
):
actual_types.append(expanded_actual)
else:
# If we are expanding an iterable inside * actual, append a homogeneous item instead
actual_types.append(
UnpackType(tuple_instance.copy_modified(args=[expanded_actual]))
)

if isinstance(unpacked_type, TypeVarTupleType):
constraints.append(
Constraint(
inner_unpacked_type,
unpacked_type,
SUPERTYPE_OF,
TupleType(
actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback
),
TupleType(actual_types, unpacked_type.tuple_fallback),
)
)
else:
# ...or it can be a homogeneous tuple.
assert (
isinstance(inner_unpacked_type, Instance)
and inner_unpacked_type.type.fullname == "builtins.tuple"
)
for at in actual_types[:-suffix_len]:
constraints.extend(
infer_constraints(inner_unpacked_type.args[0], at, SUPERTYPE_OF)
elif isinstance(unpacked_type, TupleType):
# Prefixes get converted to positional args, so technically the only case we
# should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out
# not to hold we can always handle the prefixes too.
inner_unpack = unpacked_type.items[0]
assert isinstance(inner_unpack, UnpackType)
inner_unpacked_type = get_proper_type(inner_unpack.type)
suffix_len = len(unpacked_type.items) - 1
if isinstance(inner_unpacked_type, TypeVarTupleType):
# Variadic item can be either *Ts...
constraints.append(
Constraint(
inner_unpacked_type,
SUPERTYPE_OF,
TupleType(
actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback
),
)
)
else:
# ...or it can be a homogeneous tuple.
assert (
isinstance(inner_unpacked_type, Instance)
and inner_unpacked_type.type.fullname == "builtins.tuple"
)
# Now handle the suffix (if any).
if suffix_len:
for tt, at in zip(unpacked_type.items[1:], actual_types[-suffix_len:]):
constraints.extend(infer_constraints(tt, at, SUPERTYPE_OF))
for at in actual_types[:-suffix_len]:
constraints.extend(
infer_constraints(inner_unpacked_type.args[0], at, SUPERTYPE_OF)
)
# Now handle the suffix (if any).
if suffix_len:
for tt, at in zip(unpacked_type.items[1:], actual_types[-suffix_len:]):
constraints.extend(infer_constraints(tt, at, SUPERTYPE_OF))
else:
assert False, "mypy bug: unhandled constraint inference case"
else:
assert False, "mypy bug: unhandled constraint inference case"
else:
for actual in actuals:
actual_arg_type = arg_types[actual]
if actual_arg_type is None:
continue
for actual in actuals:
actual_arg_type = arg_types[actual]
if actual_arg_type is None:
continue

if param_spec and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):
# If actual arguments are mapped to ParamSpec type, we can't infer individual
# constraints, instead store them and infer single constraint at the end.
# It is impossible to map actual kind to formal kind, so use some heuristic.
# This inference is used as a fallback, so relying on heuristic should be OK.
if not incomplete_star_mapping:
param_spec_arg_types.append(
mapper.expand_actual_type(
actual_arg_type, arg_kinds[actual], None, arg_kinds[actual]
if param_spec and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):
# If actual arguments are mapped to ParamSpec type, we can't infer individual
# constraints, instead store them and infer single constraint at the end.
# It is impossible to map actual kind to formal kind, so use some heuristic.
# This inference is used as a fallback, so relying on heuristic should be OK.
if not incomplete_star_mapping:
param_spec_arg_types.append(
mapper.expand_actual_type(
actual_arg_type, arg_kinds[actual], None, arg_kinds[actual]
)
)
actual_kind = arg_kinds[actual]
param_spec_arg_kinds.append(
ARG_POS
if actual_kind not in (ARG_STAR, ARG_STAR2)
else actual_kind
)
param_spec_arg_names.append(arg_names[actual] if arg_names else None)
else:
actual_type = mapper.expand_actual_type(
actual_arg_type,
arg_kinds[actual],
callee.arg_names[i],
callee.arg_kinds[i],
)
actual_kind = arg_kinds[actual]
param_spec_arg_kinds.append(
ARG_POS if actual_kind not in (ARG_STAR, ARG_STAR2) else actual_kind
)
param_spec_arg_names.append(arg_names[actual] if arg_names else None)
else:
actual_type = mapper.expand_actual_type(
actual_arg_type,
arg_kinds[actual],
callee.arg_names[i],
callee.arg_kinds[i],
)
c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF)
constraints.extend(c)
c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF)
constraints.extend(c)
finally:
if pushed_hint:
type_state.param_spec_hints.pop()
if (
param_spec
and not any(c.type_var == param_spec.id for c in constraints)
Expand Down Expand Up @@ -1291,7 +1335,15 @@ def infer_against_overloaded(
# the first overload item that is callable compatible. This
# seems to work somewhat well, but we should really use a more
# reliable technique.
item = find_matching_overload_item(overloaded, template)
match_template = template
template_ps = template.param_spec()
if template_ps is not None and type_state.param_spec_hints:
hint = type_state.param_spec_hints[-1].get(template_ps.id)
if hint is not None:
expanded = expand_type(template, {template_ps.id: hint})
if isinstance(expanded, CallableType):
match_template = expanded
item = find_matching_overload_item(overloaded, match_template)
if ret_only:
return infer_constraints(template.ret_type, item.ret_type, self.direction)
return infer_constraints(template, item, self.direction)
Expand Down
4 changes: 4 additions & 0 deletions mypy/typestate.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from mypy.types import (
CallableType,
Instance,
Parameters,
Type,
TypeVarId,
TypeVarLikeType,
Expand Down Expand Up @@ -108,6 +109,8 @@ class TypeState:
_assuming_proper: Final[list[tuple[Type, Type]]]
# Ditto for inference of generic constraints against recursive type aliases.
inferring: Final[list[tuple[Type, Type]]]
# Stack of ParamSpec argument hints from call sites to disambiguate overloaded callables.
param_spec_hints: Final[list[dict[TypeVarId, Parameters]]]
# Whether to use joins or unions when solving constraints, see checkexpr.py for details.
infer_unions: bool
# Whether to use new type inference algorithm that can infer polymorphic types.
Expand Down Expand Up @@ -138,6 +141,7 @@ def __init__(self) -> None:
self._assuming = []
self._assuming_proper = []
self.inferring = []
self.param_spec_hints = []
self.infer_unions = False
self.infer_polymorphic = False
self.keep_unions = False
Expand Down
28 changes: 28 additions & 0 deletions test-data/unit/check-parameter-specification.test
Original file line number Diff line number Diff line change
Expand Up @@ -2848,3 +2848,31 @@ def test(x: C[I]) -> list[int]: ...
ci: C[int]
f: list[int] = apply(test, ci)
[builtins fixtures/paramspec.pyi]

[case testParamSpecTwoSidedOverloadDisambiguation]
from typing import Callable, Protocol, TypeVar, overload
from typing_extensions import ParamSpec

P = ParamSpec("P")
R = TypeVar("R")
T = TypeVar("T")

class OverloadedProto(Protocol):
@overload
def __call__(self, x: int, y: int) -> int: ...
@overload
def __call__(self, x: str, *, flag: bool = False) -> str: ...

@overload
def ov(x: int, y: int) -> int: ...
@overload
def ov(x: str, *, flag: bool = False) -> str: ...
def ov(*args: object, **kwargs: object) -> object: ...

def run(fn: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> list[R]: ...
def unwrap(x: list[T]) -> T: ...

def f(p: OverloadedProto) -> None:
reveal_type(unwrap(run(p, "hello", flag=True))) # N: Revealed type is "builtins.str"
reveal_type(unwrap(run(ov, "hello", flag=True))) # N: Revealed type is "builtins.str"
[builtins fixtures/paramspec.pyi]
Loading