| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from collections.abc import Callable |
| 4 |
|
| 5 |
from mypy import join |
| 6 |
from mypy.erasetype import erase_type |
| 7 |
from mypy.maptype import map_instance_to_supertype |
| 8 |
from mypy.state import state |
| 9 |
from mypy.subtypes import ( |
| 10 |
are_parameters_compatible, |
| 11 |
find_member, |
| 12 |
is_callable_compatible, |
| 13 |
is_equivalent, |
| 14 |
is_proper_subtype, |
| 15 |
is_same_type, |
| 16 |
is_subtype, |
| 17 |
) |
| 18 |
from mypy.typeops import is_recursive_pair, make_simplified_union, tuple_fallback |
| 19 |
from mypy.types import ( |
| 20 |
MYPYC_NATIVE_INT_NAMES, |
| 21 |
TUPLE_LIKE_INSTANCE_NAMES, |
| 22 |
AnyType, |
| 23 |
CallableType, |
| 24 |
DeletedType, |
| 25 |
ErasedType, |
| 26 |
FunctionLike, |
| 27 |
Instance, |
| 28 |
LiteralType, |
| 29 |
NoneType, |
| 30 |
Overloaded, |
| 31 |
Parameters, |
| 32 |
ParamSpecType, |
| 33 |
PartialType, |
| 34 |
ProperType, |
| 35 |
TupleType, |
| 36 |
Type, |
| 37 |
TypeAliasType, |
| 38 |
TypedDictItem, |
| 39 |
TypedDictType, |
| 40 |
TypeGuardedType, |
| 41 |
TypeOfAny, |
| 42 |
TypeType, |
| 43 |
TypeVarLikeType, |
| 44 |
TypeVarTupleType, |
| 45 |
TypeVarType, |
| 46 |
TypeVisitor, |
| 47 |
UnboundType, |
| 48 |
UninhabitedType, |
| 49 |
UnionType, |
| 50 |
UnpackType, |
| 51 |
find_unpack_in_list, |
| 52 |
get_proper_type, |
| 53 |
get_proper_types, |
| 54 |
has_type_vars, |
| 55 |
is_named_instance, |
| 56 |
split_with_prefix_and_suffix, |
| 57 |
) |
| 58 |
|
| 59 |
# TODO Describe this module. |
| 60 |
|
| 61 |
|
| 62 |
def trivial_meet(s: Type, t: Type) -> ProperType: |
| 63 |
"""Return one of types (expanded) if it is a subtype of other, otherwise bottom type.""" |
| 64 |
if is_subtype(s, t): |
| 65 |
return get_proper_type(s) |
| 66 |
elif is_subtype(t, s): |
| 67 |
return get_proper_type(t) |
| 68 |
else: |
| 69 |
if state.strict_optional: |
| 70 |
return UninhabitedType() |
| 71 |
else: |
| 72 |
return NoneType() |
| 73 |
|
| 74 |
|
| 75 |
def meet_types(s: Type, t: Type) -> ProperType: |
| 76 |
"""Return the greatest lower bound of two types.""" |
| 77 |
if is_recursive_pair(s, t): |
| 78 |
# This case can trigger an infinite recursion, general support for this will be |
| 79 |
# tricky, so we use a trivial meet (like for protocols). |
| 80 |
return trivial_meet(s, t) |
| 81 |
s = get_proper_type(s) |
| 82 |
t = get_proper_type(t) |
| 83 |
|
| 84 |
if isinstance(s, Instance) and isinstance(t, Instance) and s.type == t.type: |
| 85 |
# Code in checker.py should merge any extra_items where possible, so we |
| 86 |
# should have only compatible extra_items here. We check this before |
| 87 |
# the below subtype check, so that extra_attrs will not get erased. |
| 88 |
if (s.extra_attrs or t.extra_attrs) and is_same_type(s, t): |
| 89 |
if s.extra_attrs and t.extra_attrs: |
| 90 |
if len(s.extra_attrs.attrs) > len(t.extra_attrs.attrs): |
| 91 |
# Return the one that has more precise information. |
| 92 |
return s |
| 93 |
return t |
| 94 |
if s.extra_attrs: |
| 95 |
return s |
| 96 |
return t |
| 97 |
|
| 98 |
if not isinstance(s, UnboundType) and not isinstance(t, UnboundType): |
| 99 |
if is_proper_subtype(s, t, ignore_promotions=True): |
| 100 |
return s |
| 101 |
if is_proper_subtype(t, s, ignore_promotions=True): |
| 102 |
return t |
| 103 |
|
| 104 |
if isinstance(s, ErasedType): |
| 105 |
return s |
| 106 |
if isinstance(s, AnyType): |
| 107 |
return t |
| 108 |
if isinstance(s, UnionType) and not isinstance(t, UnionType): |
| 109 |
s, t = t, s |
| 110 |
|
| 111 |
# Meets/joins require callable type normalization. |
| 112 |
s, t = join.normalize_callables(s, t) |
| 113 |
|
| 114 |
return t.accept(TypeMeetVisitor(s)) |
| 115 |
|
| 116 |
|
| 117 |
def narrow_declared_type(declared: Type, narrowed: Type) -> Type: |
| 118 |
"""Return the declared type narrowed down to another type.""" |
| 119 |
# TODO: check infinite recursion for aliases here. |
| 120 |
if isinstance(narrowed, TypeGuardedType): |
| 121 |
# A type guard forces the new type even if it doesn't overlap the old... |
| 122 |
if is_proper_subtype(declared, narrowed.type_guard, ignore_promotions=True): |
| 123 |
# ...unless it is a proper supertype of declared type. |
| 124 |
return declared |
| 125 |
return narrowed.type_guard |
| 126 |
|
| 127 |
original_declared = declared |
| 128 |
original_narrowed = narrowed |
| 129 |
declared = get_proper_type(declared) |
| 130 |
narrowed = get_proper_type(narrowed) |
| 131 |
|
| 132 |
if declared == narrowed: |
| 133 |
return original_declared |
| 134 |
if isinstance(declared, UnionType): |
| 135 |
declared_items = declared.relevant_items() |
| 136 |
if isinstance(narrowed, UnionType): |
| 137 |
narrowed_items = narrowed.relevant_items() |
| 138 |
else: |
| 139 |
narrowed_items = [narrowed] |
| 140 |
return make_simplified_union( |
| 141 |
[ |
| 142 |
narrow_declared_type(d, n) |
| 143 |
for d in declared_items |
| 144 |
for n in narrowed_items |
| 145 |
# This (ugly) special-casing is needed to support checking |
| 146 |
# branches like this: |
| 147 |
# x: Union[float, complex] |
| 148 |
# if isinstance(x, int): |
| 149 |
# ... |
| 150 |
# And assignments like this: |
| 151 |
# x: float | None |
| 152 |
# y: int | None |
| 153 |
# x = y |
| 154 |
if ( |
| 155 |
is_overlapping_types(d, n, ignore_promotions=True) |
| 156 |
or is_subtype(n, d, ignore_promotions=False) |
| 157 |
) |
| 158 |
] |
| 159 |
) |
| 160 |
if is_enum_overlapping_union(declared, narrowed): |
| 161 |
# Quick check before reaching `is_overlapping_types`. If it's enum/literal overlap, |
| 162 |
# avoid full expansion and make it faster. |
| 163 |
assert isinstance(narrowed, UnionType) |
| 164 |
return make_simplified_union( |
| 165 |
[narrow_declared_type(declared, x) for x in narrowed.relevant_items()] |
| 166 |
) |
| 167 |
elif ( |
| 168 |
isinstance(declared, TypeVarType) |
| 169 |
and not has_type_vars(original_narrowed) |
| 170 |
and is_subtype(original_narrowed, declared.upper_bound) |
| 171 |
): |
| 172 |
# We put this branch early to get T(bound=Union[A, B]) instead of |
| 173 |
# Union[T(bound=A), T(bound=B)] that will be confusing for users. |
| 174 |
return declared.copy_modified( |
| 175 |
upper_bound=narrow_declared_type(declared.upper_bound, original_narrowed) |
| 176 |
) |
| 177 |
elif ( |
| 178 |
isinstance(narrowed, TypeVarType) |
| 179 |
and not has_type_vars(original_declared) |
| 180 |
and is_subtype(original_declared, narrowed.upper_bound) |
| 181 |
): |
| 182 |
# This branch is a mirror image of the above one. |
| 183 |
return narrowed.copy_modified( |
| 184 |
upper_bound=narrow_declared_type(original_declared, narrowed.upper_bound) |
| 185 |
) |
| 186 |
elif not is_overlapping_types(declared, narrowed): |
| 187 |
if state.strict_optional: |
| 188 |
return UninhabitedType() |
| 189 |
else: |
| 190 |
return NoneType() |
| 191 |
elif isinstance(narrowed, UnionType): |
| 192 |
return make_simplified_union( |
| 193 |
[narrow_declared_type(declared, x) for x in narrowed.relevant_items()] |
| 194 |
) |
| 195 |
elif isinstance(narrowed, AnyType): |
| 196 |
return original_narrowed |
| 197 |
elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared): |
| 198 |
return narrowed |
| 199 |
elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType): |
| 200 |
return TypeType.make_normalized( |
| 201 |
narrow_declared_type(declared.item, narrowed.item), |
| 202 |
is_type_form=declared.is_type_form and narrowed.is_type_form, |
| 203 |
) |
| 204 |
elif ( |
| 205 |
isinstance(declared, TypeType) |
| 206 |
and isinstance(narrowed, Instance) |
| 207 |
and narrowed.type.is_metaclass() |
| 208 |
): |
| 209 |
if declared.is_type_form: |
| 210 |
# The declared TypeForm[T] after narrowing must be a kind of |
| 211 |
# type object at least as narrow as Type[T] |
| 212 |
return narrow_declared_type( |
| 213 |
TypeType.make_normalized( |
| 214 |
declared.item, line=declared.line, column=declared.column, is_type_form=False |
| 215 |
), |
| 216 |
original_narrowed, |
| 217 |
) |
| 218 |
# We'd need intersection types, so give up. |
| 219 |
return original_declared |
| 220 |
elif isinstance(declared, Instance): |
| 221 |
if declared.type.alt_promote: |
| 222 |
# Special case: low-level integer type can't be narrowed |
| 223 |
return original_declared |
| 224 |
if ( |
| 225 |
isinstance(narrowed, Instance) |
| 226 |
and narrowed.type.alt_promote |
| 227 |
and narrowed.type.alt_promote.type is declared.type |
| 228 |
): |
| 229 |
# Special case: 'int' can't be narrowed down to a native int type such as |
| 230 |
# i64, since they have different runtime representations. |
| 231 |
return original_declared |
| 232 |
return meet_types(original_declared, original_narrowed) |
| 233 |
elif isinstance(declared, (TupleType, TypeType, LiteralType)): |
| 234 |
return meet_types(original_declared, original_narrowed) |
| 235 |
elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance): |
| 236 |
# Special case useful for selecting TypedDicts from unions using isinstance(x, dict). |
| 237 |
if narrowed.type.fullname == "builtins.dict" and all( |
| 238 |
isinstance(t, AnyType) for t in get_proper_types(narrowed.args) |
| 239 |
): |
| 240 |
return original_declared |
| 241 |
return meet_types(original_declared, original_narrowed) |
| 242 |
elif ( |
| 243 |
isinstance(declared, CallableType) |
| 244 |
and isinstance(narrowed, CallableType) |
| 245 |
and has_type_vars(declared.ret_type) |
| 246 |
): |
| 247 |
return narrowed.copy_modified( |
| 248 |
ret_type=narrow_declared_type(declared.ret_type, narrowed.ret_type) |
| 249 |
) |
| 250 |
|
| 251 |
return original_narrowed |
| 252 |
|
| 253 |
|
| 254 |
def get_possible_variants(typ: Type) -> list[Type]: |
| 255 |
"""This function takes any "Union-like" type and returns a list of the available "options". |
| 256 |
|
| 257 |
Specifically, there are currently exactly three different types that can have |
| 258 |
"variants" or are "union-like": |
| 259 |
|
| 260 |
- Unions |
| 261 |
- TypeVars with value restrictions |
| 262 |
- Overloads |
| 263 |
|
| 264 |
This function will return a list of each "option" present in those types. |
| 265 |
|
| 266 |
If this function receives any other type, we return a list containing just that |
| 267 |
original type. (E.g. pretend the type was contained within a singleton union). |
| 268 |
|
| 269 |
The only current exceptions are regular TypeVars and ParamSpecs. For these "TypeVarLike"s, |
| 270 |
we return a list containing that TypeVarLike's upper bound. |
| 271 |
|
| 272 |
This function is useful primarily when checking to see if two types are overlapping: |
| 273 |
the algorithm to check if two unions are overlapping is fundamentally the same as |
| 274 |
the algorithm for checking if two overloads are overlapping. |
| 275 |
|
| 276 |
Normalizing both kinds of types in the same way lets us reuse the same algorithm |
| 277 |
for both. |
| 278 |
""" |
| 279 |
typ = get_proper_type(typ) |
| 280 |
|
| 281 |
if isinstance(typ, TypeVarType): |
| 282 |
if len(typ.values) > 0: |
| 283 |
return typ.values |
| 284 |
else: |
| 285 |
return [typ.upper_bound] |
| 286 |
elif isinstance(typ, ParamSpecType): |
| 287 |
# Extract 'object' from the final mro item |
| 288 |
upper_bound = get_proper_type(typ.upper_bound) |
| 289 |
if isinstance(upper_bound, Instance): |
| 290 |
return [Instance(upper_bound.type.mro[-1], [])] |
| 291 |
return [AnyType(TypeOfAny.implementation_artifact)] |
| 292 |
elif isinstance(typ, TypeVarTupleType): |
| 293 |
return [typ.upper_bound] |
| 294 |
elif isinstance(typ, UnionType): |
| 295 |
return list(typ.items) |
| 296 |
elif isinstance(typ, Overloaded): |
| 297 |
# Note: doing 'return typ.items()' makes mypy |
| 298 |
# infer a too-specific return type of List[CallableType] |
| 299 |
return list(typ.items) |
| 300 |
else: |
| 301 |
return [typ] |
| 302 |
|
| 303 |
|
| 304 |
def is_enum_overlapping_union(x: ProperType, y: ProperType) -> bool: |
| 305 |
"""Return True if x is an Enum, and y is an Union with at least one Literal from x""" |
| 306 |
return ( |
| 307 |
isinstance(x, Instance) |
| 308 |
and x.type.is_enum |
| 309 |
and isinstance(y, UnionType) |
| 310 |
and any( |
| 311 |
isinstance(p := get_proper_type(z), LiteralType) and x.type == p.fallback.type |
| 312 |
for z in y.relevant_items() |
| 313 |
) |
| 314 |
) |
| 315 |
|
| 316 |
|
| 317 |
def is_literal_in_union(x: ProperType, y: ProperType) -> bool: |
| 318 |
"""Return True if x is a Literal and y is an Union that includes x""" |
| 319 |
return ( |
| 320 |
isinstance(x, LiteralType) |
| 321 |
and isinstance(y, UnionType) |
| 322 |
and any(x == get_proper_type(z) for z in y.items) |
| 323 |
) |
| 324 |
|
| 325 |
|
| 326 |
def is_object(t: ProperType) -> bool: |
| 327 |
return isinstance(t, Instance) and t.type.fullname == "builtins.object" |
| 328 |
|
| 329 |
|
| 330 |
def is_none_object_overlap(t1: ProperType, t2: ProperType) -> bool: |
| 331 |
return ( |
| 332 |
isinstance(t1, NoneType) |
| 333 |
and isinstance(t2, Instance) |
| 334 |
and t2.type.fullname == "builtins.object" |
| 335 |
) |
| 336 |
|
| 337 |
|
| 338 |
def are_related_types( |
| 339 |
left: Type, right: Type, *, proper_subtype: bool, ignore_promotions: bool |
| 340 |
) -> bool: |
| 341 |
if proper_subtype: |
| 342 |
return is_proper_subtype( |
| 343 |
left, right, ignore_promotions=ignore_promotions |
| 344 |
) or is_proper_subtype(right, left, ignore_promotions=ignore_promotions) |
| 345 |
else: |
| 346 |
return is_subtype(left, right, ignore_promotions=ignore_promotions) or is_subtype( |
| 347 |
right, left, ignore_promotions=ignore_promotions |
| 348 |
) |
| 349 |
|
| 350 |
|
| 351 |
def is_overlapping_types( |
| 352 |
left: Type, |
| 353 |
right: Type, |
| 354 |
ignore_promotions: bool = False, |
| 355 |
overlap_for_overloads: bool = False, |
| 356 |
seen_types: set[tuple[Type, Type]] | None = None, |
| 357 |
) -> bool: |
| 358 |
"""Can a value of type 'left' also be of type 'right' or vice-versa? |
| 359 |
|
| 360 |
If 'ignore_promotions' is True, we ignore promotions while checking for overlaps. |
| 361 |
If 'overlap_for_overloads' is True, we check for overlaps more strictly (to avoid false |
| 362 |
positives), for example: None only overlaps with explicitly optional types, Any |
| 363 |
doesn't overlap with anything except object, we don't ignore positional argument names. |
| 364 |
""" |
| 365 |
if isinstance(left, TypeGuardedType) or isinstance(right, TypeGuardedType): |
| 366 |
# A type guard forces the new type even if it doesn't overlap the old. |
| 367 |
return True |
| 368 |
|
| 369 |
if seen_types is None: |
| 370 |
seen_types = set() |
| 371 |
elif (left, right) in seen_types: |
| 372 |
return True |
| 373 |
if is_recursive_pair(left, right): |
| 374 |
seen_types.add((left, right)) |
| 375 |
|
| 376 |
left, right = get_proper_types((left, right)) |
| 377 |
|
| 378 |
# We should never encounter this type. |
| 379 |
if isinstance(left, PartialType) or isinstance(right, PartialType): |
| 380 |
assert False, "Unexpectedly encountered partial type" |
| 381 |
|
| 382 |
# We should also never encounter these types, but it's possible a few |
| 383 |
# have snuck through due to unrelated bugs. For now, we handle these |
| 384 |
# in the same way we handle 'Any'. |
| 385 |
# |
| 386 |
# TODO: Replace these with an 'assert False' once we are more confident. |
| 387 |
illegal_types = (UnboundType, ErasedType, DeletedType) |
| 388 |
if isinstance(left, illegal_types) or isinstance(right, illegal_types): |
| 389 |
return True |
| 390 |
|
| 391 |
# When running under non-strict optional mode, simplify away types of |
| 392 |
# the form 'Union[A, B, C, None]' into just 'Union[A, B, C]'. |
| 393 |
|
| 394 |
if not state.strict_optional: |
| 395 |
if isinstance(left, UnionType): |
| 396 |
left = UnionType.make_union(left.relevant_items()) |
| 397 |
if isinstance(right, UnionType): |
| 398 |
right = UnionType.make_union(right.relevant_items()) |
| 399 |
left, right = get_proper_types((left, right)) |
| 400 |
|
| 401 |
# 'Any' may or may not be overlapping with the other type |
| 402 |
if isinstance(left, AnyType) or isinstance(right, AnyType): |
| 403 |
return not overlap_for_overloads or is_object(left) or is_object(right) |
| 404 |
|
| 405 |
# We check for complete overlaps next as a general-purpose failsafe. |
| 406 |
# If this check fails, we start checking to see if there exists a |
| 407 |
# *partial* overlap between types. |
| 408 |
# |
| 409 |
# These checks will also handle the NoneType and UninhabitedType cases for us. |
| 410 |
|
| 411 |
# enums are sometimes expanded into an Union of Literals |
| 412 |
# when that happens we want to make sure we treat the two as overlapping |
| 413 |
# and crucially, we want to do that *fast* in case the enum is large |
| 414 |
# so we do it before expanding variants below to avoid O(n**2) behavior |
| 415 |
if ( |
| 416 |
is_enum_overlapping_union(left, right) |
| 417 |
or is_enum_overlapping_union(right, left) |
| 418 |
or is_literal_in_union(left, right) |
| 419 |
or is_literal_in_union(right, left) |
| 420 |
): |
| 421 |
return True |
| 422 |
|
| 423 |
if overlap_for_overloads: |
| 424 |
if is_none_object_overlap(left, right) or is_none_object_overlap(right, left): |
| 425 |
return False |
| 426 |
|
| 427 |
if are_related_types( |
| 428 |
left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions |
| 429 |
): |
| 430 |
return True |
| 431 |
|
| 432 |
# See the docstring for 'get_possible_variants' for more info on what the |
| 433 |
# following lines are doing. |
| 434 |
|
| 435 |
left_possible = get_possible_variants(left) |
| 436 |
right_possible = get_possible_variants(right) |
| 437 |
|
| 438 |
# Now move on to checking multi-variant types like Unions. We also perform |
| 439 |
# the same logic if either type happens to be a TypeVar/ParamSpec/TypeVarTuple. |
| 440 |
# |
| 441 |
# Handling the TypeVarLikes now lets us simulate having them bind to the corresponding |
| 442 |
# type -- if we deferred these checks, the "return-early" logic of the other |
| 443 |
# checks will prevent us from detecting certain overlaps. |
| 444 |
# |
| 445 |
# If both types are singleton variants (and are not TypeVarLikes), we've hit the base case: |
| 446 |
# we skip these checks to avoid infinitely recursing. |
| 447 |
|
| 448 |
def _is_overlapping_types(left: Type, right: Type) -> bool: |
| 449 |
"""Encode the kind of overlapping check to perform. |
| 450 |
|
| 451 |
This function mostly exists, so we don't have to repeat keyword arguments everywhere. |
| 452 |
""" |
| 453 |
return is_overlapping_types( |
| 454 |
left, |
| 455 |
right, |
| 456 |
ignore_promotions=ignore_promotions, |
| 457 |
overlap_for_overloads=overlap_for_overloads, |
| 458 |
seen_types=seen_types.copy(), |
| 459 |
) |
| 460 |
|
| 461 |
if ( |
| 462 |
len(left_possible) > 1 |
| 463 |
or len(right_possible) > 1 |
| 464 |
or isinstance(left, TypeVarLikeType) |
| 465 |
or isinstance(right, TypeVarLikeType) |
| 466 |
): |
| 467 |
for l in left_possible: |
| 468 |
for r in right_possible: |
| 469 |
if _is_overlapping_types(l, r): |
| 470 |
return True |
| 471 |
return False |
| 472 |
|
| 473 |
# Now that we've finished handling TypeVarLikes, we're free to end early |
| 474 |
# if one one of the types is None and we're running in strict-optional mode. |
| 475 |
# (None only overlaps with None in strict-optional mode). |
| 476 |
# |
| 477 |
# We must perform this check after the TypeVarLike checks because |
| 478 |
# a TypeVar could be bound to None, for example. |
| 479 |
|
| 480 |
if state.strict_optional and isinstance(left, NoneType) != isinstance(right, NoneType): |
| 481 |
return False |
| 482 |
|
| 483 |
# Next, we handle single-variant types that may be inherently partially overlapping: |
| 484 |
# |
| 485 |
# - TypedDicts |
| 486 |
# - Tuples |
| 487 |
# |
| 488 |
# If we cannot identify a partial overlap and end early, we degrade these two types |
| 489 |
# into their 'Instance' fallbacks. |
| 490 |
|
| 491 |
if isinstance(left, TypedDictType) and isinstance(right, TypedDictType): |
| 492 |
return are_typed_dicts_overlapping(left, right, _is_overlapping_types) |
| 493 |
elif typed_dict_mapping_pair(left, right): |
| 494 |
# Overlaps between TypedDicts and Mappings require dedicated logic. |
| 495 |
return typed_dict_mapping_overlap(left, right, overlapping=_is_overlapping_types) |
| 496 |
elif isinstance(left, TypedDictType): |
| 497 |
left = left.fallback |
| 498 |
elif isinstance(right, TypedDictType): |
| 499 |
right = right.fallback |
| 500 |
|
| 501 |
if is_tuple(left) and is_tuple(right): |
| 502 |
return are_tuples_overlapping(left, right, _is_overlapping_types) |
| 503 |
elif isinstance(left, TupleType): |
| 504 |
left = tuple_fallback(left) |
| 505 |
elif isinstance(right, TupleType): |
| 506 |
right = tuple_fallback(right) |
| 507 |
|
| 508 |
# Next, we handle single-variant types that cannot be inherently partially overlapping, |
| 509 |
# but do require custom logic to inspect. |
| 510 |
# |
| 511 |
# As before, we degrade into 'Instance' whenever possible. |
| 512 |
|
| 513 |
if isinstance(left, TypeType) and isinstance(right, TypeType): |
| 514 |
return _is_overlapping_types(left.item, right.item) |
| 515 |
|
| 516 |
if isinstance(left, TypeType) or isinstance(right, TypeType): |
| 517 |
|
| 518 |
def _type_object_overlap(left: Type, right: Type) -> bool: |
| 519 |
"""Special cases for type object types overlaps.""" |
| 520 |
# TODO: these checks are a bit in gray area, adjust if they cause problems. |
| 521 |
left, right = get_proper_types((left, right)) |
| 522 |
# 1. Type[C] vs Callable[..., C] overlap even if the latter is not class object. |
| 523 |
if isinstance(left, TypeType) and isinstance(right, CallableType): |
| 524 |
return _is_overlapping_types(left.item, right.ret_type) |
| 525 |
# 2. Type[C] vs Meta, where Meta is a metaclass for C. |
| 526 |
if isinstance(left, TypeType) and isinstance(right, Instance): |
| 527 |
if isinstance(left.item, Instance): |
| 528 |
left_meta = left.item.type.metaclass_type |
| 529 |
if left_meta is not None: |
| 530 |
return _is_overlapping_types(left_meta, right) |
| 531 |
# builtins.type (default metaclass) overlaps with all metaclasses |
| 532 |
return right.type.has_base("builtins.type") |
| 533 |
elif isinstance(left.item, AnyType): |
| 534 |
return right.type.has_base("builtins.type") |
| 535 |
# 3. Callable[..., C] vs Meta is considered below, when we switch to fallbacks. |
| 536 |
return False |
| 537 |
|
| 538 |
return _type_object_overlap(left, right) or _type_object_overlap(right, left) |
| 539 |
|
| 540 |
if isinstance(left, Parameters) and isinstance(right, Parameters): |
| 541 |
return are_parameters_compatible( |
| 542 |
left, |
| 543 |
right, |
| 544 |
is_compat=_is_overlapping_types, |
| 545 |
is_proper_subtype=False, |
| 546 |
ignore_pos_arg_names=not overlap_for_overloads, |
| 547 |
allow_partial_overlap=True, |
| 548 |
) |
| 549 |
# A `Parameters` does not overlap with anything else, however |
| 550 |
if isinstance(left, Parameters) or isinstance(right, Parameters): |
| 551 |
return False |
| 552 |
|
| 553 |
if isinstance(left, CallableType) and isinstance(right, CallableType): |
| 554 |
# We run is_callable_compatible in both directions, similar to the logic |
| 555 |
# in is_unsafe_overlapping_overload_signatures |
| 556 |
# See comments in https://github.com/python/mypy/pull/5476 |
| 557 |
return is_callable_compatible( |
| 558 |
left, |
| 559 |
right, |
| 560 |
is_compat=_is_overlapping_types, |
| 561 |
is_proper_subtype=False, |
| 562 |
ignore_pos_arg_names=not overlap_for_overloads, |
| 563 |
allow_partial_overlap=True, |
| 564 |
) or is_callable_compatible( |
| 565 |
right, |
| 566 |
left, |
| 567 |
is_compat=_is_overlapping_types, |
| 568 |
is_proper_subtype=False, |
| 569 |
ignore_pos_arg_names=not overlap_for_overloads, |
| 570 |
check_args_covariantly=True, |
| 571 |
allow_partial_overlap=True, |
| 572 |
) |
| 573 |
|
| 574 |
call = None |
| 575 |
other = None |
| 576 |
if isinstance(left, CallableType) and isinstance(right, Instance): |
| 577 |
call = find_member("__call__", right, right, is_operator=True) |
| 578 |
other = left |
| 579 |
if isinstance(right, CallableType) and isinstance(left, Instance): |
| 580 |
call = find_member("__call__", left, left, is_operator=True) |
| 581 |
other = right |
| 582 |
if isinstance(get_proper_type(call), FunctionLike): |
| 583 |
assert call is not None and other is not None |
| 584 |
return _is_overlapping_types(call, other) |
| 585 |
|
| 586 |
if isinstance(left, CallableType): |
| 587 |
left = left.fallback |
| 588 |
if isinstance(right, CallableType): |
| 589 |
right = right.fallback |
| 590 |
|
| 591 |
if isinstance(left, LiteralType) and isinstance(right, LiteralType): |
| 592 |
if left.value == right.value: |
| 593 |
# If values are the same, we still need to check if fallbacks are overlapping, |
| 594 |
# this is done below. |
| 595 |
left = left.fallback |
| 596 |
right = right.fallback |
| 597 |
else: |
| 598 |
return False |
| 599 |
elif isinstance(left, LiteralType): |
| 600 |
left = left.fallback |
| 601 |
elif isinstance(right, LiteralType): |
| 602 |
right = right.fallback |
| 603 |
|
| 604 |
# Finally, we handle the case where left and right are instances. |
| 605 |
|
| 606 |
if isinstance(left, Instance) and isinstance(right, Instance): |
| 607 |
# First we need to handle promotions and structural compatibility for instances |
| 608 |
# that came as fallbacks, so simply call is_subtype() to avoid code duplication. |
| 609 |
if are_related_types( |
| 610 |
left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions |
| 611 |
): |
| 612 |
return True |
| 613 |
|
| 614 |
if right.type.fullname == "builtins.int" and left.type.fullname in MYPYC_NATIVE_INT_NAMES: |
| 615 |
return True |
| 616 |
|
| 617 |
# Two unrelated types cannot be partially overlapping: they're disjoint. |
| 618 |
if left.type.has_base(right.type.fullname): |
| 619 |
left = map_instance_to_supertype(left, right.type) |
| 620 |
elif right.type.has_base(left.type.fullname): |
| 621 |
right = map_instance_to_supertype(right, left.type) |
| 622 |
else: |
| 623 |
return False |
| 624 |
|
| 625 |
if right.type.has_type_var_tuple_type: |
| 626 |
# Similar to subtyping, we delegate the heavy lifting to the tuple overlap. |
| 627 |
assert right.type.type_var_tuple_prefix is not None |
| 628 |
assert right.type.type_var_tuple_suffix is not None |
| 629 |
prefix = right.type.type_var_tuple_prefix |
| 630 |
suffix = right.type.type_var_tuple_suffix |
| 631 |
tvt = right.type.defn.type_vars[prefix] |
| 632 |
assert isinstance(tvt, TypeVarTupleType) |
| 633 |
fallback = tvt.tuple_fallback |
| 634 |
left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix( |
| 635 |
left.args, prefix, suffix |
| 636 |
) |
| 637 |
right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix( |
| 638 |
right.args, prefix, suffix |
| 639 |
) |
| 640 |
left_args = left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix |
| 641 |
right_args = right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix |
| 642 |
else: |
| 643 |
left_args = left.args |
| 644 |
right_args = right.args |
| 645 |
if len(left_args) == len(right_args): |
| 646 |
# Note: we don't really care about variance here, since the overlapping check |
| 647 |
# is symmetric and since we want to return 'True' even for partial overlaps. |
| 648 |
# |
| 649 |
# For example, suppose we have two types Wrapper[Parent] and Wrapper[Child]. |
| 650 |
# It doesn't matter whether Wrapper is covariant or contravariant since |
| 651 |
# either way, one of the two types will overlap with the other. |
| 652 |
# |
| 653 |
# Similarly, if Wrapper was invariant, the two types could still be partially |
| 654 |
# overlapping -- what if Wrapper[Parent] happened to contain only instances of |
| 655 |
# specifically Child? |
| 656 |
# |
| 657 |
# Or, to use a more concrete example, List[Union[A, B]] and List[Union[B, C]] |
| 658 |
# would be considered partially overlapping since it's possible for both lists |
| 659 |
# to contain only instances of B at runtime. |
| 660 |
if all( |
| 661 |
_is_overlapping_types(left_arg, right_arg) |
| 662 |
for left_arg, right_arg in zip(left_args, right_args) |
| 663 |
): |
| 664 |
return True |
| 665 |
|
| 666 |
return False |
| 667 |
|
| 668 |
# We ought to have handled every case by now: we conclude the |
| 669 |
# two types are not overlapping, either completely or partially. |
| 670 |
# |
| 671 |
# Note: it's unclear however, whether returning False is the right thing |
| 672 |
# to do when inferring reachability -- see https://github.com/python/mypy/issues/5529 |
| 673 |
|
| 674 |
assert type(left) != type(right), f"{type(left)} vs {type(right)}" |
| 675 |
return False |
| 676 |
|
| 677 |
|
| 678 |
def is_overlapping_erased_types( |
| 679 |
left: Type, right: Type, *, ignore_promotions: bool = False |
| 680 |
) -> bool: |
| 681 |
"""The same as 'is_overlapping_erased_types', except the types are erased first.""" |
| 682 |
return is_overlapping_types( |
| 683 |
erase_type(left), erase_type(right), ignore_promotions=ignore_promotions |
| 684 |
) |
| 685 |
|
| 686 |
|
| 687 |
def are_typed_dicts_overlapping( |
| 688 |
left: TypedDictType, right: TypedDictType, is_overlapping: Callable[[Type, Type], bool] |
| 689 |
) -> bool: |
| 690 |
"""Returns 'true' if left and right are overlapping TypeDictTypes.""" |
| 691 |
# All required keys in left are present and overlapping with something in right |
| 692 |
for key in left.required_keys: |
| 693 |
if key not in right.items: |
| 694 |
return False |
| 695 |
if not is_overlapping(left.items[key], right.items[key]): |
| 696 |
return False |
| 697 |
|
| 698 |
# Repeat check in the other direction |
| 699 |
for key in right.required_keys: |
| 700 |
if key not in left.items: |
| 701 |
return False |
| 702 |
if not is_overlapping(left.items[key], right.items[key]): |
| 703 |
return False |
| 704 |
|
| 705 |
# The presence of any additional optional keys does not affect whether the two |
| 706 |
# TypedDicts are partially overlapping: the dicts would be overlapping if the |
| 707 |
# keys happened to be missing. |
| 708 |
return True |
| 709 |
|
| 710 |
|
| 711 |
def are_tuples_overlapping( |
| 712 |
left: Type, right: Type, is_overlapping: Callable[[Type, Type], bool] |
| 713 |
) -> bool: |
| 714 |
"""Returns true if left and right are overlapping tuples.""" |
| 715 |
left, right = get_proper_types((left, right)) |
| 716 |
left = adjust_tuple(left, right) or left |
| 717 |
right = adjust_tuple(right, left) or right |
| 718 |
assert isinstance(left, TupleType), f"Type {left} is not a tuple" |
| 719 |
assert isinstance(right, TupleType), f"Type {right} is not a tuple" |
| 720 |
|
| 721 |
# This algorithm works well if only one tuple is variadic, if both are |
| 722 |
# variadic we may get rare false negatives for overlapping prefix/suffix. |
| 723 |
# Also, this ignores empty unpack case, but it is probably consistent with |
| 724 |
# how we handle e.g. empty lists in overload overlaps. |
| 725 |
# TODO: write a more robust algorithm for cases where both types are variadic. |
| 726 |
left_unpack = find_unpack_in_list(left.items) |
| 727 |
right_unpack = find_unpack_in_list(right.items) |
| 728 |
if left_unpack is not None: |
| 729 |
left = expand_tuple_if_possible(left, len(right.items)) |
| 730 |
if right_unpack is not None: |
| 731 |
right = expand_tuple_if_possible(right, len(left.items)) |
| 732 |
|
| 733 |
if len(left.items) != len(right.items): |
| 734 |
return False |
| 735 |
if not all(is_overlapping(l, r) for l, r in zip(left.items, right.items)): |
| 736 |
return False |
| 737 |
|
| 738 |
# Check that the tuples aren't from e.g. different NamedTuples. |
| 739 |
if is_named_instance(right.partial_fallback, "builtins.tuple") or is_named_instance( |
| 740 |
left.partial_fallback, "builtins.tuple" |
| 741 |
): |
| 742 |
return True |
| 743 |
else: |
| 744 |
return is_overlapping(left.partial_fallback, right.partial_fallback) |
| 745 |
|
| 746 |
|
| 747 |
def expand_tuple_if_possible(tup: TupleType, target: int) -> TupleType: |
| 748 |
if len(tup.items) > target + 1: |
| 749 |
return tup |
| 750 |
extra = target + 1 - len(tup.items) |
| 751 |
new_items = [] |
| 752 |
for it in tup.items: |
| 753 |
if not isinstance(it, UnpackType): |
| 754 |
new_items.append(it) |
| 755 |
continue |
| 756 |
unpacked = get_proper_type(it.type) |
| 757 |
if isinstance(unpacked, TypeVarTupleType): |
| 758 |
instance = unpacked.tuple_fallback |
| 759 |
else: |
| 760 |
# Nested non-variadic tuples should be normalized at this point. |
| 761 |
assert isinstance(unpacked, Instance) |
| 762 |
instance = unpacked |
| 763 |
assert instance.type.fullname == "builtins.tuple" |
| 764 |
new_items.extend([instance.args[0]] * extra) |
| 765 |
return tup.copy_modified(items=new_items) |
| 766 |
|
| 767 |
|
| 768 |
def adjust_tuple(left: ProperType, r: ProperType) -> TupleType | None: |
| 769 |
"""Find out if `left` is a Tuple[A, ...], and adjust its length to `right`""" |
| 770 |
if isinstance(left, Instance) and left.type.fullname == "builtins.tuple": |
| 771 |
n = r.length() if isinstance(r, TupleType) else 1 |
| 772 |
return TupleType([left.args[0]] * n, left) |
| 773 |
return None |
| 774 |
|
| 775 |
|
| 776 |
def is_tuple(typ: Type) -> bool: |
| 777 |
typ = get_proper_type(typ) |
| 778 |
return isinstance(typ, TupleType) or ( |
| 779 |
isinstance(typ, Instance) and typ.type.fullname == "builtins.tuple" |
| 780 |
) |
| 781 |
|
| 782 |
|
| 783 |
class TypeMeetVisitor(TypeVisitor[ProperType]): |
| 784 |
def __init__(self, s: ProperType) -> None: |
| 785 |
self.s = s |
| 786 |
|
| 787 |
def visit_unbound_type(self, t: UnboundType) -> ProperType: |
| 788 |
if isinstance(self.s, NoneType): |
| 789 |
if state.strict_optional: |
| 790 |
return UninhabitedType() |
| 791 |
else: |
| 792 |
return self.s |
| 793 |
elif isinstance(self.s, UninhabitedType): |
| 794 |
return self.s |
| 795 |
else: |
| 796 |
return AnyType(TypeOfAny.special_form) |
| 797 |
|
| 798 |
def visit_any(self, t: AnyType) -> ProperType: |
| 799 |
return self.s |
| 800 |
|
| 801 |
def visit_union_type(self, t: UnionType) -> ProperType: |
| 802 |
if isinstance(self.s, UnionType): |
| 803 |
meets: list[Type] = [] |
| 804 |
for x in t.items: |
| 805 |
for y in self.s.items: |
| 806 |
meets.append(meet_types(x, y)) |
| 807 |
else: |
| 808 |
meets = [meet_types(x, self.s) for x in t.items] |
| 809 |
return make_simplified_union(meets) |
| 810 |
|
| 811 |
def visit_none_type(self, t: NoneType) -> ProperType: |
| 812 |
if state.strict_optional: |
| 813 |
if isinstance(self.s, NoneType) or ( |
| 814 |
isinstance(self.s, Instance) and self.s.type.fullname == "builtins.object" |
| 815 |
): |
| 816 |
return t |
| 817 |
else: |
| 818 |
return UninhabitedType() |
| 819 |
else: |
| 820 |
return t |
| 821 |
|
| 822 |
def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType: |
| 823 |
return t |
| 824 |
|
| 825 |
def visit_deleted_type(self, t: DeletedType) -> ProperType: |
| 826 |
if isinstance(self.s, NoneType): |
| 827 |
if state.strict_optional: |
| 828 |
return t |
| 829 |
else: |
| 830 |
return self.s |
| 831 |
elif isinstance(self.s, UninhabitedType): |
| 832 |
return self.s |
| 833 |
else: |
| 834 |
return t |
| 835 |
|
| 836 |
def visit_erased_type(self, t: ErasedType) -> ProperType: |
| 837 |
return self.s |
| 838 |
|
| 839 |
def visit_type_var(self, t: TypeVarType) -> ProperType: |
| 840 |
if isinstance(self.s, TypeVarType) and self.s.id == t.id: |
| 841 |
if self.s.upper_bound == t.upper_bound: |
| 842 |
return self.s |
| 843 |
return self.s.copy_modified(upper_bound=self.meet(self.s.upper_bound, t.upper_bound)) |
| 844 |
else: |
| 845 |
return self.default(self.s) |
| 846 |
|
| 847 |
def visit_param_spec(self, t: ParamSpecType) -> ProperType: |
| 848 |
if self.s == t: |
| 849 |
return self.s |
| 850 |
else: |
| 851 |
return self.default(self.s) |
| 852 |
|
| 853 |
def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType: |
| 854 |
if isinstance(self.s, TypeVarTupleType) and self.s.id == t.id: |
| 855 |
return self.s if self.s.min_len > t.min_len else t |
| 856 |
else: |
| 857 |
return self.default(self.s) |
| 858 |
|
| 859 |
def visit_unpack_type(self, t: UnpackType) -> ProperType: |
| 860 |
raise NotImplementedError |
| 861 |
|
| 862 |
def visit_parameters(self, t: Parameters) -> ProperType: |
| 863 |
if isinstance(self.s, Parameters): |
| 864 |
if len(t.arg_types) != len(self.s.arg_types): |
| 865 |
return self.default(self.s) |
| 866 |
from mypy.join import join_types |
| 867 |
|
| 868 |
return t.copy_modified( |
| 869 |
arg_types=[join_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types)] |
| 870 |
) |
| 871 |
else: |
| 872 |
return self.default(self.s) |
| 873 |
|
| 874 |
def visit_instance(self, t: Instance) -> ProperType: |
| 875 |
if isinstance(self.s, Instance): |
| 876 |
if t.type == self.s.type: |
| 877 |
if is_subtype(t, self.s) or is_subtype(self.s, t): |
| 878 |
# Combine type arguments. We could have used join below |
| 879 |
# equivalently. |
| 880 |
args: list[Type] = [] |
| 881 |
# N.B: We use zip instead of indexing because the lengths might have |
| 882 |
# mismatches during daemon reprocessing. |
| 883 |
if t.type.has_type_var_tuple_type: |
| 884 |
# We handle meet of variadic instances by simply creating correct mapping |
| 885 |
# for type arguments and compute the individual meets same as for regular |
| 886 |
# instances. All the heavy lifting is done in the meet of tuple types. |
| 887 |
s = self.s |
| 888 |
assert s.type.type_var_tuple_prefix is not None |
| 889 |
assert s.type.type_var_tuple_suffix is not None |
| 890 |
prefix = s.type.type_var_tuple_prefix |
| 891 |
suffix = s.type.type_var_tuple_suffix |
| 892 |
tvt = s.type.defn.type_vars[prefix] |
| 893 |
assert isinstance(tvt, TypeVarTupleType) |
| 894 |
fallback = tvt.tuple_fallback |
| 895 |
s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix( |
| 896 |
s.args, prefix, suffix |
| 897 |
) |
| 898 |
t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix( |
| 899 |
t.args, prefix, suffix |
| 900 |
) |
| 901 |
s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix |
| 902 |
t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix |
| 903 |
else: |
| 904 |
t_args = t.args |
| 905 |
s_args = self.s.args |
| 906 |
for ta, sa, tv in zip(t_args, s_args, t.type.defn.type_vars): |
| 907 |
meet = self.meet(ta, sa) |
| 908 |
if isinstance(tv, TypeVarTupleType): |
| 909 |
# Correctly unpack possible outcomes of meets of tuples: it can be |
| 910 |
# either another tuple type or Never (normalized as *tuple[Never, ...]) |
| 911 |
if isinstance(meet, TupleType): |
| 912 |
args.extend(meet.items) |
| 913 |
continue |
| 914 |
else: |
| 915 |
assert isinstance(meet, UninhabitedType) |
| 916 |
meet = UnpackType(tv.tuple_fallback.copy_modified(args=[meet])) |
| 917 |
args.append(meet) |
| 918 |
return Instance(t.type, args) |
| 919 |
else: |
| 920 |
if state.strict_optional: |
| 921 |
return UninhabitedType() |
| 922 |
else: |
| 923 |
return NoneType() |
| 924 |
else: |
| 925 |
alt_promote = t.type.alt_promote |
| 926 |
if alt_promote and alt_promote.type is self.s.type: |
| 927 |
return t |
| 928 |
alt_promote = self.s.type.alt_promote |
| 929 |
if alt_promote and alt_promote.type is t.type: |
| 930 |
return self.s |
| 931 |
if is_subtype(t, self.s): |
| 932 |
return t |
| 933 |
elif is_subtype(self.s, t): |
| 934 |
# See also above comment. |
| 935 |
return self.s |
| 936 |
else: |
| 937 |
if state.strict_optional: |
| 938 |
return UninhabitedType() |
| 939 |
else: |
| 940 |
return NoneType() |
| 941 |
elif isinstance(self.s, FunctionLike) and t.type.is_protocol: |
| 942 |
call = join.unpack_callback_protocol(t) |
| 943 |
if call: |
| 944 |
return meet_types(call, self.s) |
| 945 |
elif isinstance(self.s, FunctionLike) and self.s.is_type_obj() and t.type.is_metaclass(): |
| 946 |
if is_subtype(self.s.fallback, t): |
| 947 |
return self.s |
| 948 |
return self.default(self.s) |
| 949 |
elif isinstance(self.s, TypeType): |
| 950 |
return meet_types(t, self.s) |
| 951 |
elif isinstance(self.s, TupleType): |
| 952 |
return meet_types(t, self.s) |
| 953 |
elif isinstance(self.s, LiteralType): |
| 954 |
return meet_types(t, self.s) |
| 955 |
elif isinstance(self.s, TypedDictType): |
| 956 |
return meet_types(t, self.s) |
| 957 |
return self.default(self.s) |
| 958 |
|
| 959 |
def visit_callable_type(self, t: CallableType) -> ProperType: |
| 960 |
if isinstance(self.s, CallableType) and join.is_similar_callables(t, self.s): |
| 961 |
if is_equivalent(t, self.s): |
| 962 |
return join.combine_similar_callables(t, self.s) |
| 963 |
result = meet_similar_callables(t, self.s) |
| 964 |
# We set the from_type_type flag to suppress error when a collection of |
| 965 |
# concrete class objects gets inferred as their common abstract superclass. |
| 966 |
if not ( |
| 967 |
(t.is_type_obj() and t.type_object().is_abstract) |
| 968 |
or (self.s.is_type_obj() and self.s.type_object().is_abstract) |
| 969 |
): |
| 970 |
result.from_type_type = True |
| 971 |
if isinstance(get_proper_type(result.ret_type), UninhabitedType): |
| 972 |
# Return a plain None or <uninhabited> instead of a weird function. |
| 973 |
return self.default(self.s) |
| 974 |
return result |
| 975 |
elif isinstance(self.s, TypeType) and t.is_type_obj() and not t.is_generic(): |
| 976 |
# In this case we are able to potentially produce a better meet. |
| 977 |
res = meet_types(self.s.item, t.get_instance_type()) |
| 978 |
if not isinstance(res, (NoneType, UninhabitedType)): |
| 979 |
return TypeType.make_normalized(res) |
| 980 |
return self.default(self.s) |
| 981 |
elif isinstance(self.s, Instance) and self.s.type.is_protocol: |
| 982 |
call = join.unpack_callback_protocol(self.s) |
| 983 |
if call: |
| 984 |
return meet_types(t, call) |
| 985 |
return self.default(self.s) |
| 986 |
|
| 987 |
def visit_overloaded(self, t: Overloaded) -> ProperType: |
| 988 |
# TODO: Implement a better algorithm that covers at least the same cases |
| 989 |
# as TypeJoinVisitor.visit_overloaded(). |
| 990 |
s = self.s |
| 991 |
if isinstance(s, FunctionLike): |
| 992 |
if s.items == t.items: |
| 993 |
return Overloaded(t.items) |
| 994 |
elif is_subtype(s, t): |
| 995 |
return s |
| 996 |
elif is_subtype(t, s): |
| 997 |
return t |
| 998 |
else: |
| 999 |
return meet_types(t.fallback, s.fallback) |
| 1000 |
elif isinstance(self.s, Instance) and self.s.type.is_protocol: |
| 1001 |
call = join.unpack_callback_protocol(self.s) |
| 1002 |
if call: |
| 1003 |
return meet_types(t, call) |
| 1004 |
return meet_types(t.fallback, s) |
| 1005 |
|
| 1006 |
def meet_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None: |
| 1007 |
"""Meet two tuple types while handling variadic entries. |
| 1008 |
|
| 1009 |
This is surprisingly tricky, and we don't handle some tricky corner cases. |
| 1010 |
Most of the trickiness comes from the variadic tuple items like *tuple[X, ...] |
| 1011 |
since they can have arbitrary partial overlaps (while *Ts can't be split). This |
| 1012 |
function is roughly a mirror of join_tuples() w.r.t. to the fact that fixed |
| 1013 |
tuples are subtypes of variadic ones but not vice versa. |
| 1014 |
""" |
| 1015 |
s_unpack_index = find_unpack_in_list(s.items) |
| 1016 |
t_unpack_index = find_unpack_in_list(t.items) |
| 1017 |
if s_unpack_index is None and t_unpack_index is None: |
| 1018 |
if s.length() == t.length(): |
| 1019 |
items: list[Type] = [] |
| 1020 |
for i in range(t.length()): |
| 1021 |
items.append(self.meet(t.items[i], s.items[i])) |
| 1022 |
return items |
| 1023 |
return None |
| 1024 |
if s_unpack_index is not None and t_unpack_index is not None: |
| 1025 |
# The only simple case we can handle if both tuples are variadic |
| 1026 |
# is when their structure fully matches. Other cases are tricky because |
| 1027 |
# a variadic item is effectively a union of tuples of all length, thus |
| 1028 |
# potentially causing overlap between a suffix in `s` and a prefix |
| 1029 |
# in `t` (see how this is handled in is_subtype() for details). |
| 1030 |
# TODO: handle more cases (like when both prefix/suffix are shorter in s or t). |
| 1031 |
if s.length() == t.length() and s_unpack_index == t_unpack_index: |
| 1032 |
unpack_index = s_unpack_index |
| 1033 |
s_unpack = s.items[unpack_index] |
| 1034 |
assert isinstance(s_unpack, UnpackType) |
| 1035 |
s_unpacked = get_proper_type(s_unpack.type) |
| 1036 |
t_unpack = t.items[unpack_index] |
| 1037 |
assert isinstance(t_unpack, UnpackType) |
| 1038 |
t_unpacked = get_proper_type(t_unpack.type) |
| 1039 |
if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)): |
| 1040 |
return None |
| 1041 |
meet = self.meet(s_unpacked, t_unpacked) |
| 1042 |
if not isinstance(meet, Instance): |
| 1043 |
return None |
| 1044 |
m_prefix: list[Type] = [] |
| 1045 |
for si, ti in zip(s.items[:unpack_index], t.items[:unpack_index]): |
| 1046 |
m_prefix.append(meet_types(si, ti)) |
| 1047 |
m_suffix: list[Type] = [] |
| 1048 |
for si, ti in zip(s.items[unpack_index + 1 :], t.items[unpack_index + 1 :]): |
| 1049 |
m_suffix.append(meet_types(si, ti)) |
| 1050 |
return m_prefix + [UnpackType(meet)] + m_suffix |
| 1051 |
return None |
| 1052 |
if s_unpack_index is not None: |
| 1053 |
variadic = s |
| 1054 |
unpack_index = s_unpack_index |
| 1055 |
fixed = t |
| 1056 |
else: |
| 1057 |
assert t_unpack_index is not None |
| 1058 |
variadic = t |
| 1059 |
unpack_index = t_unpack_index |
| 1060 |
fixed = s |
| 1061 |
# If one tuple is variadic one, and the other one is fixed, the meet will be fixed. |
| 1062 |
unpack = variadic.items[unpack_index] |
| 1063 |
assert isinstance(unpack, UnpackType) |
| 1064 |
unpacked = get_proper_type(unpack.type) |
| 1065 |
if not isinstance(unpacked, Instance): |
| 1066 |
return None |
| 1067 |
if fixed.length() < variadic.length() - 1: |
| 1068 |
return None |
| 1069 |
prefix_len = unpack_index |
| 1070 |
suffix_len = variadic.length() - prefix_len - 1 |
| 1071 |
prefix, middle, suffix = split_with_prefix_and_suffix( |
| 1072 |
tuple(fixed.items), prefix_len, suffix_len |
| 1073 |
) |
| 1074 |
items = [] |
| 1075 |
for fi, vi in zip(prefix, variadic.items[:prefix_len]): |
| 1076 |
items.append(self.meet(fi, vi)) |
| 1077 |
for mi in middle: |
| 1078 |
items.append(self.meet(mi, unpacked.args[0])) |
| 1079 |
if suffix_len: |
| 1080 |
for fi, vi in zip(suffix, variadic.items[-suffix_len:]): |
| 1081 |
items.append(self.meet(fi, vi)) |
| 1082 |
return items |
| 1083 |
|
| 1084 |
def visit_tuple_type(self, t: TupleType) -> ProperType: |
| 1085 |
if isinstance(self.s, TupleType): |
| 1086 |
items = self.meet_tuples(self.s, t) |
| 1087 |
if items is None: |
| 1088 |
return self.default(self.s) |
| 1089 |
# TODO: What if the fallbacks are different? |
| 1090 |
return TupleType(items, tuple_fallback(t)) |
| 1091 |
elif isinstance(self.s, Instance): |
| 1092 |
# meet(Tuple[t1, t2, <...>], Tuple[s, ...]) == Tuple[meet(t1, s), meet(t2, s), <...>]. |
| 1093 |
if self.s.type.fullname in TUPLE_LIKE_INSTANCE_NAMES and self.s.args: |
| 1094 |
arg = self.s.args[0] |
| 1095 |
new_items: list[Type] = [] |
| 1096 |
for it in t.items: |
| 1097 |
# Unpack items need to be handled by the caller. |
| 1098 |
if isinstance(it, UnpackType): |
| 1099 |
unpacked = get_proper_type(it.type) |
| 1100 |
if isinstance(unpacked, TypeVarTupleType): |
| 1101 |
# We can't infer anything in this case. |
| 1102 |
new_arg = UninhabitedType() |
| 1103 |
instance = unpacked.tuple_fallback |
| 1104 |
else: |
| 1105 |
assert ( |
| 1106 |
isinstance(unpacked, Instance) |
| 1107 |
and unpacked.type.fullname == "builtins.tuple" |
| 1108 |
) |
| 1109 |
new_arg = meet_types(unpacked.args[0], arg) |
| 1110 |
instance = unpacked |
| 1111 |
new_items.append(UnpackType(instance.copy_modified(args=[new_arg]))) |
| 1112 |
else: |
| 1113 |
# All other items can be processed in a regular way. |
| 1114 |
new_items.append(meet_types(it, arg)) |
| 1115 |
return t.copy_modified(items=new_items) |
| 1116 |
elif is_proper_subtype(t, self.s): |
| 1117 |
# A named tuple that inherits from a normal class |
| 1118 |
return t |
| 1119 |
elif self.s.type.has_type_var_tuple_type and is_subtype(t, self.s): |
| 1120 |
# This is a bit ad-hoc but more principled handling is tricky, and this |
| 1121 |
# special case is important for type narrowing in binder to work. |
| 1122 |
return t |
| 1123 |
return self.default(self.s) |
| 1124 |
|
| 1125 |
def resolve_typeddict_item_type( |
| 1126 |
self, name: str, s: TypedDictItem, t: TypedDictItem |
| 1127 |
) -> tuple[Type | None, bool]: |
| 1128 |
"""Return the type and readonlyness of a meet item. |
| 1129 |
|
| 1130 |
If the parent constraints are mutually incompatible, the |
| 1131 |
returned type will be None; the overall meet type should |
| 1132 |
be UninhabitedType. |
| 1133 |
""" |
| 1134 |
is_readonly = s.readonly and t.readonly |
| 1135 |
|
| 1136 |
if t.typ is None: |
| 1137 |
assert s.typ is not None |
| 1138 |
meet_type = s.typ |
| 1139 |
elif s.typ is None: |
| 1140 |
meet_type = t.typ |
| 1141 |
else: |
| 1142 |
meet_type = meet_types(s.typ, t.typ) |
| 1143 |
|
| 1144 |
if ( |
| 1145 |
s.typ is not None |
| 1146 |
and s.mutable |
| 1147 |
and (not is_equivalent(meet_type, s.typ) or (t.required and not s.required)) |
| 1148 |
): |
| 1149 |
meet_type = None |
| 1150 |
elif ( |
| 1151 |
t.typ is not None |
| 1152 |
and t.mutable |
| 1153 |
and (not is_equivalent(meet_type, t.typ) or (s.required and not t.required)) |
| 1154 |
): |
| 1155 |
meet_type = None |
| 1156 |
elif isinstance(get_proper_type(meet_type), UninhabitedType) and ( |
| 1157 |
s.required or t.required |
| 1158 |
): |
| 1159 |
meet_type = None |
| 1160 |
|
| 1161 |
return (meet_type, is_readonly) |
| 1162 |
|
| 1163 |
def visit_typeddict_type(self, t: TypedDictType) -> ProperType: |
| 1164 |
if isinstance(self.s, TypedDictType): |
| 1165 |
is_closed = self.s.is_closed or t.is_closed |
| 1166 |
items: dict[str, Type] = {} |
| 1167 |
readonly_keys: set[str] = set() |
| 1168 |
for name, s_item, t_item in self.s.zipall(t): |
| 1169 |
meet_type, is_readonly = self.resolve_typeddict_item_type(name, s_item, t_item) |
| 1170 |
|
| 1171 |
if meet_type is None: |
| 1172 |
return self.default(self.s) |
| 1173 |
|
| 1174 |
if ( |
| 1175 |
is_closed |
| 1176 |
and not is_readonly |
| 1177 |
and isinstance(get_proper_type(meet_type), UninhabitedType) |
| 1178 |
): |
| 1179 |
# Simplify emitted type by omitting redundant Never keys from closed |
| 1180 |
# TypedDicts |
| 1181 |
continue |
| 1182 |
|
| 1183 |
items[name] = meet_type |
| 1184 |
if is_readonly: |
| 1185 |
readonly_keys.add(name) |
| 1186 |
|
| 1187 |
fallback = self.s.create_anonymous_fallback() |
| 1188 |
required_keys = self.s.required_keys | t.required_keys |
| 1189 |
return TypedDictType( |
| 1190 |
items, required_keys, readonly_keys, fallback, is_closed=is_closed |
| 1191 |
) |
| 1192 |
elif isinstance(self.s, Instance) and is_subtype(t, self.s): |
| 1193 |
return t |
| 1194 |
else: |
| 1195 |
return self.default(self.s) |
| 1196 |
|
| 1197 |
def visit_literal_type(self, t: LiteralType) -> ProperType: |
| 1198 |
if isinstance(self.s, LiteralType) and self.s == t: |
| 1199 |
return t |
| 1200 |
elif isinstance(self.s, Instance) and is_subtype(t.fallback, self.s): |
| 1201 |
return t |
| 1202 |
else: |
| 1203 |
return self.default(self.s) |
| 1204 |
|
| 1205 |
def visit_partial_type(self, t: PartialType) -> ProperType: |
| 1206 |
# We can't determine the meet of partial types. We should never get here. |
| 1207 |
assert False, "Internal error" |
| 1208 |
|
| 1209 |
def visit_type_type(self, t: TypeType) -> ProperType: |
| 1210 |
if isinstance(self.s, TypeType): |
| 1211 |
typ = self.meet(t.item, self.s.item) |
| 1212 |
if not isinstance(typ, NoneType): |
| 1213 |
typ = TypeType.make_normalized( |
| 1214 |
typ, line=t.line, is_type_form=self.s.is_type_form and t.is_type_form |
| 1215 |
) |
| 1216 |
return typ |
| 1217 |
elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type": |
| 1218 |
return t |
| 1219 |
elif isinstance(self.s, CallableType): |
| 1220 |
return self.meet(t, self.s) |
| 1221 |
else: |
| 1222 |
return self.default(self.s) |
| 1223 |
|
| 1224 |
def visit_type_alias_type(self, t: TypeAliasType) -> ProperType: |
| 1225 |
assert False, f"This should be never called, got {t}" |
| 1226 |
|
| 1227 |
def meet(self, s: Type, t: Type) -> ProperType: |
| 1228 |
return meet_types(s, t) |
| 1229 |
|
| 1230 |
def default(self, typ: Type) -> ProperType: |
| 1231 |
if isinstance(typ, UnboundType): |
| 1232 |
return AnyType(TypeOfAny.special_form) |
| 1233 |
else: |
| 1234 |
if state.strict_optional: |
| 1235 |
return UninhabitedType() |
| 1236 |
else: |
| 1237 |
return NoneType() |
| 1238 |
|
| 1239 |
|
| 1240 |
def meet_similar_callables(t: CallableType, s: CallableType) -> CallableType: |
| 1241 |
from mypy.join import match_generic_callables, safe_join |
| 1242 |
|
| 1243 |
t, s = match_generic_callables(t, s) |
| 1244 |
arg_types: list[Type] = [] |
| 1245 |
for i in range(len(t.arg_types)): |
| 1246 |
arg_types.append(safe_join(t.arg_types[i], s.arg_types[i])) |
| 1247 |
# TODO in combine_similar_callables also applies here (names and kinds) |
| 1248 |
# The fallback type can be either 'function' or 'type'. The result should have 'function' as |
| 1249 |
# fallback only if both operands have it as 'function'. |
| 1250 |
if t.fallback.type.fullname != "builtins.function": |
| 1251 |
fallback = t.fallback |
| 1252 |
else: |
| 1253 |
fallback = s.fallback |
| 1254 |
if t.instance_type is None: |
| 1255 |
instance_type = s.instance_type |
| 1256 |
elif s.instance_type is None: |
| 1257 |
instance_type = t.instance_type |
| 1258 |
else: |
| 1259 |
instance_type = meet_types(t.instance_type, s.instance_type) |
| 1260 |
return t.copy_modified( |
| 1261 |
arg_types=arg_types, |
| 1262 |
ret_type=meet_types(t.ret_type, s.ret_type), |
| 1263 |
instance_type=instance_type, |
| 1264 |
fallback=fallback, |
| 1265 |
name=None, |
| 1266 |
) |
| 1267 |
|
| 1268 |
|
| 1269 |
def meet_type_list(types: list[Type]) -> Type: |
| 1270 |
if not types: |
| 1271 |
# This should probably be builtins.object but that is hard to get and |
| 1272 |
# it doesn't matter for any current users. |
| 1273 |
return AnyType(TypeOfAny.implementation_artifact) |
| 1274 |
met = types[0] |
| 1275 |
for t in types[1:]: |
| 1276 |
met = meet_types(met, t) |
| 1277 |
return met |
| 1278 |
|
| 1279 |
|
| 1280 |
def typed_dict_mapping_pair(left: Type, right: Type) -> bool: |
| 1281 |
"""Is this a pair where one type is a TypedDict and another one is an instance of Mapping? |
| 1282 |
|
| 1283 |
This case requires a precise/principled consideration because there are two use cases |
| 1284 |
that push the boundary the opposite ways: we need to avoid spurious overlaps to avoid |
| 1285 |
false positives for overloads, but we also need to avoid spuriously non-overlapping types |
| 1286 |
to avoid false positives with --strict-equality. |
| 1287 |
""" |
| 1288 |
left, right = get_proper_types((left, right)) |
| 1289 |
assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType) |
| 1290 |
|
| 1291 |
if isinstance(left, TypedDictType): |
| 1292 |
_, other = left, right |
| 1293 |
elif isinstance(right, TypedDictType): |
| 1294 |
_, other = right, left |
| 1295 |
else: |
| 1296 |
return False |
| 1297 |
return isinstance(other, Instance) and other.type.has_base("typing.Mapping") |
| 1298 |
|
| 1299 |
|
| 1300 |
def typed_dict_mapping_overlap( |
| 1301 |
left: Type, right: Type, overlapping: Callable[[Type, Type], bool] |
| 1302 |
) -> bool: |
| 1303 |
"""Check if a TypedDict type is overlapping with a Mapping. |
| 1304 |
|
| 1305 |
The basic logic here consists of two rules: |
| 1306 |
|
| 1307 |
* A TypedDict with some required keys is overlapping with Mapping[str, <some type>] |
| 1308 |
if and only if every key type is overlapping with <some type>. For example: |
| 1309 |
|
| 1310 |
- TypedDict(x=int, y=str) overlaps with Dict[str, Union[str, int]] |
| 1311 |
- TypedDict(x=int, y=str) doesn't overlap with Dict[str, int] |
| 1312 |
|
| 1313 |
Note that any additional non-required keys can't change the above result. |
| 1314 |
|
| 1315 |
* A TypedDict with no required keys overlaps with Mapping[str, <some type>] if and |
| 1316 |
only if at least one of key types overlaps with <some type>. For example: |
| 1317 |
|
| 1318 |
- TypedDict(x=str, y=str, total=False) overlaps with Dict[str, str] |
| 1319 |
- TypedDict(x=str, y=str, total=False) doesn't overlap with Dict[str, int] |
| 1320 |
- TypedDict(x=int, y=str, total=False) overlaps with Dict[str, str] |
| 1321 |
|
| 1322 |
* A TypedDict with at least one ReadOnly[] key does not overlap |
| 1323 |
with Dict or MutableMapping, because they assume mutable data. |
| 1324 |
|
| 1325 |
As usual empty, dictionaries lie in a gray area. In general, List[str] and List[str] |
| 1326 |
are considered non-overlapping despite empty list belongs to both. However, List[int] |
| 1327 |
and List[Never] are considered overlapping. |
| 1328 |
|
| 1329 |
So here we follow the same logic: a TypedDict with no required keys is considered |
| 1330 |
non-overlapping with Mapping[str, <some type>], but is considered overlapping with |
| 1331 |
Mapping[Never, Never]. This way we avoid false positives for overloads, and also |
| 1332 |
avoid false positives for comparisons like SomeTypedDict == {} under --strict-equality. |
| 1333 |
""" |
| 1334 |
left, right = get_proper_types((left, right)) |
| 1335 |
assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType) |
| 1336 |
|
| 1337 |
if isinstance(left, TypedDictType): |
| 1338 |
assert isinstance(right, Instance) |
| 1339 |
typed, other = left, right |
| 1340 |
else: |
| 1341 |
assert isinstance(left, Instance) |
| 1342 |
assert isinstance(right, TypedDictType) |
| 1343 |
typed, other = right, left |
| 1344 |
|
| 1345 |
mutable_mapping = next( |
| 1346 |
(base for base in other.type.mro if base.fullname == "typing.MutableMapping"), None |
| 1347 |
) |
| 1348 |
if mutable_mapping is not None and typed.readonly_keys: |
| 1349 |
return False |
| 1350 |
|
| 1351 |
mapping = next(base for base in other.type.mro if base.fullname == "typing.Mapping") |
| 1352 |
other = map_instance_to_supertype(other, mapping) |
| 1353 |
key_type, value_type = get_proper_types(other.args) |
| 1354 |
|
| 1355 |
# TODO: is there a cleaner way to get str_type here? |
| 1356 |
fallback = typed.create_anonymous_fallback() |
| 1357 |
str_type = fallback.type.bases[0].args[0] # typing._TypedDict inherits Mapping[str, object] |
| 1358 |
|
| 1359 |
# Special case: a TypedDict with no required keys overlaps with an empty dict. |
| 1360 |
if isinstance(key_type, UninhabitedType) and isinstance(value_type, UninhabitedType): |
| 1361 |
return not typed.required_keys |
| 1362 |
|
| 1363 |
if typed.required_keys: |
| 1364 |
if not overlapping(key_type, str_type): |
| 1365 |
return False |
| 1366 |
return all(overlapping(typed.items[k], value_type) for k in typed.required_keys) |
| 1367 |
else: |
| 1368 |
if not overlapping(key_type, str_type): |
| 1369 |
return False |
| 1370 |
non_required = set(typed.items.keys()) - typed.required_keys |
| 1371 |
return any(overlapping(typed.items[k], value_type) for k in non_required) |