constraints.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. """Type inference constraints."""
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING, Final, Iterable, List, Sequence, cast
  4. import mypy.subtypes
  5. import mypy.typeops
  6. from mypy.argmap import ArgTypeExpander
  7. from mypy.erasetype import erase_typevars
  8. from mypy.maptype import map_instance_to_supertype
  9. from mypy.nodes import ARG_OPT, ARG_POS, CONTRAVARIANT, COVARIANT, ArgKind
  10. from mypy.types import (
  11. TUPLE_LIKE_INSTANCE_NAMES,
  12. AnyType,
  13. CallableType,
  14. DeletedType,
  15. ErasedType,
  16. Instance,
  17. LiteralType,
  18. NoneType,
  19. Overloaded,
  20. Parameters,
  21. ParamSpecType,
  22. PartialType,
  23. ProperType,
  24. TupleType,
  25. Type,
  26. TypeAliasType,
  27. TypedDictType,
  28. TypeOfAny,
  29. TypeQuery,
  30. TypeType,
  31. TypeVarId,
  32. TypeVarLikeType,
  33. TypeVarTupleType,
  34. TypeVarType,
  35. TypeVisitor,
  36. UnboundType,
  37. UninhabitedType,
  38. UnionType,
  39. UnpackType,
  40. callable_with_ellipsis,
  41. get_proper_type,
  42. has_recursive_types,
  43. has_type_vars,
  44. is_named_instance,
  45. split_with_prefix_and_suffix,
  46. )
  47. from mypy.types_utils import is_union_with_any
  48. from mypy.typestate import type_state
  49. from mypy.typevartuples import extract_unpack, find_unpack_in_list, split_with_mapped_and_template
  50. if TYPE_CHECKING:
  51. from mypy.infer import ArgumentInferContext
  52. SUBTYPE_OF: Final = 0
  53. SUPERTYPE_OF: Final = 1
  54. class Constraint:
  55. """A representation of a type constraint.
  56. It can be either T <: type or T :> type (T is a type variable).
  57. """
  58. type_var: TypeVarId
  59. op = 0 # SUBTYPE_OF or SUPERTYPE_OF
  60. target: Type
  61. def __init__(self, type_var: TypeVarLikeType, op: int, target: Type) -> None:
  62. self.type_var = type_var.id
  63. self.op = op
  64. self.target = target
  65. self.origin_type_var = type_var
  66. def __repr__(self) -> str:
  67. op_str = "<:"
  68. if self.op == SUPERTYPE_OF:
  69. op_str = ":>"
  70. return f"{self.type_var} {op_str} {self.target}"
  71. def __hash__(self) -> int:
  72. return hash((self.type_var, self.op, self.target))
  73. def __eq__(self, other: object) -> bool:
  74. if not isinstance(other, Constraint):
  75. return False
  76. return (self.type_var, self.op, self.target) == (other.type_var, other.op, other.target)
  77. def infer_constraints_for_callable(
  78. callee: CallableType,
  79. arg_types: Sequence[Type | None],
  80. arg_kinds: list[ArgKind],
  81. formal_to_actual: list[list[int]],
  82. context: ArgumentInferContext,
  83. ) -> list[Constraint]:
  84. """Infer type variable constraints for a callable and actual arguments.
  85. Return a list of constraints.
  86. """
  87. constraints: list[Constraint] = []
  88. mapper = ArgTypeExpander(context)
  89. for i, actuals in enumerate(formal_to_actual):
  90. if isinstance(callee.arg_types[i], UnpackType):
  91. unpack_type = callee.arg_types[i]
  92. assert isinstance(unpack_type, UnpackType)
  93. # In this case we are binding all of the actuals to *args
  94. # and we want a constraint that the typevar tuple being unpacked
  95. # is equal to a type list of all the actuals.
  96. actual_types = []
  97. for actual in actuals:
  98. actual_arg_type = arg_types[actual]
  99. if actual_arg_type is None:
  100. continue
  101. actual_types.append(
  102. mapper.expand_actual_type(
  103. actual_arg_type,
  104. arg_kinds[actual],
  105. callee.arg_names[i],
  106. callee.arg_kinds[i],
  107. )
  108. )
  109. unpacked_type = get_proper_type(unpack_type.type)
  110. if isinstance(unpacked_type, TypeVarTupleType):
  111. constraints.append(
  112. Constraint(
  113. unpacked_type,
  114. SUPERTYPE_OF,
  115. TupleType(actual_types, unpacked_type.tuple_fallback),
  116. )
  117. )
  118. elif isinstance(unpacked_type, TupleType):
  119. # Prefixes get converted to positional args, so technically the only case we
  120. # should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out
  121. # not to hold we can always handle the prefixes too.
  122. inner_unpack = unpacked_type.items[0]
  123. assert isinstance(inner_unpack, UnpackType)
  124. inner_unpacked_type = inner_unpack.type
  125. assert isinstance(inner_unpacked_type, TypeVarTupleType)
  126. suffix_len = len(unpacked_type.items) - 1
  127. constraints.append(
  128. Constraint(
  129. inner_unpacked_type,
  130. SUPERTYPE_OF,
  131. TupleType(actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback),
  132. )
  133. )
  134. else:
  135. assert False, "mypy bug: unhandled constraint inference case"
  136. else:
  137. for actual in actuals:
  138. actual_arg_type = arg_types[actual]
  139. if actual_arg_type is None:
  140. continue
  141. actual_type = mapper.expand_actual_type(
  142. actual_arg_type, arg_kinds[actual], callee.arg_names[i], callee.arg_kinds[i]
  143. )
  144. c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF)
  145. constraints.extend(c)
  146. return constraints
  147. def infer_constraints(template: Type, actual: Type, direction: int) -> list[Constraint]:
  148. """Infer type constraints.
  149. Match a template type, which may contain type variable references,
  150. recursively against a type which does not contain (the same) type
  151. variable references. The result is a list of type constrains of
  152. form 'T is a supertype/subtype of x', where T is a type variable
  153. present in the template and x is a type without reference to type
  154. variables present in the template.
  155. Assume T and S are type variables. Now the following results can be
  156. calculated (read as '(template, actual) --> result'):
  157. (T, X) --> T :> X
  158. (X[T], X[Y]) --> T <: Y and T :> Y
  159. ((T, T), (X, Y)) --> T :> X and T :> Y
  160. ((T, S), (X, Y)) --> T :> X and S :> Y
  161. (X[T], Any) --> T <: Any and T :> Any
  162. The constraints are represented as Constraint objects.
  163. """
  164. if any(
  165. get_proper_type(template) == get_proper_type(t)
  166. and get_proper_type(actual) == get_proper_type(a)
  167. for (t, a) in reversed(type_state.inferring)
  168. ):
  169. return []
  170. if has_recursive_types(template) or isinstance(get_proper_type(template), Instance):
  171. # This case requires special care because it may cause infinite recursion.
  172. # Note that we include Instances because the may be recursive as str(Sequence[str]).
  173. if not has_type_vars(template):
  174. # Return early on an empty branch.
  175. return []
  176. type_state.inferring.append((template, actual))
  177. res = _infer_constraints(template, actual, direction)
  178. type_state.inferring.pop()
  179. return res
  180. return _infer_constraints(template, actual, direction)
  181. def _infer_constraints(template: Type, actual: Type, direction: int) -> list[Constraint]:
  182. orig_template = template
  183. template = get_proper_type(template)
  184. actual = get_proper_type(actual)
  185. # Type inference shouldn't be affected by whether union types have been simplified.
  186. # We however keep any ErasedType items, so that the caller will see it when using
  187. # checkexpr.has_erased_component().
  188. if isinstance(template, UnionType):
  189. template = mypy.typeops.make_simplified_union(template.items, keep_erased=True)
  190. if isinstance(actual, UnionType):
  191. actual = mypy.typeops.make_simplified_union(actual.items, keep_erased=True)
  192. # Ignore Any types from the type suggestion engine to avoid them
  193. # causing us to infer Any in situations where a better job could
  194. # be done otherwise. (This can produce false positives but that
  195. # doesn't really matter because it is all heuristic anyway.)
  196. if isinstance(actual, AnyType) and actual.type_of_any == TypeOfAny.suggestion_engine:
  197. return []
  198. # If the template is simply a type variable, emit a Constraint directly.
  199. # We need to handle this case before handling Unions for two reasons:
  200. # 1. "T <: Union[U1, U2]" is not equivalent to "T <: U1 or T <: U2",
  201. # because T can itself be a union (notably, Union[U1, U2] itself).
  202. # 2. "T :> Union[U1, U2]" is logically equivalent to "T :> U1 and
  203. # T :> U2", but they are not equivalent to the constraint solver,
  204. # which never introduces new Union types (it uses join() instead).
  205. if isinstance(template, TypeVarType):
  206. return [Constraint(template, direction, actual)]
  207. # Now handle the case of either template or actual being a Union.
  208. # For a Union to be a subtype of another type, every item of the Union
  209. # must be a subtype of that type, so concatenate the constraints.
  210. if direction == SUBTYPE_OF and isinstance(template, UnionType):
  211. res = []
  212. for t_item in template.items:
  213. res.extend(infer_constraints(t_item, actual, direction))
  214. return res
  215. if direction == SUPERTYPE_OF and isinstance(actual, UnionType):
  216. res = []
  217. for a_item in actual.items:
  218. res.extend(infer_constraints(orig_template, a_item, direction))
  219. return res
  220. # Now the potential subtype is known not to be a Union or a type
  221. # variable that we are solving for. In that case, for a Union to
  222. # be a supertype of the potential subtype, some item of the Union
  223. # must be a supertype of it.
  224. if direction == SUBTYPE_OF and isinstance(actual, UnionType):
  225. # If some of items is not a complete type, disregard that.
  226. items = simplify_away_incomplete_types(actual.items)
  227. # We infer constraints eagerly -- try to find constraints for a type
  228. # variable if possible. This seems to help with some real-world
  229. # use cases.
  230. return any_constraints(
  231. [infer_constraints_if_possible(template, a_item, direction) for a_item in items],
  232. eager=True,
  233. )
  234. if direction == SUPERTYPE_OF and isinstance(template, UnionType):
  235. # When the template is a union, we are okay with leaving some
  236. # type variables indeterminate. This helps with some special
  237. # cases, though this isn't very principled.
  238. result = any_constraints(
  239. [
  240. infer_constraints_if_possible(t_item, actual, direction)
  241. for t_item in template.items
  242. ],
  243. eager=False,
  244. )
  245. if result:
  246. return result
  247. elif has_recursive_types(template) and not has_recursive_types(actual):
  248. return handle_recursive_union(template, actual, direction)
  249. return []
  250. # Remaining cases are handled by ConstraintBuilderVisitor.
  251. return template.accept(ConstraintBuilderVisitor(actual, direction))
  252. def infer_constraints_if_possible(
  253. template: Type, actual: Type, direction: int
  254. ) -> list[Constraint] | None:
  255. """Like infer_constraints, but return None if the input relation is
  256. known to be unsatisfiable, for example if template=List[T] and actual=int.
  257. (In this case infer_constraints would return [], just like it would for
  258. an automatically satisfied relation like template=List[T] and actual=object.)
  259. """
  260. if direction == SUBTYPE_OF and not mypy.subtypes.is_subtype(erase_typevars(template), actual):
  261. return None
  262. if direction == SUPERTYPE_OF and not mypy.subtypes.is_subtype(
  263. actual, erase_typevars(template)
  264. ):
  265. return None
  266. if (
  267. direction == SUPERTYPE_OF
  268. and isinstance(template, TypeVarType)
  269. and not mypy.subtypes.is_subtype(actual, erase_typevars(template.upper_bound))
  270. ):
  271. # This is not caught by the above branch because of the erase_typevars() call,
  272. # that would return 'Any' for a type variable.
  273. return None
  274. return infer_constraints(template, actual, direction)
  275. def select_trivial(options: Sequence[list[Constraint] | None]) -> list[list[Constraint]]:
  276. """Select only those lists where each item is a constraint against Any."""
  277. res = []
  278. for option in options:
  279. if option is None:
  280. continue
  281. if all(isinstance(get_proper_type(c.target), AnyType) for c in option):
  282. res.append(option)
  283. return res
  284. def merge_with_any(constraint: Constraint) -> Constraint:
  285. """Transform a constraint target into a union with given Any type."""
  286. target = constraint.target
  287. if is_union_with_any(target):
  288. # Do not produce redundant unions.
  289. return constraint
  290. # TODO: if we will support multiple sources Any, use this here instead.
  291. any_type = AnyType(TypeOfAny.implementation_artifact)
  292. return Constraint(
  293. constraint.origin_type_var,
  294. constraint.op,
  295. UnionType.make_union([target, any_type], target.line, target.column),
  296. )
  297. def handle_recursive_union(template: UnionType, actual: Type, direction: int) -> list[Constraint]:
  298. # This is a hack to special-case things like Union[T, Inst[T]] in recursive types. Although
  299. # it is quite arbitrary, it is a relatively common pattern, so we should handle it well.
  300. # This function may be called when inferring against such union resulted in different
  301. # constraints for each item. Normally we give up in such case, but here we instead split
  302. # the union in two parts, and try inferring sequentially.
  303. non_type_var_items = [t for t in template.items if not isinstance(t, TypeVarType)]
  304. type_var_items = [t for t in template.items if isinstance(t, TypeVarType)]
  305. return infer_constraints(
  306. UnionType.make_union(non_type_var_items), actual, direction
  307. ) or infer_constraints(UnionType.make_union(type_var_items), actual, direction)
  308. def any_constraints(options: list[list[Constraint] | None], eager: bool) -> list[Constraint]:
  309. """Deduce what we can from a collection of constraint lists.
  310. It's a given that at least one of the lists must be satisfied. A
  311. None element in the list of options represents an unsatisfiable
  312. constraint and is ignored. Ignore empty constraint lists if eager
  313. is true -- they are always trivially satisfiable.
  314. """
  315. if eager:
  316. valid_options = [option for option in options if option]
  317. else:
  318. valid_options = [option for option in options if option is not None]
  319. if not valid_options:
  320. return []
  321. if len(valid_options) == 1:
  322. return valid_options[0]
  323. if all(is_same_constraints(valid_options[0], c) for c in valid_options[1:]):
  324. # Multiple sets of constraints that are all the same. Just pick any one of them.
  325. return valid_options[0]
  326. if all(is_similar_constraints(valid_options[0], c) for c in valid_options[1:]):
  327. # All options have same structure. In this case we can merge-in trivial
  328. # options (i.e. those that only have Any) and try again.
  329. # TODO: More generally, if a given (variable, direction) pair appears in
  330. # every option, combine the bounds with meet/join always, not just for Any.
  331. trivial_options = select_trivial(valid_options)
  332. if trivial_options and len(trivial_options) < len(valid_options):
  333. merged_options = []
  334. for option in valid_options:
  335. if option in trivial_options:
  336. continue
  337. if option is not None:
  338. merged_option: list[Constraint] | None = [merge_with_any(c) for c in option]
  339. else:
  340. merged_option = None
  341. merged_options.append(merged_option)
  342. return any_constraints(list(merged_options), eager)
  343. # If normal logic didn't work, try excluding trivially unsatisfiable constraint (due to
  344. # upper bounds) from each option, and comparing them again.
  345. filtered_options = [filter_satisfiable(o) for o in options]
  346. if filtered_options != options:
  347. return any_constraints(filtered_options, eager=eager)
  348. # Otherwise, there are either no valid options or multiple, inconsistent valid
  349. # options. Give up and deduce nothing.
  350. return []
  351. def filter_satisfiable(option: list[Constraint] | None) -> list[Constraint] | None:
  352. """Keep only constraints that can possibly be satisfied.
  353. Currently, we filter out constraints where target is not a subtype of the upper bound.
  354. Since those can be never satisfied. We may add more cases in future if it improves type
  355. inference.
  356. """
  357. if not option:
  358. return option
  359. satisfiable = []
  360. for c in option:
  361. if isinstance(c.origin_type_var, TypeVarType) and c.origin_type_var.values:
  362. if any(
  363. mypy.subtypes.is_subtype(c.target, value) for value in c.origin_type_var.values
  364. ):
  365. satisfiable.append(c)
  366. elif mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound):
  367. satisfiable.append(c)
  368. if not satisfiable:
  369. return None
  370. return satisfiable
  371. def is_same_constraints(x: list[Constraint], y: list[Constraint]) -> bool:
  372. for c1 in x:
  373. if not any(is_same_constraint(c1, c2) for c2 in y):
  374. return False
  375. for c1 in y:
  376. if not any(is_same_constraint(c1, c2) for c2 in x):
  377. return False
  378. return True
  379. def is_same_constraint(c1: Constraint, c2: Constraint) -> bool:
  380. # Ignore direction when comparing constraints against Any.
  381. skip_op_check = isinstance(get_proper_type(c1.target), AnyType) and isinstance(
  382. get_proper_type(c2.target), AnyType
  383. )
  384. return (
  385. c1.type_var == c2.type_var
  386. and (c1.op == c2.op or skip_op_check)
  387. and mypy.subtypes.is_same_type(c1.target, c2.target)
  388. )
  389. def is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool:
  390. """Check that two lists of constraints have similar structure.
  391. This means that each list has same type variable plus direction pairs (i.e we
  392. ignore the target). Except for constraints where target is Any type, there
  393. we ignore direction as well.
  394. """
  395. return _is_similar_constraints(x, y) and _is_similar_constraints(y, x)
  396. def _is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool:
  397. """Check that every constraint in the first list has a similar one in the second.
  398. See docstring above for definition of similarity.
  399. """
  400. for c1 in x:
  401. has_similar = False
  402. for c2 in y:
  403. # Ignore direction when either constraint is against Any.
  404. skip_op_check = isinstance(get_proper_type(c1.target), AnyType) or isinstance(
  405. get_proper_type(c2.target), AnyType
  406. )
  407. if c1.type_var == c2.type_var and (c1.op == c2.op or skip_op_check):
  408. has_similar = True
  409. break
  410. if not has_similar:
  411. return False
  412. return True
  413. def simplify_away_incomplete_types(types: Iterable[Type]) -> list[Type]:
  414. complete = [typ for typ in types if is_complete_type(typ)]
  415. if complete:
  416. return complete
  417. else:
  418. return list(types)
  419. def is_complete_type(typ: Type) -> bool:
  420. """Is a type complete?
  421. A complete doesn't have uninhabited type components or (when not in strict
  422. optional mode) None components.
  423. """
  424. return typ.accept(CompleteTypeVisitor())
  425. class CompleteTypeVisitor(TypeQuery[bool]):
  426. def __init__(self) -> None:
  427. super().__init__(all)
  428. def visit_uninhabited_type(self, t: UninhabitedType) -> bool:
  429. return False
  430. class ConstraintBuilderVisitor(TypeVisitor[List[Constraint]]):
  431. """Visitor class for inferring type constraints."""
  432. # The type that is compared against a template
  433. # TODO: The value may be None. Is that actually correct?
  434. actual: ProperType
  435. def __init__(self, actual: ProperType, direction: int) -> None:
  436. # Direction must be SUBTYPE_OF or SUPERTYPE_OF.
  437. self.actual = actual
  438. self.direction = direction
  439. # Trivial leaf types
  440. def visit_unbound_type(self, template: UnboundType) -> list[Constraint]:
  441. return []
  442. def visit_any(self, template: AnyType) -> list[Constraint]:
  443. return []
  444. def visit_none_type(self, template: NoneType) -> list[Constraint]:
  445. return []
  446. def visit_uninhabited_type(self, template: UninhabitedType) -> list[Constraint]:
  447. return []
  448. def visit_erased_type(self, template: ErasedType) -> list[Constraint]:
  449. return []
  450. def visit_deleted_type(self, template: DeletedType) -> list[Constraint]:
  451. return []
  452. def visit_literal_type(self, template: LiteralType) -> list[Constraint]:
  453. return []
  454. # Errors
  455. def visit_partial_type(self, template: PartialType) -> list[Constraint]:
  456. # We can't do anything useful with a partial type here.
  457. assert False, "Internal error"
  458. # Non-trivial leaf type
  459. def visit_type_var(self, template: TypeVarType) -> list[Constraint]:
  460. assert False, (
  461. "Unexpected TypeVarType in ConstraintBuilderVisitor"
  462. " (should have been handled in infer_constraints)"
  463. )
  464. def visit_param_spec(self, template: ParamSpecType) -> list[Constraint]:
  465. # Can't infer ParamSpecs from component values (only via Callable[P, T]).
  466. return []
  467. def visit_type_var_tuple(self, template: TypeVarTupleType) -> list[Constraint]:
  468. raise NotImplementedError
  469. def visit_unpack_type(self, template: UnpackType) -> list[Constraint]:
  470. raise RuntimeError("Mypy bug: unpack should be handled at a higher level.")
  471. def visit_parameters(self, template: Parameters) -> list[Constraint]:
  472. # constraining Any against C[P] turns into infer_against_any([P], Any)
  473. # ... which seems like the only case this can happen. Better to fail loudly.
  474. if isinstance(self.actual, AnyType):
  475. return self.infer_against_any(template.arg_types, self.actual)
  476. raise RuntimeError("Parameters cannot be constrained to")
  477. # Non-leaf types
  478. def visit_instance(self, template: Instance) -> list[Constraint]:
  479. original_actual = actual = self.actual
  480. res: list[Constraint] = []
  481. if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol:
  482. if "__call__" in template.type.protocol_members:
  483. # Special case: a generic callback protocol
  484. if not any(template == t for t in template.type.inferring):
  485. template.type.inferring.append(template)
  486. call = mypy.subtypes.find_member(
  487. "__call__", template, actual, is_operator=True
  488. )
  489. assert call is not None
  490. if mypy.subtypes.is_subtype(actual, erase_typevars(call)):
  491. subres = infer_constraints(call, actual, self.direction)
  492. res.extend(subres)
  493. template.type.inferring.pop()
  494. if isinstance(actual, CallableType) and actual.fallback is not None:
  495. if actual.is_type_obj() and template.type.is_protocol:
  496. ret_type = get_proper_type(actual.ret_type)
  497. if isinstance(ret_type, TupleType):
  498. ret_type = mypy.typeops.tuple_fallback(ret_type)
  499. if isinstance(ret_type, Instance):
  500. if self.direction == SUBTYPE_OF:
  501. subtype = template
  502. else:
  503. subtype = ret_type
  504. res.extend(
  505. self.infer_constraints_from_protocol_members(
  506. ret_type, template, subtype, template, class_obj=True
  507. )
  508. )
  509. actual = actual.fallback
  510. if isinstance(actual, TypeType) and template.type.is_protocol:
  511. if isinstance(actual.item, Instance):
  512. if self.direction == SUBTYPE_OF:
  513. subtype = template
  514. else:
  515. subtype = actual.item
  516. res.extend(
  517. self.infer_constraints_from_protocol_members(
  518. actual.item, template, subtype, template, class_obj=True
  519. )
  520. )
  521. if self.direction == SUPERTYPE_OF:
  522. # Infer constraints for Type[T] via metaclass of T when it makes sense.
  523. a_item = actual.item
  524. if isinstance(a_item, TypeVarType):
  525. a_item = get_proper_type(a_item.upper_bound)
  526. if isinstance(a_item, Instance) and a_item.type.metaclass_type:
  527. res.extend(
  528. self.infer_constraints_from_protocol_members(
  529. a_item.type.metaclass_type, template, actual, template
  530. )
  531. )
  532. if isinstance(actual, Overloaded) and actual.fallback is not None:
  533. actual = actual.fallback
  534. if isinstance(actual, TypedDictType):
  535. actual = actual.as_anonymous().fallback
  536. if isinstance(actual, LiteralType):
  537. actual = actual.fallback
  538. if isinstance(actual, Instance):
  539. instance = actual
  540. erased = erase_typevars(template)
  541. assert isinstance(erased, Instance) # type: ignore[misc]
  542. # We always try nominal inference if possible,
  543. # it is much faster than the structural one.
  544. if self.direction == SUBTYPE_OF and template.type.has_base(instance.type.fullname):
  545. mapped = map_instance_to_supertype(template, instance.type)
  546. tvars = mapped.type.defn.type_vars
  547. if instance.type.has_type_var_tuple_type:
  548. assert instance.type.type_var_tuple_prefix is not None
  549. assert instance.type.type_var_tuple_suffix is not None
  550. assert mapped.type.type_var_tuple_prefix is not None
  551. assert mapped.type.type_var_tuple_suffix is not None
  552. unpack_constraints, mapped_args, instance_args = build_constraints_for_unpack(
  553. mapped.args,
  554. mapped.type.type_var_tuple_prefix,
  555. mapped.type.type_var_tuple_suffix,
  556. instance.args,
  557. instance.type.type_var_tuple_prefix,
  558. instance.type.type_var_tuple_suffix,
  559. self.direction,
  560. )
  561. res.extend(unpack_constraints)
  562. tvars_prefix, _, tvars_suffix = split_with_prefix_and_suffix(
  563. tuple(tvars),
  564. instance.type.type_var_tuple_prefix,
  565. instance.type.type_var_tuple_suffix,
  566. )
  567. tvars = cast("list[TypeVarLikeType]", list(tvars_prefix + tvars_suffix))
  568. else:
  569. mapped_args = mapped.args
  570. instance_args = instance.args
  571. # N.B: We use zip instead of indexing because the lengths might have
  572. # mismatches during daemon reprocessing.
  573. for tvar, mapped_arg, instance_arg in zip(tvars, mapped_args, instance_args):
  574. # TODO(PEP612): More ParamSpec work (or is Parameters the only thing accepted)
  575. if isinstance(tvar, TypeVarType):
  576. # The constraints for generic type parameters depend on variance.
  577. # Include constraints from both directions if invariant.
  578. if tvar.variance != CONTRAVARIANT:
  579. res.extend(infer_constraints(mapped_arg, instance_arg, self.direction))
  580. if tvar.variance != COVARIANT:
  581. res.extend(
  582. infer_constraints(mapped_arg, instance_arg, neg_op(self.direction))
  583. )
  584. elif isinstance(tvar, ParamSpecType) and isinstance(mapped_arg, ParamSpecType):
  585. suffix = get_proper_type(instance_arg)
  586. if isinstance(suffix, CallableType):
  587. prefix = mapped_arg.prefix
  588. from_concat = bool(prefix.arg_types) or suffix.from_concatenate
  589. suffix = suffix.copy_modified(from_concatenate=from_concat)
  590. if isinstance(suffix, (Parameters, CallableType)):
  591. # no such thing as variance for ParamSpecs
  592. # TODO: is there a case I am missing?
  593. # TODO: constraints between prefixes
  594. prefix = mapped_arg.prefix
  595. suffix = suffix.copy_modified(
  596. suffix.arg_types[len(prefix.arg_types) :],
  597. suffix.arg_kinds[len(prefix.arg_kinds) :],
  598. suffix.arg_names[len(prefix.arg_names) :],
  599. )
  600. res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix))
  601. elif isinstance(suffix, ParamSpecType):
  602. res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix))
  603. else:
  604. # This case should have been handled above.
  605. assert not isinstance(tvar, TypeVarTupleType)
  606. return res
  607. elif self.direction == SUPERTYPE_OF and instance.type.has_base(template.type.fullname):
  608. mapped = map_instance_to_supertype(instance, template.type)
  609. tvars = template.type.defn.type_vars
  610. if template.type.has_type_var_tuple_type:
  611. assert mapped.type.type_var_tuple_prefix is not None
  612. assert mapped.type.type_var_tuple_suffix is not None
  613. assert template.type.type_var_tuple_prefix is not None
  614. assert template.type.type_var_tuple_suffix is not None
  615. unpack_constraints, mapped_args, template_args = build_constraints_for_unpack(
  616. mapped.args,
  617. mapped.type.type_var_tuple_prefix,
  618. mapped.type.type_var_tuple_suffix,
  619. template.args,
  620. template.type.type_var_tuple_prefix,
  621. template.type.type_var_tuple_suffix,
  622. self.direction,
  623. )
  624. res.extend(unpack_constraints)
  625. tvars_prefix, _, tvars_suffix = split_with_prefix_and_suffix(
  626. tuple(tvars),
  627. template.type.type_var_tuple_prefix,
  628. template.type.type_var_tuple_suffix,
  629. )
  630. tvars = cast("list[TypeVarLikeType]", list(tvars_prefix + tvars_suffix))
  631. else:
  632. mapped_args = mapped.args
  633. template_args = template.args
  634. # N.B: We use zip instead of indexing because the lengths might have
  635. # mismatches during daemon reprocessing.
  636. for tvar, mapped_arg, template_arg in zip(tvars, mapped_args, template_args):
  637. assert not isinstance(tvar, TypeVarTupleType)
  638. if isinstance(tvar, TypeVarType):
  639. # The constraints for generic type parameters depend on variance.
  640. # Include constraints from both directions if invariant.
  641. if tvar.variance != CONTRAVARIANT:
  642. res.extend(infer_constraints(template_arg, mapped_arg, self.direction))
  643. if tvar.variance != COVARIANT:
  644. res.extend(
  645. infer_constraints(template_arg, mapped_arg, neg_op(self.direction))
  646. )
  647. elif isinstance(tvar, ParamSpecType) and isinstance(
  648. template_arg, ParamSpecType
  649. ):
  650. suffix = get_proper_type(mapped_arg)
  651. if isinstance(suffix, CallableType):
  652. prefix = template_arg.prefix
  653. from_concat = bool(prefix.arg_types) or suffix.from_concatenate
  654. suffix = suffix.copy_modified(from_concatenate=from_concat)
  655. if isinstance(suffix, (Parameters, CallableType)):
  656. # no such thing as variance for ParamSpecs
  657. # TODO: is there a case I am missing?
  658. # TODO: constraints between prefixes
  659. prefix = template_arg.prefix
  660. suffix = suffix.copy_modified(
  661. suffix.arg_types[len(prefix.arg_types) :],
  662. suffix.arg_kinds[len(prefix.arg_kinds) :],
  663. suffix.arg_names[len(prefix.arg_names) :],
  664. )
  665. res.append(Constraint(template_arg, SUPERTYPE_OF, suffix))
  666. elif isinstance(suffix, ParamSpecType):
  667. res.append(Constraint(template_arg, SUPERTYPE_OF, suffix))
  668. else:
  669. # This case should have been handled above.
  670. assert not isinstance(tvar, TypeVarTupleType)
  671. return res
  672. if (
  673. template.type.is_protocol
  674. and self.direction == SUPERTYPE_OF
  675. and
  676. # We avoid infinite recursion for structural subtypes by checking
  677. # whether this type already appeared in the inference chain.
  678. # This is a conservative way to break the inference cycles.
  679. # It never produces any "false" constraints but gives up soon
  680. # on purely structural inference cycles, see #3829.
  681. # Note that we use is_protocol_implementation instead of is_subtype
  682. # because some type may be considered a subtype of a protocol
  683. # due to _promote, but still not implement the protocol.
  684. not any(template == t for t in reversed(template.type.inferring))
  685. and mypy.subtypes.is_protocol_implementation(instance, erased, skip=["__call__"])
  686. ):
  687. template.type.inferring.append(template)
  688. res.extend(
  689. self.infer_constraints_from_protocol_members(
  690. instance, template, original_actual, template
  691. )
  692. )
  693. template.type.inferring.pop()
  694. return res
  695. elif (
  696. instance.type.is_protocol
  697. and self.direction == SUBTYPE_OF
  698. and
  699. # We avoid infinite recursion for structural subtypes also here.
  700. not any(instance == i for i in reversed(instance.type.inferring))
  701. and mypy.subtypes.is_protocol_implementation(erased, instance, skip=["__call__"])
  702. ):
  703. instance.type.inferring.append(instance)
  704. res.extend(
  705. self.infer_constraints_from_protocol_members(
  706. instance, template, template, instance
  707. )
  708. )
  709. instance.type.inferring.pop()
  710. return res
  711. if res:
  712. return res
  713. if isinstance(actual, AnyType):
  714. return self.infer_against_any(template.args, actual)
  715. if (
  716. isinstance(actual, TupleType)
  717. and is_named_instance(template, TUPLE_LIKE_INSTANCE_NAMES)
  718. and self.direction == SUPERTYPE_OF
  719. ):
  720. for item in actual.items:
  721. cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)
  722. res.extend(cb)
  723. return res
  724. elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF:
  725. return infer_constraints(template, mypy.typeops.tuple_fallback(actual), self.direction)
  726. elif isinstance(actual, TypeVarType):
  727. if not actual.values:
  728. return infer_constraints(template, actual.upper_bound, self.direction)
  729. return []
  730. elif isinstance(actual, ParamSpecType):
  731. return infer_constraints(template, actual.upper_bound, self.direction)
  732. elif isinstance(actual, TypeVarTupleType):
  733. raise NotImplementedError
  734. else:
  735. return []
  736. def infer_constraints_from_protocol_members(
  737. self,
  738. instance: Instance,
  739. template: Instance,
  740. subtype: Type,
  741. protocol: Instance,
  742. class_obj: bool = False,
  743. ) -> list[Constraint]:
  744. """Infer constraints for situations where either 'template' or 'instance' is a protocol.
  745. The 'protocol' is the one of two that is an instance of protocol type, 'subtype'
  746. is the type used to bind self during inference. Currently, we just infer constrains for
  747. every protocol member type (both ways for settable members).
  748. """
  749. res = []
  750. for member in protocol.type.protocol_members:
  751. inst = mypy.subtypes.find_member(member, instance, subtype, class_obj=class_obj)
  752. temp = mypy.subtypes.find_member(member, template, subtype)
  753. if inst is None or temp is None:
  754. if member == "__call__":
  755. continue
  756. return [] # See #11020
  757. # The above is safe since at this point we know that 'instance' is a subtype
  758. # of (erased) 'template', therefore it defines all protocol members
  759. res.extend(infer_constraints(temp, inst, self.direction))
  760. if mypy.subtypes.IS_SETTABLE in mypy.subtypes.get_member_flags(member, protocol):
  761. # Settable members are invariant, add opposite constraints
  762. res.extend(infer_constraints(temp, inst, neg_op(self.direction)))
  763. return res
  764. def visit_callable_type(self, template: CallableType) -> list[Constraint]:
  765. # Normalize callables before matching against each other.
  766. # Note that non-normalized callables can be created in annotations
  767. # using e.g. callback protocols.
  768. template = template.with_unpacked_kwargs()
  769. if isinstance(self.actual, CallableType):
  770. res: list[Constraint] = []
  771. cactual = self.actual.with_unpacked_kwargs()
  772. param_spec = template.param_spec()
  773. if param_spec is None:
  774. # FIX verify argument counts
  775. # TODO: Erase template variables if it is generic?
  776. if (
  777. type_state.infer_polymorphic
  778. and cactual.variables
  779. and cactual.param_spec() is None
  780. # Technically, the correct inferred type for application of e.g.
  781. # Callable[..., T] -> Callable[..., T] (with literal ellipsis), to a generic
  782. # like U -> U, should be Callable[..., Any], but if U is a self-type, we can
  783. # allow it to leak, to be later bound to self. A bunch of existing code
  784. # depends on this old behaviour.
  785. and not any(tv.id.raw_id == 0 for tv in cactual.variables)
  786. ):
  787. # If actual is generic, unify it with template. Note: this is
  788. # not an ideal solution (which would be adding the generic variables
  789. # to the constraint inference set), but it's a good first approximation,
  790. # and this will prevent leaking these variables in the solutions.
  791. # Note: this may infer constraints like T <: S or T <: List[S]
  792. # that contain variables in the target.
  793. unified = mypy.subtypes.unify_generic_callable(
  794. cactual, template, ignore_return=True
  795. )
  796. if unified is not None:
  797. cactual = unified
  798. res.extend(infer_constraints(cactual, template, neg_op(self.direction)))
  799. # We can't infer constraints from arguments if the template is Callable[..., T]
  800. # (with literal '...').
  801. if not template.is_ellipsis_args:
  802. if find_unpack_in_list(template.arg_types) is not None:
  803. (
  804. unpack_constraints,
  805. cactual_args_t,
  806. template_args_t,
  807. ) = find_and_build_constraints_for_unpack(
  808. tuple(cactual.arg_types), tuple(template.arg_types), self.direction
  809. )
  810. template_args = list(template_args_t)
  811. cactual_args = list(cactual_args_t)
  812. res.extend(unpack_constraints)
  813. assert len(template_args) == len(cactual_args)
  814. else:
  815. template_args = template.arg_types
  816. cactual_args = cactual.arg_types
  817. # The lengths should match, but don't crash (it will error elsewhere).
  818. for t, a in zip(template_args, cactual_args):
  819. # Negate direction due to function argument type contravariance.
  820. res.extend(infer_constraints(t, a, neg_op(self.direction)))
  821. else:
  822. # sometimes, it appears we try to get constraints between two paramspec callables?
  823. # TODO: Direction
  824. # TODO: check the prefixes match
  825. prefix = param_spec.prefix
  826. prefix_len = len(prefix.arg_types)
  827. cactual_ps = cactual.param_spec()
  828. if not cactual_ps:
  829. max_prefix_len = len([k for k in cactual.arg_kinds if k in (ARG_POS, ARG_OPT)])
  830. prefix_len = min(prefix_len, max_prefix_len)
  831. res.append(
  832. Constraint(
  833. param_spec,
  834. SUBTYPE_OF,
  835. cactual.copy_modified(
  836. arg_types=cactual.arg_types[prefix_len:],
  837. arg_kinds=cactual.arg_kinds[prefix_len:],
  838. arg_names=cactual.arg_names[prefix_len:],
  839. ret_type=UninhabitedType(),
  840. ),
  841. )
  842. )
  843. else:
  844. res.append(Constraint(param_spec, SUBTYPE_OF, cactual_ps))
  845. # compare prefixes
  846. cactual_prefix = cactual.copy_modified(
  847. arg_types=cactual.arg_types[:prefix_len],
  848. arg_kinds=cactual.arg_kinds[:prefix_len],
  849. arg_names=cactual.arg_names[:prefix_len],
  850. )
  851. # TODO: see above "FIX" comments for param_spec is None case
  852. # TODO: this assumes positional arguments
  853. for t, a in zip(prefix.arg_types, cactual_prefix.arg_types):
  854. res.extend(infer_constraints(t, a, neg_op(self.direction)))
  855. template_ret_type, cactual_ret_type = template.ret_type, cactual.ret_type
  856. if template.type_guard is not None:
  857. template_ret_type = template.type_guard
  858. if cactual.type_guard is not None:
  859. cactual_ret_type = cactual.type_guard
  860. res.extend(infer_constraints(template_ret_type, cactual_ret_type, self.direction))
  861. return res
  862. elif isinstance(self.actual, AnyType):
  863. param_spec = template.param_spec()
  864. any_type = AnyType(TypeOfAny.from_another_any, source_any=self.actual)
  865. if param_spec is None:
  866. # FIX what if generic
  867. res = self.infer_against_any(template.arg_types, self.actual)
  868. else:
  869. res = [
  870. Constraint(
  871. param_spec,
  872. SUBTYPE_OF,
  873. callable_with_ellipsis(any_type, any_type, template.fallback),
  874. )
  875. ]
  876. res.extend(infer_constraints(template.ret_type, any_type, self.direction))
  877. return res
  878. elif isinstance(self.actual, Overloaded):
  879. return self.infer_against_overloaded(self.actual, template)
  880. elif isinstance(self.actual, TypeType):
  881. return infer_constraints(template.ret_type, self.actual.item, self.direction)
  882. elif isinstance(self.actual, Instance):
  883. # Instances with __call__ method defined are considered structural
  884. # subtypes of Callable with a compatible signature.
  885. call = mypy.subtypes.find_member(
  886. "__call__", self.actual, self.actual, is_operator=True
  887. )
  888. if call:
  889. return infer_constraints(template, call, self.direction)
  890. else:
  891. return []
  892. else:
  893. return []
  894. def infer_against_overloaded(
  895. self, overloaded: Overloaded, template: CallableType
  896. ) -> list[Constraint]:
  897. # Create constraints by matching an overloaded type against a template.
  898. # This is tricky to do in general. We cheat by only matching against
  899. # the first overload item that is callable compatible. This
  900. # seems to work somewhat well, but we should really use a more
  901. # reliable technique.
  902. item = find_matching_overload_item(overloaded, template)
  903. return infer_constraints(template, item, self.direction)
  904. def visit_tuple_type(self, template: TupleType) -> list[Constraint]:
  905. actual = self.actual
  906. unpack_index = find_unpack_in_list(template.items)
  907. is_varlength_tuple = (
  908. isinstance(actual, Instance) and actual.type.fullname == "builtins.tuple"
  909. )
  910. if isinstance(actual, TupleType) or is_varlength_tuple:
  911. res: list[Constraint] = []
  912. if unpack_index is not None:
  913. if is_varlength_tuple:
  914. unpack_type = template.items[unpack_index]
  915. assert isinstance(unpack_type, UnpackType)
  916. unpacked_type = unpack_type.type
  917. assert isinstance(unpacked_type, TypeVarTupleType)
  918. return [Constraint(type_var=unpacked_type, op=self.direction, target=actual)]
  919. else:
  920. assert isinstance(actual, TupleType)
  921. (
  922. unpack_constraints,
  923. actual_items,
  924. template_items,
  925. ) = find_and_build_constraints_for_unpack(
  926. tuple(actual.items), tuple(template.items), self.direction
  927. )
  928. res.extend(unpack_constraints)
  929. elif isinstance(actual, TupleType):
  930. actual_items = tuple(actual.items)
  931. template_items = tuple(template.items)
  932. else:
  933. return res
  934. # Cases above will return if actual wasn't a TupleType.
  935. assert isinstance(actual, TupleType)
  936. if len(actual_items) == len(template_items):
  937. if (
  938. actual.partial_fallback.type.is_named_tuple
  939. and template.partial_fallback.type.is_named_tuple
  940. ):
  941. # For named tuples using just the fallbacks usually gives better results.
  942. return res + infer_constraints(
  943. template.partial_fallback, actual.partial_fallback, self.direction
  944. )
  945. for i in range(len(template_items)):
  946. res.extend(
  947. infer_constraints(template_items[i], actual_items[i], self.direction)
  948. )
  949. return res
  950. elif isinstance(actual, AnyType):
  951. return self.infer_against_any(template.items, actual)
  952. else:
  953. return []
  954. def visit_typeddict_type(self, template: TypedDictType) -> list[Constraint]:
  955. actual = self.actual
  956. if isinstance(actual, TypedDictType):
  957. res: list[Constraint] = []
  958. # NOTE: Non-matching keys are ignored. Compatibility is checked
  959. # elsewhere so this shouldn't be unsafe.
  960. for item_name, template_item_type, actual_item_type in template.zip(actual):
  961. res.extend(infer_constraints(template_item_type, actual_item_type, self.direction))
  962. return res
  963. elif isinstance(actual, AnyType):
  964. return self.infer_against_any(template.items.values(), actual)
  965. else:
  966. return []
  967. def visit_union_type(self, template: UnionType) -> list[Constraint]:
  968. assert False, (
  969. "Unexpected UnionType in ConstraintBuilderVisitor"
  970. " (should have been handled in infer_constraints)"
  971. )
  972. def visit_type_alias_type(self, template: TypeAliasType) -> list[Constraint]:
  973. assert False, f"This should be never called, got {template}"
  974. def infer_against_any(self, types: Iterable[Type], any_type: AnyType) -> list[Constraint]:
  975. res: list[Constraint] = []
  976. for t in types:
  977. if isinstance(t, UnpackType) and isinstance(t.type, TypeVarTupleType):
  978. res.append(Constraint(t.type, self.direction, any_type))
  979. else:
  980. # Note that we ignore variance and simply always use the
  981. # original direction. This is because for Any targets direction is
  982. # irrelevant in most cases, see e.g. is_same_constraint().
  983. res.extend(infer_constraints(t, any_type, self.direction))
  984. return res
  985. def visit_overloaded(self, template: Overloaded) -> list[Constraint]:
  986. if isinstance(self.actual, CallableType):
  987. items = find_matching_overload_items(template, self.actual)
  988. else:
  989. items = template.items
  990. res: list[Constraint] = []
  991. for t in items:
  992. res.extend(infer_constraints(t, self.actual, self.direction))
  993. return res
  994. def visit_type_type(self, template: TypeType) -> list[Constraint]:
  995. if isinstance(self.actual, CallableType):
  996. return infer_constraints(template.item, self.actual.ret_type, self.direction)
  997. elif isinstance(self.actual, Overloaded):
  998. return infer_constraints(template.item, self.actual.items[0].ret_type, self.direction)
  999. elif isinstance(self.actual, TypeType):
  1000. return infer_constraints(template.item, self.actual.item, self.direction)
  1001. elif isinstance(self.actual, AnyType):
  1002. return infer_constraints(template.item, self.actual, self.direction)
  1003. else:
  1004. return []
  1005. def neg_op(op: int) -> int:
  1006. """Map SubtypeOf to SupertypeOf and vice versa."""
  1007. if op == SUBTYPE_OF:
  1008. return SUPERTYPE_OF
  1009. elif op == SUPERTYPE_OF:
  1010. return SUBTYPE_OF
  1011. else:
  1012. raise ValueError(f"Invalid operator {op}")
  1013. def find_matching_overload_item(overloaded: Overloaded, template: CallableType) -> CallableType:
  1014. """Disambiguate overload item against a template."""
  1015. items = overloaded.items
  1016. for item in items:
  1017. # Return type may be indeterminate in the template, so ignore it when performing a
  1018. # subtype check.
  1019. if mypy.subtypes.is_callable_compatible(
  1020. item, template, is_compat=mypy.subtypes.is_subtype, ignore_return=True
  1021. ):
  1022. return item
  1023. # Fall back to the first item if we can't find a match. This is totally arbitrary --
  1024. # maybe we should just bail out at this point.
  1025. return items[0]
  1026. def find_matching_overload_items(
  1027. overloaded: Overloaded, template: CallableType
  1028. ) -> list[CallableType]:
  1029. """Like find_matching_overload_item, but return all matches, not just the first."""
  1030. items = overloaded.items
  1031. res = []
  1032. for item in items:
  1033. # Return type may be indeterminate in the template, so ignore it when performing a
  1034. # subtype check.
  1035. if mypy.subtypes.is_callable_compatible(
  1036. item, template, is_compat=mypy.subtypes.is_subtype, ignore_return=True
  1037. ):
  1038. res.append(item)
  1039. if not res:
  1040. # Falling back to all items if we can't find a match is pretty arbitrary, but
  1041. # it maintains backward compatibility.
  1042. res = items.copy()
  1043. return res
  1044. def find_and_build_constraints_for_unpack(
  1045. mapped: tuple[Type, ...], template: tuple[Type, ...], direction: int
  1046. ) -> tuple[list[Constraint], tuple[Type, ...], tuple[Type, ...]]:
  1047. mapped_prefix_len = find_unpack_in_list(mapped)
  1048. if mapped_prefix_len is not None:
  1049. mapped_suffix_len: int | None = len(mapped) - mapped_prefix_len - 1
  1050. else:
  1051. mapped_suffix_len = None
  1052. template_prefix_len = find_unpack_in_list(template)
  1053. assert template_prefix_len is not None
  1054. template_suffix_len = len(template) - template_prefix_len - 1
  1055. return build_constraints_for_unpack(
  1056. mapped,
  1057. mapped_prefix_len,
  1058. mapped_suffix_len,
  1059. template,
  1060. template_prefix_len,
  1061. template_suffix_len,
  1062. direction,
  1063. )
  1064. def build_constraints_for_unpack(
  1065. mapped: tuple[Type, ...],
  1066. mapped_prefix_len: int | None,
  1067. mapped_suffix_len: int | None,
  1068. template: tuple[Type, ...],
  1069. template_prefix_len: int,
  1070. template_suffix_len: int,
  1071. direction: int,
  1072. ) -> tuple[list[Constraint], tuple[Type, ...], tuple[Type, ...]]:
  1073. if mapped_prefix_len is None:
  1074. mapped_prefix_len = template_prefix_len
  1075. if mapped_suffix_len is None:
  1076. mapped_suffix_len = template_suffix_len
  1077. split_result = split_with_mapped_and_template(
  1078. mapped,
  1079. mapped_prefix_len,
  1080. mapped_suffix_len,
  1081. template,
  1082. template_prefix_len,
  1083. template_suffix_len,
  1084. )
  1085. assert split_result is not None
  1086. (
  1087. mapped_prefix,
  1088. mapped_middle,
  1089. mapped_suffix,
  1090. template_prefix,
  1091. template_middle,
  1092. template_suffix,
  1093. ) = split_result
  1094. template_unpack = extract_unpack(template_middle)
  1095. res = []
  1096. if template_unpack is not None:
  1097. if isinstance(template_unpack, TypeVarTupleType):
  1098. res.append(
  1099. Constraint(
  1100. template_unpack,
  1101. direction,
  1102. TupleType(list(mapped_middle), template_unpack.tuple_fallback),
  1103. )
  1104. )
  1105. elif (
  1106. isinstance(template_unpack, Instance)
  1107. and template_unpack.type.fullname == "builtins.tuple"
  1108. ):
  1109. for item in mapped_middle:
  1110. res.extend(infer_constraints(template_unpack.args[0], item, direction))
  1111. elif isinstance(template_unpack, TupleType):
  1112. if len(template_unpack.items) == len(mapped_middle):
  1113. for template_arg, item in zip(template_unpack.items, mapped_middle):
  1114. res.extend(infer_constraints(template_arg, item, direction))
  1115. return (res, mapped_prefix + mapped_suffix, template_prefix + template_suffix)