meet.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. from __future__ import annotations
  2. from typing import Callable
  3. from mypy import join
  4. from mypy.erasetype import erase_type
  5. from mypy.maptype import map_instance_to_supertype
  6. from mypy.state import state
  7. from mypy.subtypes import (
  8. is_callable_compatible,
  9. is_equivalent,
  10. is_proper_subtype,
  11. is_same_type,
  12. is_subtype,
  13. )
  14. from mypy.typeops import is_recursive_pair, make_simplified_union, tuple_fallback
  15. from mypy.types import (
  16. MYPYC_NATIVE_INT_NAMES,
  17. AnyType,
  18. CallableType,
  19. DeletedType,
  20. ErasedType,
  21. FunctionLike,
  22. Instance,
  23. LiteralType,
  24. NoneType,
  25. Overloaded,
  26. Parameters,
  27. ParamSpecType,
  28. PartialType,
  29. ProperType,
  30. TupleType,
  31. Type,
  32. TypeAliasType,
  33. TypedDictType,
  34. TypeGuardedType,
  35. TypeOfAny,
  36. TypeType,
  37. TypeVarLikeType,
  38. TypeVarTupleType,
  39. TypeVarType,
  40. TypeVisitor,
  41. UnboundType,
  42. UninhabitedType,
  43. UnionType,
  44. UnpackType,
  45. get_proper_type,
  46. get_proper_types,
  47. )
  48. # TODO Describe this module.
  49. def trivial_meet(s: Type, t: Type) -> ProperType:
  50. """Return one of types (expanded) if it is a subtype of other, otherwise bottom type."""
  51. if is_subtype(s, t):
  52. return get_proper_type(s)
  53. elif is_subtype(t, s):
  54. return get_proper_type(t)
  55. else:
  56. if state.strict_optional:
  57. return UninhabitedType()
  58. else:
  59. return NoneType()
  60. def meet_types(s: Type, t: Type) -> ProperType:
  61. """Return the greatest lower bound of two types."""
  62. if is_recursive_pair(s, t):
  63. # This case can trigger an infinite recursion, general support for this will be
  64. # tricky, so we use a trivial meet (like for protocols).
  65. return trivial_meet(s, t)
  66. s = get_proper_type(s)
  67. t = get_proper_type(t)
  68. if isinstance(s, Instance) and isinstance(t, Instance) and s.type == t.type:
  69. # Code in checker.py should merge any extra_items where possible, so we
  70. # should have only compatible extra_items here. We check this before
  71. # the below subtype check, so that extra_attrs will not get erased.
  72. if (s.extra_attrs or t.extra_attrs) and is_same_type(s, t):
  73. if s.extra_attrs and t.extra_attrs:
  74. if len(s.extra_attrs.attrs) > len(t.extra_attrs.attrs):
  75. # Return the one that has more precise information.
  76. return s
  77. return t
  78. if s.extra_attrs:
  79. return s
  80. return t
  81. if not isinstance(s, UnboundType) and not isinstance(t, UnboundType):
  82. if is_proper_subtype(s, t, ignore_promotions=True):
  83. return s
  84. if is_proper_subtype(t, s, ignore_promotions=True):
  85. return t
  86. if isinstance(s, ErasedType):
  87. return s
  88. if isinstance(s, AnyType):
  89. return t
  90. if isinstance(s, UnionType) and not isinstance(t, UnionType):
  91. s, t = t, s
  92. # Meets/joins require callable type normalization.
  93. s, t = join.normalize_callables(s, t)
  94. return t.accept(TypeMeetVisitor(s))
  95. def narrow_declared_type(declared: Type, narrowed: Type) -> Type:
  96. """Return the declared type narrowed down to another type."""
  97. # TODO: check infinite recursion for aliases here.
  98. if isinstance(narrowed, TypeGuardedType): # type: ignore[misc]
  99. # A type guard forces the new type even if it doesn't overlap the old.
  100. return narrowed.type_guard
  101. original_declared = declared
  102. original_narrowed = narrowed
  103. declared = get_proper_type(declared)
  104. narrowed = get_proper_type(narrowed)
  105. if declared == narrowed:
  106. return original_declared
  107. if isinstance(declared, UnionType):
  108. return make_simplified_union(
  109. [
  110. narrow_declared_type(x, narrowed)
  111. for x in declared.relevant_items()
  112. # This (ugly) special-casing is needed to support checking
  113. # branches like this:
  114. # x: Union[float, complex]
  115. # if isinstance(x, int):
  116. # ...
  117. if (
  118. is_overlapping_types(x, narrowed, ignore_promotions=True)
  119. or is_subtype(narrowed, x, ignore_promotions=False)
  120. )
  121. ]
  122. )
  123. if is_enum_overlapping_union(declared, narrowed):
  124. return original_narrowed
  125. elif not is_overlapping_types(declared, narrowed, prohibit_none_typevar_overlap=True):
  126. if state.strict_optional:
  127. return UninhabitedType()
  128. else:
  129. return NoneType()
  130. elif isinstance(narrowed, UnionType):
  131. return make_simplified_union(
  132. [narrow_declared_type(declared, x) for x in narrowed.relevant_items()]
  133. )
  134. elif isinstance(narrowed, AnyType):
  135. return original_narrowed
  136. elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared):
  137. return narrowed
  138. elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType):
  139. return TypeType.make_normalized(narrow_declared_type(declared.item, narrowed.item))
  140. elif (
  141. isinstance(declared, TypeType)
  142. and isinstance(narrowed, Instance)
  143. and narrowed.type.is_metaclass()
  144. ):
  145. # We'd need intersection types, so give up.
  146. return original_declared
  147. elif isinstance(declared, Instance):
  148. if declared.type.alt_promote:
  149. # Special case: low-level integer type can't be narrowed
  150. return original_declared
  151. if (
  152. isinstance(narrowed, Instance)
  153. and narrowed.type.alt_promote
  154. and narrowed.type.alt_promote.type is declared.type
  155. ):
  156. # Special case: 'int' can't be narrowed down to a native int type such as
  157. # i64, since they have different runtime representations.
  158. return original_declared
  159. return meet_types(original_declared, original_narrowed)
  160. elif isinstance(declared, (TupleType, TypeType, LiteralType)):
  161. return meet_types(original_declared, original_narrowed)
  162. elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance):
  163. # Special case useful for selecting TypedDicts from unions using isinstance(x, dict).
  164. if narrowed.type.fullname == "builtins.dict" and all(
  165. isinstance(t, AnyType) for t in get_proper_types(narrowed.args)
  166. ):
  167. return original_declared
  168. return meet_types(original_declared, original_narrowed)
  169. return original_narrowed
  170. def get_possible_variants(typ: Type) -> list[Type]:
  171. """This function takes any "Union-like" type and returns a list of the available "options".
  172. Specifically, there are currently exactly three different types that can have
  173. "variants" or are "union-like":
  174. - Unions
  175. - TypeVars with value restrictions
  176. - Overloads
  177. This function will return a list of each "option" present in those types.
  178. If this function receives any other type, we return a list containing just that
  179. original type. (E.g. pretend the type was contained within a singleton union).
  180. The only current exceptions are regular TypeVars and ParamSpecs. For these "TypeVarLike"s,
  181. we return a list containing that TypeVarLike's upper bound.
  182. This function is useful primarily when checking to see if two types are overlapping:
  183. the algorithm to check if two unions are overlapping is fundamentally the same as
  184. the algorithm for checking if two overloads are overlapping.
  185. Normalizing both kinds of types in the same way lets us reuse the same algorithm
  186. for both.
  187. """
  188. typ = get_proper_type(typ)
  189. if isinstance(typ, TypeVarType):
  190. if len(typ.values) > 0:
  191. return typ.values
  192. else:
  193. return [typ.upper_bound]
  194. elif isinstance(typ, ParamSpecType):
  195. return [typ.upper_bound]
  196. elif isinstance(typ, UnionType):
  197. return list(typ.items)
  198. elif isinstance(typ, Overloaded):
  199. # Note: doing 'return typ.items()' makes mypy
  200. # infer a too-specific return type of List[CallableType]
  201. return list(typ.items)
  202. else:
  203. return [typ]
  204. def is_enum_overlapping_union(x: ProperType, y: ProperType) -> bool:
  205. """Return True if x is an Enum, and y is an Union with at least one Literal from x"""
  206. return (
  207. isinstance(x, Instance)
  208. and x.type.is_enum
  209. and isinstance(y, UnionType)
  210. and any(
  211. isinstance(p, LiteralType) and x.type == p.fallback.type
  212. for p in (get_proper_type(z) for z in y.relevant_items())
  213. )
  214. )
  215. def is_literal_in_union(x: ProperType, y: ProperType) -> bool:
  216. """Return True if x is a Literal and y is an Union that includes x"""
  217. return (
  218. isinstance(x, LiteralType)
  219. and isinstance(y, UnionType)
  220. and any(x == get_proper_type(z) for z in y.items)
  221. )
  222. def is_overlapping_types(
  223. left: Type,
  224. right: Type,
  225. ignore_promotions: bool = False,
  226. prohibit_none_typevar_overlap: bool = False,
  227. ignore_uninhabited: bool = False,
  228. ) -> bool:
  229. """Can a value of type 'left' also be of type 'right' or vice-versa?
  230. If 'ignore_promotions' is True, we ignore promotions while checking for overlaps.
  231. If 'prohibit_none_typevar_overlap' is True, we disallow None from overlapping with
  232. TypeVars (in both strict-optional and non-strict-optional mode).
  233. """
  234. if isinstance(left, TypeGuardedType) or isinstance( # type: ignore[misc]
  235. right, TypeGuardedType
  236. ):
  237. # A type guard forces the new type even if it doesn't overlap the old.
  238. return True
  239. left, right = get_proper_types((left, right))
  240. def _is_overlapping_types(left: Type, right: Type) -> bool:
  241. """Encode the kind of overlapping check to perform.
  242. This function mostly exists so we don't have to repeat keyword arguments everywhere."""
  243. return is_overlapping_types(
  244. left,
  245. right,
  246. ignore_promotions=ignore_promotions,
  247. prohibit_none_typevar_overlap=prohibit_none_typevar_overlap,
  248. ignore_uninhabited=ignore_uninhabited,
  249. )
  250. # We should never encounter this type.
  251. if isinstance(left, PartialType) or isinstance(right, PartialType):
  252. assert False, "Unexpectedly encountered partial type"
  253. # We should also never encounter these types, but it's possible a few
  254. # have snuck through due to unrelated bugs. For now, we handle these
  255. # in the same way we handle 'Any'.
  256. #
  257. # TODO: Replace these with an 'assert False' once we are more confident.
  258. illegal_types = (UnboundType, ErasedType, DeletedType)
  259. if isinstance(left, illegal_types) or isinstance(right, illegal_types):
  260. return True
  261. # When running under non-strict optional mode, simplify away types of
  262. # the form 'Union[A, B, C, None]' into just 'Union[A, B, C]'.
  263. if not state.strict_optional:
  264. if isinstance(left, UnionType):
  265. left = UnionType.make_union(left.relevant_items())
  266. if isinstance(right, UnionType):
  267. right = UnionType.make_union(right.relevant_items())
  268. left, right = get_proper_types((left, right))
  269. # 'Any' may or may not be overlapping with the other type
  270. if isinstance(left, AnyType) or isinstance(right, AnyType):
  271. return True
  272. # We check for complete overlaps next as a general-purpose failsafe.
  273. # If this check fails, we start checking to see if there exists a
  274. # *partial* overlap between types.
  275. #
  276. # These checks will also handle the NoneType and UninhabitedType cases for us.
  277. # enums are sometimes expanded into an Union of Literals
  278. # when that happens we want to make sure we treat the two as overlapping
  279. # and crucially, we want to do that *fast* in case the enum is large
  280. # so we do it before expanding variants below to avoid O(n**2) behavior
  281. if (
  282. is_enum_overlapping_union(left, right)
  283. or is_enum_overlapping_union(right, left)
  284. or is_literal_in_union(left, right)
  285. or is_literal_in_union(right, left)
  286. ):
  287. return True
  288. if is_proper_subtype(
  289. left, right, ignore_promotions=ignore_promotions, ignore_uninhabited=ignore_uninhabited
  290. ) or is_proper_subtype(
  291. right, left, ignore_promotions=ignore_promotions, ignore_uninhabited=ignore_uninhabited
  292. ):
  293. return True
  294. # See the docstring for 'get_possible_variants' for more info on what the
  295. # following lines are doing.
  296. left_possible = get_possible_variants(left)
  297. right_possible = get_possible_variants(right)
  298. # First handle special cases relating to PEP 612:
  299. # - comparing a `Parameters` to a `Parameters`
  300. # - comparing a `Parameters` to a `ParamSpecType`
  301. # - comparing a `ParamSpecType` to a `ParamSpecType`
  302. #
  303. # These should all always be considered overlapping equality checks.
  304. # These need to be done before we move on to other TypeVarLike comparisons.
  305. if isinstance(left, (Parameters, ParamSpecType)) and isinstance(
  306. right, (Parameters, ParamSpecType)
  307. ):
  308. return True
  309. # A `Parameters` does not overlap with anything else, however
  310. if isinstance(left, Parameters) or isinstance(right, Parameters):
  311. return False
  312. # Now move on to checking multi-variant types like Unions. We also perform
  313. # the same logic if either type happens to be a TypeVar/ParamSpec/TypeVarTuple.
  314. #
  315. # Handling the TypeVarLikes now lets us simulate having them bind to the corresponding
  316. # type -- if we deferred these checks, the "return-early" logic of the other
  317. # checks will prevent us from detecting certain overlaps.
  318. #
  319. # If both types are singleton variants (and are not TypeVarLikes), we've hit the base case:
  320. # we skip these checks to avoid infinitely recursing.
  321. def is_none_typevarlike_overlap(t1: Type, t2: Type) -> bool:
  322. t1, t2 = get_proper_types((t1, t2))
  323. return isinstance(t1, NoneType) and isinstance(t2, TypeVarLikeType)
  324. if prohibit_none_typevar_overlap:
  325. if is_none_typevarlike_overlap(left, right) or is_none_typevarlike_overlap(right, left):
  326. return False
  327. if (
  328. len(left_possible) > 1
  329. or len(right_possible) > 1
  330. or isinstance(left, TypeVarLikeType)
  331. or isinstance(right, TypeVarLikeType)
  332. ):
  333. for l in left_possible:
  334. for r in right_possible:
  335. if _is_overlapping_types(l, r):
  336. return True
  337. return False
  338. # Now that we've finished handling TypeVarLikes, we're free to end early
  339. # if one one of the types is None and we're running in strict-optional mode.
  340. # (None only overlaps with None in strict-optional mode).
  341. #
  342. # We must perform this check after the TypeVarLike checks because
  343. # a TypeVar could be bound to None, for example.
  344. if state.strict_optional and isinstance(left, NoneType) != isinstance(right, NoneType):
  345. return False
  346. # Next, we handle single-variant types that may be inherently partially overlapping:
  347. #
  348. # - TypedDicts
  349. # - Tuples
  350. #
  351. # If we cannot identify a partial overlap and end early, we degrade these two types
  352. # into their 'Instance' fallbacks.
  353. if isinstance(left, TypedDictType) and isinstance(right, TypedDictType):
  354. return are_typed_dicts_overlapping(left, right, ignore_promotions=ignore_promotions)
  355. elif typed_dict_mapping_pair(left, right):
  356. # Overlaps between TypedDicts and Mappings require dedicated logic.
  357. return typed_dict_mapping_overlap(left, right, overlapping=_is_overlapping_types)
  358. elif isinstance(left, TypedDictType):
  359. left = left.fallback
  360. elif isinstance(right, TypedDictType):
  361. right = right.fallback
  362. if is_tuple(left) and is_tuple(right):
  363. return are_tuples_overlapping(left, right, ignore_promotions=ignore_promotions)
  364. elif isinstance(left, TupleType):
  365. left = tuple_fallback(left)
  366. elif isinstance(right, TupleType):
  367. right = tuple_fallback(right)
  368. # Next, we handle single-variant types that cannot be inherently partially overlapping,
  369. # but do require custom logic to inspect.
  370. #
  371. # As before, we degrade into 'Instance' whenever possible.
  372. if isinstance(left, TypeType) and isinstance(right, TypeType):
  373. return _is_overlapping_types(left.item, right.item)
  374. def _type_object_overlap(left: Type, right: Type) -> bool:
  375. """Special cases for type object types overlaps."""
  376. # TODO: these checks are a bit in gray area, adjust if they cause problems.
  377. left, right = get_proper_types((left, right))
  378. # 1. Type[C] vs Callable[..., C] overlap even if the latter is not class object.
  379. if isinstance(left, TypeType) and isinstance(right, CallableType):
  380. return _is_overlapping_types(left.item, right.ret_type)
  381. # 2. Type[C] vs Meta, where Meta is a metaclass for C.
  382. if isinstance(left, TypeType) and isinstance(right, Instance):
  383. if isinstance(left.item, Instance):
  384. left_meta = left.item.type.metaclass_type
  385. if left_meta is not None:
  386. return _is_overlapping_types(left_meta, right)
  387. # builtins.type (default metaclass) overlaps with all metaclasses
  388. return right.type.has_base("builtins.type")
  389. elif isinstance(left.item, AnyType):
  390. return right.type.has_base("builtins.type")
  391. # 3. Callable[..., C] vs Meta is considered below, when we switch to fallbacks.
  392. return False
  393. if isinstance(left, TypeType) or isinstance(right, TypeType):
  394. return _type_object_overlap(left, right) or _type_object_overlap(right, left)
  395. if isinstance(left, CallableType) and isinstance(right, CallableType):
  396. return is_callable_compatible(
  397. left,
  398. right,
  399. is_compat=_is_overlapping_types,
  400. ignore_pos_arg_names=True,
  401. allow_partial_overlap=True,
  402. )
  403. elif isinstance(left, CallableType):
  404. left = left.fallback
  405. elif isinstance(right, CallableType):
  406. right = right.fallback
  407. if isinstance(left, LiteralType) and isinstance(right, LiteralType):
  408. if left.value == right.value:
  409. # If values are the same, we still need to check if fallbacks are overlapping,
  410. # this is done below.
  411. left = left.fallback
  412. right = right.fallback
  413. else:
  414. return False
  415. elif isinstance(left, LiteralType):
  416. left = left.fallback
  417. elif isinstance(right, LiteralType):
  418. right = right.fallback
  419. # Finally, we handle the case where left and right are instances.
  420. if isinstance(left, Instance) and isinstance(right, Instance):
  421. # First we need to handle promotions and structural compatibility for instances
  422. # that came as fallbacks, so simply call is_subtype() to avoid code duplication.
  423. if is_subtype(
  424. left, right, ignore_promotions=ignore_promotions, ignore_uninhabited=ignore_uninhabited
  425. ) or is_subtype(
  426. right, left, ignore_promotions=ignore_promotions, ignore_uninhabited=ignore_uninhabited
  427. ):
  428. return True
  429. if right.type.fullname == "builtins.int" and left.type.fullname in MYPYC_NATIVE_INT_NAMES:
  430. return True
  431. # Two unrelated types cannot be partially overlapping: they're disjoint.
  432. if left.type.has_base(right.type.fullname):
  433. left = map_instance_to_supertype(left, right.type)
  434. elif right.type.has_base(left.type.fullname):
  435. right = map_instance_to_supertype(right, left.type)
  436. else:
  437. return False
  438. if len(left.args) == len(right.args):
  439. # Note: we don't really care about variance here, since the overlapping check
  440. # is symmetric and since we want to return 'True' even for partial overlaps.
  441. #
  442. # For example, suppose we have two types Wrapper[Parent] and Wrapper[Child].
  443. # It doesn't matter whether Wrapper is covariant or contravariant since
  444. # either way, one of the two types will overlap with the other.
  445. #
  446. # Similarly, if Wrapper was invariant, the two types could still be partially
  447. # overlapping -- what if Wrapper[Parent] happened to contain only instances of
  448. # specifically Child?
  449. #
  450. # Or, to use a more concrete example, List[Union[A, B]] and List[Union[B, C]]
  451. # would be considered partially overlapping since it's possible for both lists
  452. # to contain only instances of B at runtime.
  453. if all(
  454. _is_overlapping_types(left_arg, right_arg)
  455. for left_arg, right_arg in zip(left.args, right.args)
  456. ):
  457. return True
  458. return False
  459. # We ought to have handled every case by now: we conclude the
  460. # two types are not overlapping, either completely or partially.
  461. #
  462. # Note: it's unclear however, whether returning False is the right thing
  463. # to do when inferring reachability -- see https://github.com/python/mypy/issues/5529
  464. assert type(left) != type(right), f"{type(left)} vs {type(right)}"
  465. return False
  466. def is_overlapping_erased_types(
  467. left: Type, right: Type, *, ignore_promotions: bool = False
  468. ) -> bool:
  469. """The same as 'is_overlapping_erased_types', except the types are erased first."""
  470. return is_overlapping_types(
  471. erase_type(left),
  472. erase_type(right),
  473. ignore_promotions=ignore_promotions,
  474. prohibit_none_typevar_overlap=True,
  475. )
  476. def are_typed_dicts_overlapping(
  477. left: TypedDictType,
  478. right: TypedDictType,
  479. *,
  480. ignore_promotions: bool = False,
  481. prohibit_none_typevar_overlap: bool = False,
  482. ) -> bool:
  483. """Returns 'true' if left and right are overlapping TypeDictTypes."""
  484. # All required keys in left are present and overlapping with something in right
  485. for key in left.required_keys:
  486. if key not in right.items:
  487. return False
  488. if not is_overlapping_types(
  489. left.items[key],
  490. right.items[key],
  491. ignore_promotions=ignore_promotions,
  492. prohibit_none_typevar_overlap=prohibit_none_typevar_overlap,
  493. ):
  494. return False
  495. # Repeat check in the other direction
  496. for key in right.required_keys:
  497. if key not in left.items:
  498. return False
  499. if not is_overlapping_types(
  500. left.items[key], right.items[key], ignore_promotions=ignore_promotions
  501. ):
  502. return False
  503. # The presence of any additional optional keys does not affect whether the two
  504. # TypedDicts are partially overlapping: the dicts would be overlapping if the
  505. # keys happened to be missing.
  506. return True
  507. def are_tuples_overlapping(
  508. left: Type,
  509. right: Type,
  510. *,
  511. ignore_promotions: bool = False,
  512. prohibit_none_typevar_overlap: bool = False,
  513. ) -> bool:
  514. """Returns true if left and right are overlapping tuples."""
  515. left, right = get_proper_types((left, right))
  516. left = adjust_tuple(left, right) or left
  517. right = adjust_tuple(right, left) or right
  518. assert isinstance(left, TupleType), f"Type {left} is not a tuple"
  519. assert isinstance(right, TupleType), f"Type {right} is not a tuple"
  520. if len(left.items) != len(right.items):
  521. return False
  522. return all(
  523. is_overlapping_types(
  524. l,
  525. r,
  526. ignore_promotions=ignore_promotions,
  527. prohibit_none_typevar_overlap=prohibit_none_typevar_overlap,
  528. )
  529. for l, r in zip(left.items, right.items)
  530. )
  531. def adjust_tuple(left: ProperType, r: ProperType) -> TupleType | None:
  532. """Find out if `left` is a Tuple[A, ...], and adjust its length to `right`"""
  533. if isinstance(left, Instance) and left.type.fullname == "builtins.tuple":
  534. n = r.length() if isinstance(r, TupleType) else 1
  535. return TupleType([left.args[0]] * n, left)
  536. return None
  537. def is_tuple(typ: Type) -> bool:
  538. typ = get_proper_type(typ)
  539. return isinstance(typ, TupleType) or (
  540. isinstance(typ, Instance) and typ.type.fullname == "builtins.tuple"
  541. )
  542. class TypeMeetVisitor(TypeVisitor[ProperType]):
  543. def __init__(self, s: ProperType) -> None:
  544. self.s = s
  545. def visit_unbound_type(self, t: UnboundType) -> ProperType:
  546. if isinstance(self.s, NoneType):
  547. if state.strict_optional:
  548. return AnyType(TypeOfAny.special_form)
  549. else:
  550. return self.s
  551. elif isinstance(self.s, UninhabitedType):
  552. return self.s
  553. else:
  554. return AnyType(TypeOfAny.special_form)
  555. def visit_any(self, t: AnyType) -> ProperType:
  556. return self.s
  557. def visit_union_type(self, t: UnionType) -> ProperType:
  558. if isinstance(self.s, UnionType):
  559. meets: list[Type] = []
  560. for x in t.items:
  561. for y in self.s.items:
  562. meets.append(meet_types(x, y))
  563. else:
  564. meets = [meet_types(x, self.s) for x in t.items]
  565. return make_simplified_union(meets)
  566. def visit_none_type(self, t: NoneType) -> ProperType:
  567. if state.strict_optional:
  568. if isinstance(self.s, NoneType) or (
  569. isinstance(self.s, Instance) and self.s.type.fullname == "builtins.object"
  570. ):
  571. return t
  572. else:
  573. return UninhabitedType()
  574. else:
  575. return t
  576. def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:
  577. return t
  578. def visit_deleted_type(self, t: DeletedType) -> ProperType:
  579. if isinstance(self.s, NoneType):
  580. if state.strict_optional:
  581. return t
  582. else:
  583. return self.s
  584. elif isinstance(self.s, UninhabitedType):
  585. return self.s
  586. else:
  587. return t
  588. def visit_erased_type(self, t: ErasedType) -> ProperType:
  589. return self.s
  590. def visit_type_var(self, t: TypeVarType) -> ProperType:
  591. if isinstance(self.s, TypeVarType) and self.s.id == t.id:
  592. return self.s
  593. else:
  594. return self.default(self.s)
  595. def visit_param_spec(self, t: ParamSpecType) -> ProperType:
  596. if self.s == t:
  597. return self.s
  598. else:
  599. return self.default(self.s)
  600. def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:
  601. if self.s == t:
  602. return self.s
  603. else:
  604. return self.default(self.s)
  605. def visit_unpack_type(self, t: UnpackType) -> ProperType:
  606. raise NotImplementedError
  607. def visit_parameters(self, t: Parameters) -> ProperType:
  608. # TODO: is this the right variance?
  609. if isinstance(self.s, (Parameters, CallableType)):
  610. if len(t.arg_types) != len(self.s.arg_types):
  611. return self.default(self.s)
  612. return t.copy_modified(
  613. arg_types=[meet_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types)]
  614. )
  615. else:
  616. return self.default(self.s)
  617. def visit_instance(self, t: Instance) -> ProperType:
  618. if isinstance(self.s, Instance):
  619. if t.type == self.s.type:
  620. if is_subtype(t, self.s) or is_subtype(self.s, t):
  621. # Combine type arguments. We could have used join below
  622. # equivalently.
  623. args: list[Type] = []
  624. # N.B: We use zip instead of indexing because the lengths might have
  625. # mismatches during daemon reprocessing.
  626. for ta, sia in zip(t.args, self.s.args):
  627. args.append(self.meet(ta, sia))
  628. return Instance(t.type, args)
  629. else:
  630. if state.strict_optional:
  631. return UninhabitedType()
  632. else:
  633. return NoneType()
  634. else:
  635. alt_promote = t.type.alt_promote
  636. if alt_promote and alt_promote.type is self.s.type:
  637. return t
  638. alt_promote = self.s.type.alt_promote
  639. if alt_promote and alt_promote.type is t.type:
  640. return self.s
  641. if is_subtype(t, self.s):
  642. return t
  643. elif is_subtype(self.s, t):
  644. # See also above comment.
  645. return self.s
  646. else:
  647. if state.strict_optional:
  648. return UninhabitedType()
  649. else:
  650. return NoneType()
  651. elif isinstance(self.s, FunctionLike) and t.type.is_protocol:
  652. call = join.unpack_callback_protocol(t)
  653. if call:
  654. return meet_types(call, self.s)
  655. elif isinstance(self.s, FunctionLike) and self.s.is_type_obj() and t.type.is_metaclass():
  656. if is_subtype(self.s.fallback, t):
  657. return self.s
  658. return self.default(self.s)
  659. elif isinstance(self.s, TypeType):
  660. return meet_types(t, self.s)
  661. elif isinstance(self.s, TupleType):
  662. return meet_types(t, self.s)
  663. elif isinstance(self.s, LiteralType):
  664. return meet_types(t, self.s)
  665. elif isinstance(self.s, TypedDictType):
  666. return meet_types(t, self.s)
  667. return self.default(self.s)
  668. def visit_callable_type(self, t: CallableType) -> ProperType:
  669. if isinstance(self.s, CallableType) and join.is_similar_callables(t, self.s):
  670. if is_equivalent(t, self.s):
  671. return join.combine_similar_callables(t, self.s)
  672. result = meet_similar_callables(t, self.s)
  673. # We set the from_type_type flag to suppress error when a collection of
  674. # concrete class objects gets inferred as their common abstract superclass.
  675. if not (
  676. (t.is_type_obj() and t.type_object().is_abstract)
  677. or (self.s.is_type_obj() and self.s.type_object().is_abstract)
  678. ):
  679. result.from_type_type = True
  680. if isinstance(get_proper_type(result.ret_type), UninhabitedType):
  681. # Return a plain None or <uninhabited> instead of a weird function.
  682. return self.default(self.s)
  683. return result
  684. elif isinstance(self.s, TypeType) and t.is_type_obj() and not t.is_generic():
  685. # In this case we are able to potentially produce a better meet.
  686. res = meet_types(self.s.item, t.ret_type)
  687. if not isinstance(res, (NoneType, UninhabitedType)):
  688. return TypeType.make_normalized(res)
  689. return self.default(self.s)
  690. elif isinstance(self.s, Instance) and self.s.type.is_protocol:
  691. call = join.unpack_callback_protocol(self.s)
  692. if call:
  693. return meet_types(t, call)
  694. return self.default(self.s)
  695. def visit_overloaded(self, t: Overloaded) -> ProperType:
  696. # TODO: Implement a better algorithm that covers at least the same cases
  697. # as TypeJoinVisitor.visit_overloaded().
  698. s = self.s
  699. if isinstance(s, FunctionLike):
  700. if s.items == t.items:
  701. return Overloaded(t.items)
  702. elif is_subtype(s, t):
  703. return s
  704. elif is_subtype(t, s):
  705. return t
  706. else:
  707. return meet_types(t.fallback, s.fallback)
  708. elif isinstance(self.s, Instance) and self.s.type.is_protocol:
  709. call = join.unpack_callback_protocol(self.s)
  710. if call:
  711. return meet_types(t, call)
  712. return meet_types(t.fallback, s)
  713. def visit_tuple_type(self, t: TupleType) -> ProperType:
  714. if isinstance(self.s, TupleType) and self.s.length() == t.length():
  715. items: list[Type] = []
  716. for i in range(t.length()):
  717. items.append(self.meet(t.items[i], self.s.items[i]))
  718. # TODO: What if the fallbacks are different?
  719. return TupleType(items, tuple_fallback(t))
  720. elif isinstance(self.s, Instance):
  721. # meet(Tuple[t1, t2, <...>], Tuple[s, ...]) == Tuple[meet(t1, s), meet(t2, s), <...>].
  722. if self.s.type.fullname == "builtins.tuple" and self.s.args:
  723. return t.copy_modified(items=[meet_types(it, self.s.args[0]) for it in t.items])
  724. elif is_proper_subtype(t, self.s):
  725. # A named tuple that inherits from a normal class
  726. return t
  727. return self.default(self.s)
  728. def visit_typeddict_type(self, t: TypedDictType) -> ProperType:
  729. if isinstance(self.s, TypedDictType):
  730. for name, l, r in self.s.zip(t):
  731. if not is_equivalent(l, r) or (name in t.required_keys) != (
  732. name in self.s.required_keys
  733. ):
  734. return self.default(self.s)
  735. item_list: list[tuple[str, Type]] = []
  736. for item_name, s_item_type, t_item_type in self.s.zipall(t):
  737. if s_item_type is not None:
  738. item_list.append((item_name, s_item_type))
  739. else:
  740. # at least one of s_item_type and t_item_type is not None
  741. assert t_item_type is not None
  742. item_list.append((item_name, t_item_type))
  743. items = dict(item_list)
  744. fallback = self.s.create_anonymous_fallback()
  745. required_keys = t.required_keys | self.s.required_keys
  746. return TypedDictType(items, required_keys, fallback)
  747. elif isinstance(self.s, Instance) and is_subtype(t, self.s):
  748. return t
  749. else:
  750. return self.default(self.s)
  751. def visit_literal_type(self, t: LiteralType) -> ProperType:
  752. if isinstance(self.s, LiteralType) and self.s == t:
  753. return t
  754. elif isinstance(self.s, Instance) and is_subtype(t.fallback, self.s):
  755. return t
  756. else:
  757. return self.default(self.s)
  758. def visit_partial_type(self, t: PartialType) -> ProperType:
  759. # We can't determine the meet of partial types. We should never get here.
  760. assert False, "Internal error"
  761. def visit_type_type(self, t: TypeType) -> ProperType:
  762. if isinstance(self.s, TypeType):
  763. typ = self.meet(t.item, self.s.item)
  764. if not isinstance(typ, NoneType):
  765. typ = TypeType.make_normalized(typ, line=t.line)
  766. return typ
  767. elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type":
  768. return t
  769. elif isinstance(self.s, CallableType):
  770. return self.meet(t, self.s)
  771. else:
  772. return self.default(self.s)
  773. def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:
  774. assert False, f"This should be never called, got {t}"
  775. def meet(self, s: Type, t: Type) -> ProperType:
  776. return meet_types(s, t)
  777. def default(self, typ: Type) -> ProperType:
  778. if isinstance(typ, UnboundType):
  779. return AnyType(TypeOfAny.special_form)
  780. else:
  781. if state.strict_optional:
  782. return UninhabitedType()
  783. else:
  784. return NoneType()
  785. def meet_similar_callables(t: CallableType, s: CallableType) -> CallableType:
  786. from mypy.join import join_types
  787. arg_types: list[Type] = []
  788. for i in range(len(t.arg_types)):
  789. arg_types.append(join_types(t.arg_types[i], s.arg_types[i]))
  790. # TODO in combine_similar_callables also applies here (names and kinds)
  791. # The fallback type can be either 'function' or 'type'. The result should have 'function' as
  792. # fallback only if both operands have it as 'function'.
  793. if t.fallback.type.fullname != "builtins.function":
  794. fallback = t.fallback
  795. else:
  796. fallback = s.fallback
  797. return t.copy_modified(
  798. arg_types=arg_types,
  799. ret_type=meet_types(t.ret_type, s.ret_type),
  800. fallback=fallback,
  801. name=None,
  802. )
  803. def meet_type_list(types: list[Type]) -> Type:
  804. if not types:
  805. # This should probably be builtins.object but that is hard to get and
  806. # it doesn't matter for any current users.
  807. return AnyType(TypeOfAny.implementation_artifact)
  808. met = types[0]
  809. for t in types[1:]:
  810. met = meet_types(met, t)
  811. return met
  812. def typed_dict_mapping_pair(left: Type, right: Type) -> bool:
  813. """Is this a pair where one type is a TypedDict and another one is an instance of Mapping?
  814. This case requires a precise/principled consideration because there are two use cases
  815. that push the boundary the opposite ways: we need to avoid spurious overlaps to avoid
  816. false positives for overloads, but we also need to avoid spuriously non-overlapping types
  817. to avoid false positives with --strict-equality.
  818. """
  819. left, right = get_proper_types((left, right))
  820. assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType)
  821. if isinstance(left, TypedDictType):
  822. _, other = left, right
  823. elif isinstance(right, TypedDictType):
  824. _, other = right, left
  825. else:
  826. return False
  827. return isinstance(other, Instance) and other.type.has_base("typing.Mapping")
  828. def typed_dict_mapping_overlap(
  829. left: Type, right: Type, overlapping: Callable[[Type, Type], bool]
  830. ) -> bool:
  831. """Check if a TypedDict type is overlapping with a Mapping.
  832. The basic logic here consists of two rules:
  833. * A TypedDict with some required keys is overlapping with Mapping[str, <some type>]
  834. if and only if every key type is overlapping with <some type>. For example:
  835. - TypedDict(x=int, y=str) overlaps with Dict[str, Union[str, int]]
  836. - TypedDict(x=int, y=str) doesn't overlap with Dict[str, int]
  837. Note that any additional non-required keys can't change the above result.
  838. * A TypedDict with no required keys overlaps with Mapping[str, <some type>] if and
  839. only if at least one of key types overlaps with <some type>. For example:
  840. - TypedDict(x=str, y=str, total=False) overlaps with Dict[str, str]
  841. - TypedDict(x=str, y=str, total=False) doesn't overlap with Dict[str, int]
  842. - TypedDict(x=int, y=str, total=False) overlaps with Dict[str, str]
  843. As usual empty, dictionaries lie in a gray area. In general, List[str] and List[str]
  844. are considered non-overlapping despite empty list belongs to both. However, List[int]
  845. and List[<nothing>] are considered overlapping.
  846. So here we follow the same logic: a TypedDict with no required keys is considered
  847. non-overlapping with Mapping[str, <some type>], but is considered overlapping with
  848. Mapping[<nothing>, <nothing>]. This way we avoid false positives for overloads, and also
  849. avoid false positives for comparisons like SomeTypedDict == {} under --strict-equality.
  850. """
  851. left, right = get_proper_types((left, right))
  852. assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType)
  853. if isinstance(left, TypedDictType):
  854. assert isinstance(right, Instance)
  855. typed, other = left, right
  856. else:
  857. assert isinstance(left, Instance)
  858. assert isinstance(right, TypedDictType)
  859. typed, other = right, left
  860. mapping = next(base for base in other.type.mro if base.fullname == "typing.Mapping")
  861. other = map_instance_to_supertype(other, mapping)
  862. key_type, value_type = get_proper_types(other.args)
  863. # TODO: is there a cleaner way to get str_type here?
  864. fallback = typed.as_anonymous().fallback
  865. str_type = fallback.type.bases[0].args[0] # typing._TypedDict inherits Mapping[str, object]
  866. # Special case: a TypedDict with no required keys overlaps with an empty dict.
  867. if isinstance(key_type, UninhabitedType) and isinstance(value_type, UninhabitedType):
  868. return not typed.required_keys
  869. if typed.required_keys:
  870. if not overlapping(key_type, str_type):
  871. return False
  872. return all(overlapping(typed.items[k], value_type) for k in typed.required_keys)
  873. else:
  874. if not overlapping(key_type, str_type):
  875. return False
  876. non_required = set(typed.items.keys()) - typed.required_keys
  877. return any(overlapping(typed.items[k], value_type) for k in non_required)