join.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. """Calculation of the least upper bound types (joins)."""
  2. from __future__ import annotations
  3. from typing import overload
  4. import mypy.typeops
  5. from mypy.maptype import map_instance_to_supertype
  6. from mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT
  7. from mypy.state import state
  8. from mypy.subtypes import (
  9. SubtypeContext,
  10. find_member,
  11. is_equivalent,
  12. is_proper_subtype,
  13. is_protocol_implementation,
  14. is_subtype,
  15. )
  16. from mypy.types import (
  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. TypeOfAny,
  35. TypeType,
  36. TypeVarTupleType,
  37. TypeVarType,
  38. TypeVisitor,
  39. UnboundType,
  40. UninhabitedType,
  41. UnionType,
  42. UnpackType,
  43. get_proper_type,
  44. get_proper_types,
  45. )
  46. class InstanceJoiner:
  47. def __init__(self) -> None:
  48. self.seen_instances: list[tuple[Instance, Instance]] = []
  49. def join_instances(self, t: Instance, s: Instance) -> ProperType:
  50. if (t, s) in self.seen_instances or (s, t) in self.seen_instances:
  51. return object_from_instance(t)
  52. self.seen_instances.append((t, s))
  53. # Calculate the join of two instance types
  54. if t.type == s.type:
  55. # Simplest case: join two types with the same base type (but
  56. # potentially different arguments).
  57. # Combine type arguments.
  58. args: list[Type] = []
  59. # N.B: We use zip instead of indexing because the lengths might have
  60. # mismatches during daemon reprocessing.
  61. for ta, sa, type_var in zip(t.args, s.args, t.type.defn.type_vars):
  62. ta_proper = get_proper_type(ta)
  63. sa_proper = get_proper_type(sa)
  64. new_type: Type | None = None
  65. if isinstance(ta_proper, AnyType):
  66. new_type = AnyType(TypeOfAny.from_another_any, ta_proper)
  67. elif isinstance(sa_proper, AnyType):
  68. new_type = AnyType(TypeOfAny.from_another_any, sa_proper)
  69. elif isinstance(type_var, TypeVarType):
  70. if type_var.variance == COVARIANT:
  71. new_type = join_types(ta, sa, self)
  72. if len(type_var.values) != 0 and new_type not in type_var.values:
  73. self.seen_instances.pop()
  74. return object_from_instance(t)
  75. if not is_subtype(new_type, type_var.upper_bound):
  76. self.seen_instances.pop()
  77. return object_from_instance(t)
  78. # TODO: contravariant case should use meet but pass seen instances as
  79. # an argument to keep track of recursive checks.
  80. elif type_var.variance in (INVARIANT, CONTRAVARIANT):
  81. if not is_equivalent(ta, sa):
  82. self.seen_instances.pop()
  83. return object_from_instance(t)
  84. # If the types are different but equivalent, then an Any is involved
  85. # so using a join in the contravariant case is also OK.
  86. new_type = join_types(ta, sa, self)
  87. else:
  88. # ParamSpec type variables behave the same, independent of variance
  89. if not is_equivalent(ta, sa):
  90. return get_proper_type(type_var.upper_bound)
  91. new_type = join_types(ta, sa, self)
  92. assert new_type is not None
  93. args.append(new_type)
  94. result: ProperType = Instance(t.type, args)
  95. elif t.type.bases and is_proper_subtype(
  96. t, s, subtype_context=SubtypeContext(ignore_type_params=True)
  97. ):
  98. result = self.join_instances_via_supertype(t, s)
  99. else:
  100. # Now t is not a subtype of s, and t != s. Now s could be a subtype
  101. # of t; alternatively, we need to find a common supertype. This works
  102. # in of the both cases.
  103. result = self.join_instances_via_supertype(s, t)
  104. self.seen_instances.pop()
  105. return result
  106. def join_instances_via_supertype(self, t: Instance, s: Instance) -> ProperType:
  107. # Give preference to joins via duck typing relationship, so that
  108. # join(int, float) == float, for example.
  109. for p in t.type._promote:
  110. if is_subtype(p, s):
  111. return join_types(p, s, self)
  112. for p in s.type._promote:
  113. if is_subtype(p, t):
  114. return join_types(t, p, self)
  115. # Compute the "best" supertype of t when joined with s.
  116. # The definition of "best" may evolve; for now it is the one with
  117. # the longest MRO. Ties are broken by using the earlier base.
  118. best: ProperType | None = None
  119. for base in t.type.bases:
  120. mapped = map_instance_to_supertype(t, base.type)
  121. res = self.join_instances(mapped, s)
  122. if best is None or is_better(res, best):
  123. best = res
  124. assert best is not None
  125. for promote in t.type._promote:
  126. if isinstance(promote, Instance):
  127. res = self.join_instances(promote, s)
  128. if is_better(res, best):
  129. best = res
  130. return best
  131. def join_simple(declaration: Type | None, s: Type, t: Type) -> ProperType:
  132. """Return a simple least upper bound given the declared type.
  133. This function should be only used by binder, and should not recurse.
  134. For all other uses, use `join_types()`.
  135. """
  136. declaration = get_proper_type(declaration)
  137. s = get_proper_type(s)
  138. t = get_proper_type(t)
  139. if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):
  140. # if types are restricted in different ways, use the more general versions
  141. s = mypy.typeops.true_or_false(s)
  142. t = mypy.typeops.true_or_false(t)
  143. if isinstance(s, AnyType):
  144. return s
  145. if isinstance(s, ErasedType):
  146. return t
  147. if is_proper_subtype(s, t, ignore_promotions=True):
  148. return t
  149. if is_proper_subtype(t, s, ignore_promotions=True):
  150. return s
  151. if isinstance(declaration, UnionType):
  152. return mypy.typeops.make_simplified_union([s, t])
  153. if isinstance(s, NoneType) and not isinstance(t, NoneType):
  154. s, t = t, s
  155. if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):
  156. s, t = t, s
  157. # Meets/joins require callable type normalization.
  158. s, t = normalize_callables(s, t)
  159. if isinstance(s, UnionType) and not isinstance(t, UnionType):
  160. s, t = t, s
  161. value = t.accept(TypeJoinVisitor(s))
  162. if declaration is None or is_subtype(value, declaration):
  163. return value
  164. return declaration
  165. def trivial_join(s: Type, t: Type) -> Type:
  166. """Return one of types (expanded) if it is a supertype of other, otherwise top type."""
  167. if is_subtype(s, t):
  168. return t
  169. elif is_subtype(t, s):
  170. return s
  171. else:
  172. return object_or_any_from_type(get_proper_type(t))
  173. @overload
  174. def join_types(
  175. s: ProperType, t: ProperType, instance_joiner: InstanceJoiner | None = None
  176. ) -> ProperType:
  177. ...
  178. @overload
  179. def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type:
  180. ...
  181. def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type:
  182. """Return the least upper bound of s and t.
  183. For example, the join of 'int' and 'object' is 'object'.
  184. """
  185. if mypy.typeops.is_recursive_pair(s, t):
  186. # This case can trigger an infinite recursion, general support for this will be
  187. # tricky so we use a trivial join (like for protocols).
  188. return trivial_join(s, t)
  189. s = get_proper_type(s)
  190. t = get_proper_type(t)
  191. if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):
  192. # if types are restricted in different ways, use the more general versions
  193. s = mypy.typeops.true_or_false(s)
  194. t = mypy.typeops.true_or_false(t)
  195. if isinstance(s, UnionType) and not isinstance(t, UnionType):
  196. s, t = t, s
  197. if isinstance(s, AnyType):
  198. return s
  199. if isinstance(s, ErasedType):
  200. return t
  201. if isinstance(s, NoneType) and not isinstance(t, NoneType):
  202. s, t = t, s
  203. if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):
  204. s, t = t, s
  205. # Meets/joins require callable type normalization.
  206. s, t = normalize_callables(s, t)
  207. # Use a visitor to handle non-trivial cases.
  208. return t.accept(TypeJoinVisitor(s, instance_joiner))
  209. class TypeJoinVisitor(TypeVisitor[ProperType]):
  210. """Implementation of the least upper bound algorithm.
  211. Attributes:
  212. s: The other (left) type operand.
  213. """
  214. def __init__(self, s: ProperType, instance_joiner: InstanceJoiner | None = None) -> None:
  215. self.s = s
  216. self.instance_joiner = instance_joiner
  217. def visit_unbound_type(self, t: UnboundType) -> ProperType:
  218. return AnyType(TypeOfAny.special_form)
  219. def visit_union_type(self, t: UnionType) -> ProperType:
  220. if is_proper_subtype(self.s, t):
  221. return t
  222. else:
  223. return mypy.typeops.make_simplified_union([self.s, t])
  224. def visit_any(self, t: AnyType) -> ProperType:
  225. return t
  226. def visit_none_type(self, t: NoneType) -> ProperType:
  227. if state.strict_optional:
  228. if isinstance(self.s, (NoneType, UninhabitedType)):
  229. return t
  230. elif isinstance(self.s, UnboundType):
  231. return AnyType(TypeOfAny.special_form)
  232. else:
  233. return mypy.typeops.make_simplified_union([self.s, t])
  234. else:
  235. return self.s
  236. def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:
  237. return self.s
  238. def visit_deleted_type(self, t: DeletedType) -> ProperType:
  239. return self.s
  240. def visit_erased_type(self, t: ErasedType) -> ProperType:
  241. return self.s
  242. def visit_type_var(self, t: TypeVarType) -> ProperType:
  243. if isinstance(self.s, TypeVarType) and self.s.id == t.id:
  244. return self.s
  245. else:
  246. return self.default(self.s)
  247. def visit_param_spec(self, t: ParamSpecType) -> ProperType:
  248. if self.s == t:
  249. return t
  250. return self.default(self.s)
  251. def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:
  252. if self.s == t:
  253. return t
  254. return self.default(self.s)
  255. def visit_unpack_type(self, t: UnpackType) -> UnpackType:
  256. raise NotImplementedError
  257. def visit_parameters(self, t: Parameters) -> ProperType:
  258. if self.s == t:
  259. return t
  260. else:
  261. return self.default(self.s)
  262. def visit_instance(self, t: Instance) -> ProperType:
  263. if isinstance(self.s, Instance):
  264. if self.instance_joiner is None:
  265. self.instance_joiner = InstanceJoiner()
  266. nominal = self.instance_joiner.join_instances(t, self.s)
  267. structural: Instance | None = None
  268. if t.type.is_protocol and is_protocol_implementation(self.s, t):
  269. structural = t
  270. elif self.s.type.is_protocol and is_protocol_implementation(t, self.s):
  271. structural = self.s
  272. # Structural join is preferred in the case where we have found both
  273. # structural and nominal and they have same MRO length (see two comments
  274. # in join_instances_via_supertype). Otherwise, just return the nominal join.
  275. if not structural or is_better(nominal, structural):
  276. return nominal
  277. return structural
  278. elif isinstance(self.s, FunctionLike):
  279. if t.type.is_protocol:
  280. call = unpack_callback_protocol(t)
  281. if call:
  282. return join_types(call, self.s)
  283. return join_types(t, self.s.fallback)
  284. elif isinstance(self.s, TypeType):
  285. return join_types(t, self.s)
  286. elif isinstance(self.s, TypedDictType):
  287. return join_types(t, self.s)
  288. elif isinstance(self.s, TupleType):
  289. return join_types(t, self.s)
  290. elif isinstance(self.s, LiteralType):
  291. return join_types(t, self.s)
  292. else:
  293. return self.default(self.s)
  294. def visit_callable_type(self, t: CallableType) -> ProperType:
  295. if isinstance(self.s, CallableType) and is_similar_callables(t, self.s):
  296. if is_equivalent(t, self.s):
  297. return combine_similar_callables(t, self.s)
  298. result = join_similar_callables(t, self.s)
  299. # We set the from_type_type flag to suppress error when a collection of
  300. # concrete class objects gets inferred as their common abstract superclass.
  301. if not (
  302. (t.is_type_obj() and t.type_object().is_abstract)
  303. or (self.s.is_type_obj() and self.s.type_object().is_abstract)
  304. ):
  305. result.from_type_type = True
  306. if any(
  307. isinstance(tp, (NoneType, UninhabitedType))
  308. for tp in get_proper_types(result.arg_types)
  309. ):
  310. # We don't want to return unusable Callable, attempt fallback instead.
  311. return join_types(t.fallback, self.s)
  312. return result
  313. elif isinstance(self.s, Overloaded):
  314. # Switch the order of arguments to that we'll get to visit_overloaded.
  315. return join_types(t, self.s)
  316. elif isinstance(self.s, Instance) and self.s.type.is_protocol:
  317. call = unpack_callback_protocol(self.s)
  318. if call:
  319. return join_types(t, call)
  320. return join_types(t.fallback, self.s)
  321. def visit_overloaded(self, t: Overloaded) -> ProperType:
  322. # This is more complex than most other cases. Here are some
  323. # examples that illustrate how this works.
  324. #
  325. # First let's define a concise notation:
  326. # - Cn are callable types (for n in 1, 2, ...)
  327. # - Ov(C1, C2, ...) is an overloaded type with items C1, C2, ...
  328. # - Callable[[T, ...], S] is written as [T, ...] -> S.
  329. #
  330. # We want some basic properties to hold (assume Cn are all
  331. # unrelated via Any-similarity):
  332. #
  333. # join(Ov(C1, C2), C1) == C1
  334. # join(Ov(C1, C2), Ov(C1, C2)) == Ov(C1, C2)
  335. # join(Ov(C1, C2), Ov(C1, C3)) == C1
  336. # join(Ov(C2, C2), C3) == join of fallback types
  337. #
  338. # The presence of Any types makes things more interesting. The join is the
  339. # most general type we can get with respect to Any:
  340. #
  341. # join(Ov([int] -> int, [str] -> str), [Any] -> str) == Any -> str
  342. #
  343. # We could use a simplification step that removes redundancies, but that's not
  344. # implemented right now. Consider this example, where we get a redundancy:
  345. #
  346. # join(Ov([int, Any] -> Any, [str, Any] -> Any), [Any, int] -> Any) ==
  347. # Ov([Any, int] -> Any, [Any, int] -> Any)
  348. #
  349. # TODO: Consider more cases of callable subtyping.
  350. result: list[CallableType] = []
  351. s = self.s
  352. if isinstance(s, FunctionLike):
  353. # The interesting case where both types are function types.
  354. for t_item in t.items:
  355. for s_item in s.items:
  356. if is_similar_callables(t_item, s_item):
  357. if is_equivalent(t_item, s_item):
  358. result.append(combine_similar_callables(t_item, s_item))
  359. elif is_subtype(t_item, s_item):
  360. result.append(s_item)
  361. if result:
  362. # TODO: Simplify redundancies from the result.
  363. if len(result) == 1:
  364. return result[0]
  365. else:
  366. return Overloaded(result)
  367. return join_types(t.fallback, s.fallback)
  368. elif isinstance(s, Instance) and s.type.is_protocol:
  369. call = unpack_callback_protocol(s)
  370. if call:
  371. return join_types(t, call)
  372. return join_types(t.fallback, s)
  373. def visit_tuple_type(self, t: TupleType) -> ProperType:
  374. # When given two fixed-length tuples:
  375. # * If they have the same length, join their subtypes item-wise:
  376. # Tuple[int, bool] + Tuple[bool, bool] becomes Tuple[int, bool]
  377. # * If lengths do not match, return a variadic tuple:
  378. # Tuple[bool, int] + Tuple[bool] becomes Tuple[int, ...]
  379. #
  380. # Otherwise, `t` is a fixed-length tuple but `self.s` is NOT:
  381. # * Joining with a variadic tuple returns variadic tuple:
  382. # Tuple[int, bool] + Tuple[bool, ...] becomes Tuple[int, ...]
  383. # * Joining with any Sequence also returns a Sequence:
  384. # Tuple[int, bool] + List[bool] becomes Sequence[int]
  385. if isinstance(self.s, TupleType) and self.s.length() == t.length():
  386. if self.instance_joiner is None:
  387. self.instance_joiner = InstanceJoiner()
  388. fallback = self.instance_joiner.join_instances(
  389. mypy.typeops.tuple_fallback(self.s), mypy.typeops.tuple_fallback(t)
  390. )
  391. assert isinstance(fallback, Instance)
  392. if self.s.length() == t.length():
  393. items: list[Type] = []
  394. for i in range(t.length()):
  395. items.append(join_types(t.items[i], self.s.items[i]))
  396. return TupleType(items, fallback)
  397. else:
  398. return fallback
  399. else:
  400. return join_types(self.s, mypy.typeops.tuple_fallback(t))
  401. def visit_typeddict_type(self, t: TypedDictType) -> ProperType:
  402. if isinstance(self.s, TypedDictType):
  403. items = {
  404. item_name: s_item_type
  405. for (item_name, s_item_type, t_item_type) in self.s.zip(t)
  406. if (
  407. is_equivalent(s_item_type, t_item_type)
  408. and (item_name in t.required_keys) == (item_name in self.s.required_keys)
  409. )
  410. }
  411. fallback = self.s.create_anonymous_fallback()
  412. # We need to filter by items.keys() since some required keys present in both t and
  413. # self.s might be missing from the join if the types are incompatible.
  414. required_keys = set(items.keys()) & t.required_keys & self.s.required_keys
  415. return TypedDictType(items, required_keys, fallback)
  416. elif isinstance(self.s, Instance):
  417. return join_types(self.s, t.fallback)
  418. else:
  419. return self.default(self.s)
  420. def visit_literal_type(self, t: LiteralType) -> ProperType:
  421. if isinstance(self.s, LiteralType):
  422. if t == self.s:
  423. return t
  424. if self.s.fallback.type.is_enum and t.fallback.type.is_enum:
  425. return mypy.typeops.make_simplified_union([self.s, t])
  426. return join_types(self.s.fallback, t.fallback)
  427. else:
  428. return join_types(self.s, t.fallback)
  429. def visit_partial_type(self, t: PartialType) -> ProperType:
  430. # We only have partial information so we can't decide the join result. We should
  431. # never get here.
  432. assert False, "Internal error"
  433. def visit_type_type(self, t: TypeType) -> ProperType:
  434. if isinstance(self.s, TypeType):
  435. return TypeType.make_normalized(join_types(t.item, self.s.item), line=t.line)
  436. elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type":
  437. return self.s
  438. else:
  439. return self.default(self.s)
  440. def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:
  441. assert False, f"This should be never called, got {t}"
  442. def default(self, typ: Type) -> ProperType:
  443. typ = get_proper_type(typ)
  444. if isinstance(typ, Instance):
  445. return object_from_instance(typ)
  446. elif isinstance(typ, UnboundType):
  447. return AnyType(TypeOfAny.special_form)
  448. elif isinstance(typ, TupleType):
  449. return self.default(mypy.typeops.tuple_fallback(typ))
  450. elif isinstance(typ, TypedDictType):
  451. return self.default(typ.fallback)
  452. elif isinstance(typ, FunctionLike):
  453. return self.default(typ.fallback)
  454. elif isinstance(typ, TypeVarType):
  455. return self.default(typ.upper_bound)
  456. elif isinstance(typ, ParamSpecType):
  457. return self.default(typ.upper_bound)
  458. else:
  459. return AnyType(TypeOfAny.special_form)
  460. def is_better(t: Type, s: Type) -> bool:
  461. # Given two possible results from join_instances_via_supertype(),
  462. # indicate whether t is the better one.
  463. t = get_proper_type(t)
  464. s = get_proper_type(s)
  465. if isinstance(t, Instance):
  466. if not isinstance(s, Instance):
  467. return True
  468. # Use len(mro) as a proxy for the better choice.
  469. if len(t.type.mro) > len(s.type.mro):
  470. return True
  471. return False
  472. def normalize_callables(s: ProperType, t: ProperType) -> tuple[ProperType, ProperType]:
  473. if isinstance(s, (CallableType, Overloaded)):
  474. s = s.with_unpacked_kwargs()
  475. if isinstance(t, (CallableType, Overloaded)):
  476. t = t.with_unpacked_kwargs()
  477. return s, t
  478. def is_similar_callables(t: CallableType, s: CallableType) -> bool:
  479. """Return True if t and s have identical numbers of
  480. arguments, default arguments and varargs.
  481. """
  482. return (
  483. len(t.arg_types) == len(s.arg_types)
  484. and t.min_args == s.min_args
  485. and t.is_var_arg == s.is_var_arg
  486. )
  487. def join_similar_callables(t: CallableType, s: CallableType) -> CallableType:
  488. from mypy.meet import meet_types
  489. arg_types: list[Type] = []
  490. for i in range(len(t.arg_types)):
  491. arg_types.append(meet_types(t.arg_types[i], s.arg_types[i]))
  492. # TODO in combine_similar_callables also applies here (names and kinds; user metaclasses)
  493. # The fallback type can be either 'function', 'type', or some user-provided metaclass.
  494. # The result should always use 'function' as a fallback if either operands are using it.
  495. if t.fallback.type.fullname == "builtins.function":
  496. fallback = t.fallback
  497. else:
  498. fallback = s.fallback
  499. return t.copy_modified(
  500. arg_types=arg_types,
  501. arg_names=combine_arg_names(t, s),
  502. ret_type=join_types(t.ret_type, s.ret_type),
  503. fallback=fallback,
  504. name=None,
  505. )
  506. def combine_similar_callables(t: CallableType, s: CallableType) -> CallableType:
  507. arg_types: list[Type] = []
  508. for i in range(len(t.arg_types)):
  509. arg_types.append(join_types(t.arg_types[i], s.arg_types[i]))
  510. # TODO kinds and argument names
  511. # TODO what should happen if one fallback is 'type' and the other is a user-provided metaclass?
  512. # The fallback type can be either 'function', 'type', or some user-provided metaclass.
  513. # The result should always use 'function' as a fallback if either operands are using it.
  514. if t.fallback.type.fullname == "builtins.function":
  515. fallback = t.fallback
  516. else:
  517. fallback = s.fallback
  518. return t.copy_modified(
  519. arg_types=arg_types,
  520. arg_names=combine_arg_names(t, s),
  521. ret_type=join_types(t.ret_type, s.ret_type),
  522. fallback=fallback,
  523. name=None,
  524. )
  525. def combine_arg_names(t: CallableType, s: CallableType) -> list[str | None]:
  526. """Produces a list of argument names compatible with both callables.
  527. For example, suppose 't' and 's' have the following signatures:
  528. - t: (a: int, b: str, X: str) -> None
  529. - s: (a: int, b: str, Y: str) -> None
  530. This function would return ["a", "b", None]. This information
  531. is then used above to compute the join of t and s, which results
  532. in a signature of (a: int, b: str, str) -> None.
  533. Note that the third argument's name is omitted and 't' and 's'
  534. are both valid subtypes of this inferred signature.
  535. Precondition: is_similar_types(t, s) is true.
  536. """
  537. num_args = len(t.arg_types)
  538. new_names = []
  539. for i in range(num_args):
  540. t_name = t.arg_names[i]
  541. s_name = s.arg_names[i]
  542. if t_name == s_name or t.arg_kinds[i].is_named() or s.arg_kinds[i].is_named():
  543. new_names.append(t_name)
  544. else:
  545. new_names.append(None)
  546. return new_names
  547. def object_from_instance(instance: Instance) -> Instance:
  548. """Construct the type 'builtins.object' from an instance type."""
  549. # Use the fact that 'object' is always the last class in the mro.
  550. res = Instance(instance.type.mro[-1], [])
  551. return res
  552. def object_or_any_from_type(typ: ProperType) -> ProperType:
  553. # Similar to object_from_instance() but tries hard for all types.
  554. # TODO: find a better way to get object, or make this more reliable.
  555. if isinstance(typ, Instance):
  556. return object_from_instance(typ)
  557. elif isinstance(typ, (CallableType, TypedDictType, LiteralType)):
  558. return object_from_instance(typ.fallback)
  559. elif isinstance(typ, TupleType):
  560. return object_from_instance(typ.partial_fallback)
  561. elif isinstance(typ, TypeType):
  562. return object_or_any_from_type(typ.item)
  563. elif isinstance(typ, TypeVarType) and isinstance(typ.upper_bound, ProperType):
  564. return object_or_any_from_type(typ.upper_bound)
  565. elif isinstance(typ, UnionType):
  566. for item in typ.items:
  567. if isinstance(item, ProperType):
  568. candidate = object_or_any_from_type(item)
  569. if isinstance(candidate, Instance):
  570. return candidate
  571. return AnyType(TypeOfAny.implementation_artifact)
  572. def join_type_list(types: list[Type]) -> Type:
  573. if not types:
  574. # This is a little arbitrary but reasonable. Any empty tuple should be compatible
  575. # with all variable length tuples, and this makes it possible.
  576. return UninhabitedType()
  577. joined = types[0]
  578. for t in types[1:]:
  579. joined = join_types(joined, t)
  580. return joined
  581. def unpack_callback_protocol(t: Instance) -> ProperType | None:
  582. assert t.type.is_protocol
  583. if t.type.protocol_members == ["__call__"]:
  584. return get_proper_type(find_member("__call__", t, t, is_operator=True))
  585. return None