Debian Codegraph @

mypy/checkexpr.py

raw
1 """Expression type checker. This file is conceptually part of TypeChecker."""
2
3 from __future__ import annotations
4
5 import enum
6 import itertools
7 import time
8 from collections import defaultdict
9 from collections.abc import Callable, Iterable, Iterator, Sequence
10 from contextlib import contextmanager, nullcontext
11 from typing import ClassVar, Final, TypeAlias as _TypeAlias, cast, overload
12 from typing_extensions import assert_never
13
14 import mypy.checker
15 import mypy.errorcodes as codes
16 from mypy import applytype, erasetype, join, message_registry, nodes, operators, types
17 from mypy.argmap import ArgTypeExpander, map_actuals_to_formals, map_formals_to_actuals
18 from mypy.checker_shared import ExpressionCheckerSharedApi
19 from mypy.checkmember import analyze_member_access, has_operator
20 from mypy.checkstrformat import StringFormatterChecker
21 from mypy.constant_fold import constant_fold_expr
22 from mypy.erasetype import erase_type, remove_instance_last_known_values, replace_meta_vars
23 from mypy.errors import ErrorInfo, ErrorWatcher, report_internal_error
24 from mypy.expandtype import (
25 expand_type,
26 expand_type_by_instance,
27 freshen_all_functions_type_vars,
28 freshen_function_type_vars,
29 )
30 from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type
31 from mypy.infer import ArgumentInferContext, infer_function_type_arguments, infer_type_arguments
32 from mypy.literals import literal
33 from mypy.lookup import lookup_fully_qualified
34 from mypy.maptype import map_instance_to_supertype
35 from mypy.meet import is_overlapping_types, narrow_declared_type
36 from mypy.message_registry import ErrorMessage
37 from mypy.messages import MessageBuilder, callable_name, format_type
38 from mypy.nodes import (
39 ARG_NAMED,
40 ARG_POS,
41 ARG_STAR,
42 ARG_STAR2,
43 IMPLICITLY_ABSTRACT,
44 LAMBDA_NAME,
45 LITERAL_TYPE,
46 REVEAL_LOCALS,
47 REVEAL_TYPE,
48 UNBOUND_IMPORTED,
49 ArgKind,
50 AssertTypeExpr,
51 AssignmentExpr,
52 AwaitExpr,
53 BytesExpr,
54 CallExpr,
55 CastExpr,
56 ComparisonExpr,
57 ComplexExpr,
58 ConditionalExpr,
59 Context,
60 Decorator,
61 DictExpr,
62 DictionaryComprehension,
63 EllipsisExpr,
64 EnumCallExpr,
65 Expression,
66 FloatExpr,
67 FuncDef,
68 GeneratorExpr,
69 IndexExpr,
70 IntExpr,
71 LambdaExpr,
72 ListComprehension,
73 ListExpr,
74 MaybeTypeExpression,
75 MemberExpr,
76 MypyFile,
77 NamedTupleExpr,
78 NameExpr,
79 NewTypeExpr,
80 NotParsed,
81 OpExpr,
82 OverloadedFuncDef,
83 ParamSpecExpr,
84 PlaceholderNode,
85 PromoteExpr,
86 RefExpr,
87 RevealExpr,
88 SetComprehension,
89 SetExpr,
90 SliceExpr,
91 StarExpr,
92 StrExpr,
93 SuperExpr,
94 SymbolNode,
95 SymbolTableNode,
96 TemplateStrExpr,
97 TempNode,
98 TupleExpr,
99 TypeAlias,
100 TypeAliasExpr,
101 TypeApplication,
102 TypedDictExpr,
103 TypeFormExpr,
104 TypeInfo,
105 TypeVarExpr,
106 TypeVarLikeExpr,
107 TypeVarTupleExpr,
108 UnaryExpr,
109 Var,
110 YieldExpr,
111 YieldFromExpr,
112 get_member_expr_fullname,
113 )
114 from mypy.options import PRECISE_TUPLE_TYPES
115 from mypy.plugin import (
116 FunctionContext,
117 FunctionSigContext,
118 MethodContext,
119 MethodSigContext,
120 Plugin,
121 )
122 from mypy.semanal_enum import ENUM_BASES
123 from mypy.state import state
124 from mypy.subtypes import (
125 covers_at_runtime,
126 find_member,
127 is_same_type,
128 is_subtype,
129 non_method_protocol_members,
130 )
131 from mypy.traverser import (
132 all_name_and_member_expressions,
133 has_await_expression,
134 has_str_expression,
135 )
136 from mypy.tvar_scope import TypeVarLikeScope
137 from mypy.typeanal import (
138 TypeAnalyser,
139 check_for_explicit_any,
140 fix_instance,
141 has_any_from_unimported_type,
142 instantiate_type_alias,
143 set_any_tvars,
144 validate_instance,
145 )
146 from mypy.typeops import (
147 callable_type,
148 custom_special_method,
149 erase_to_union_or_bound,
150 false_only,
151 fixup_partial_type,
152 freeze_all_type_vars,
153 function_type,
154 get_all_type_vars,
155 get_type_vars,
156 is_literal_type_like,
157 make_simplified_union,
158 true_only,
159 try_expanding_sum_type_to_union,
160 try_getting_str_literals,
161 tuple_fallback,
162 type_object_type,
163 )
164 from mypy.types import (
165 LITERAL_TYPE_NAMES,
166 TUPLE_LIKE_INSTANCE_NAMES,
167 AnyType,
168 CallableType,
169 DeletedType,
170 ErasedType,
171 ExtraAttrs,
172 FunctionLike,
173 Instance,
174 LiteralType,
175 LiteralValue,
176 NoneType,
177 Overloaded,
178 Parameters,
179 ParamSpecFlavor,
180 ParamSpecType,
181 PartialType,
182 ProperType,
183 TupleType,
184 Type,
185 TypeAliasType,
186 TypedDictType,
187 TypeOfAny,
188 TypeType,
189 TypeVarId,
190 TypeVarLikeType,
191 TypeVarTupleType,
192 TypeVarType,
193 UnboundType,
194 UninhabitedType,
195 UnionType,
196 UnpackType,
197 find_unpack_in_list,
198 flatten_nested_tuples,
199 flatten_nested_unions,
200 get_proper_type,
201 get_proper_types,
202 has_recursive_types,
203 has_type_vars,
204 is_named_instance,
205 split_with_prefix_and_suffix,
206 )
207 from mypy.types_utils import (
208 is_generic_instance,
209 is_overlapping_none,
210 is_self_type_like,
211 remove_optional,
212 )
213 from mypy.typestate import type_state
214 from mypy.typevars import fill_typevars
215 from mypy.visitor import ExpressionVisitor
216
217 # Type of callback user for checking individual function arguments. See
218 # check_args() below for details.
219 ArgChecker: _TypeAlias = Callable[
220 [Type, Type, ArgKind, Type, int, int, CallableType, Type | None, Context, Context], None
221 ]
222
223 # Maximum nesting level for math union in overloads, setting this to large values
224 # may cause performance issues. The reason is that although union math algorithm we use
225 # nicely captures most corner cases, its worst case complexity is exponential,
226 # see https://github.com/python/mypy/pull/5255#discussion_r196896335 for discussion.
227 MAX_UNIONS: Final = 5
228
229
230 # Types considered safe for comparisons with --strict-equality due to known behaviour of __eq__.
231 # NOTE: All these types are subtypes of AbstractSet.
232 OVERLAPPING_TYPES_ALLOWLIST: Final = [
233 "builtins.set",
234 "builtins.frozenset",
235 "typing.KeysView",
236 "typing.ItemsView",
237 "_collections_abc.dict_keys",
238 "_collections_abc.dict_items",
239 ]
240 OVERLAPPING_BYTES_ALLOWLIST: Final = {
241 "builtins.bytes",
242 "builtins.bytearray",
243 "builtins.memoryview",
244 }
245
246
247 class TooManyUnions(Exception):
248 """Indicates that we need to stop splitting unions in an attempt
249 to match an overload in order to save performance.
250 """
251
252
253 def allow_fast_container_literal(t: Type) -> bool:
254 if isinstance(t, TypeAliasType) and t.is_recursive:
255 return False
256 t = get_proper_type(t)
257 return isinstance(t, Instance) or (
258 isinstance(t, TupleType) and all(allow_fast_container_literal(it) for it in t.items)
259 )
260
261
262 class Finished(Exception):
263 """Raised if we can terminate overload argument check early (no match)."""
264
265
266 @enum.unique
267 class UseReverse(enum.Enum):
268 """Used in `visit_op_expr` to enable or disable reverse method checks."""
269
270 DEFAULT = 0
271 ALWAYS = 1
272 NEVER = 2
273
274
275 USE_REVERSE_DEFAULT: Final = UseReverse.DEFAULT
276 USE_REVERSE_ALWAYS: Final = UseReverse.ALWAYS
277 USE_REVERSE_NEVER: Final = UseReverse.NEVER
278
279
280 class ExpressionChecker(ExpressionVisitor[Type], ExpressionCheckerSharedApi):
281 """Expression type checker.
282
283 This class works closely together with checker.TypeChecker.
284 """
285
286 # Some services are provided by a TypeChecker instance.
287 chk: mypy.checker.TypeChecker
288 # This is shared with TypeChecker, but stored also here for convenience.
289 msg: MessageBuilder
290 # Type context for type inference
291 type_context: list[Type | None]
292
293 strfrm_checker: StringFormatterChecker
294 plugin: Plugin
295
296 _arg_infer_context_cache: ArgumentInferContext | None
297
298 def __init__(
299 self,
300 chk: mypy.checker.TypeChecker,
301 msg: MessageBuilder,
302 plugin: Plugin,
303 per_line_checking_time_ns: dict[int, int],
304 ) -> None:
305 """Construct an expression type checker."""
306 self.chk = chk
307 self.msg = msg
308 self.plugin = plugin
309 self.per_line_checking_time_ns = per_line_checking_time_ns
310 self.collect_line_checking_stats = chk.options.line_checking_stats is not None
311 # Are we already visiting some expression? This is used to avoid double counting
312 # time for nested expressions.
313 self.in_expression = False
314 self.type_context = [None]
315
316 # Temporary overrides for expression types. This is currently
317 # used by the union math in overloads.
318 # TODO: refactor this to use a pattern similar to one in
319 # multiassign_from_union, or maybe even combine the two?
320 self.type_overrides: dict[Expression, Type] = {}
321 self.strfrm_checker = StringFormatterChecker(self.chk, self.msg)
322
323 # Callee in a call expression is in some sense both runtime context and
324 # type context, because we support things like C[int](...). Store information
325 # on whether current expression is a callee, to give better error messages
326 # related to type context.
327 self.is_callee = False
328 type_state.infer_polymorphic = not self.chk.options.old_type_inference
329
330 self._arg_infer_context_cache = None
331 self.expr_cache: dict[
332 tuple[Expression, Type | None],
333 tuple[int, Type, list[ErrorInfo], dict[Expression, Type]],
334 ] = {}
335 self.in_lambda_expr = False
336
337 self._literal_true: Instance | None = None
338 self._literal_false: Instance | None = None
339
340 def reset(self) -> None:
341 self.expr_cache.clear()
342
343 def visit_name_expr(self, e: NameExpr) -> Type:
344 """Type check a name expression.
345
346 It can be of any kind: local, member or global.
347 """
348 result = self.analyze_ref_expr(e)
349 narrowed = self.narrow_type_from_binder(e, result)
350 self.chk.check_deprecated(e.node, e)
351 return narrowed
352
353 def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:
354 result: Type | None = None
355 node = e.node
356
357 if isinstance(e, NameExpr) and e.is_special_form:
358 # A special form definition, nothing to check here.
359 return AnyType(TypeOfAny.special_form)
360
361 if isinstance(node, Var):
362 # Variable reference.
363 result = self.analyze_var_ref(node, e)
364 if isinstance(result, PartialType):
365 result = self.chk.handle_partial_var_type(result, lvalue, node, e)
366 elif isinstance(node, Decorator):
367 result = self.analyze_var_ref(node.var, e)
368 elif isinstance(node, OverloadedFuncDef):
369 if node.type is None:
370 if self.chk.in_checked_function() and node.items:
371 self.chk.handle_cannot_determine_type(node.name, e)
372 result = AnyType(TypeOfAny.from_error)
373 else:
374 result = node.type
375 elif isinstance(node, (FuncDef, TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)):
376 result = self.analyze_static_reference(node, e, e.is_alias_rvalue or lvalue)
377 else:
378 if isinstance(node, PlaceholderNode):
379 assert False, f"PlaceholderNode {node.fullname!r} leaked to checker"
380 # Unknown reference; use any type implicitly to avoid
381 # generating extra type errors.
382 result = AnyType(TypeOfAny.from_error)
383 if isinstance(node, TypeInfo):
384 if isinstance(result, CallableType) and isinstance( # type: ignore[misc]
385 result.ret_type, Instance
386 ):
387 # We need to set correct line and column
388 # TODO: always do this in type_object_type by passing the original context
389 result.ret_type.line = e.line
390 result.ret_type.column = e.column
391 if is_type_type_context(self.type_context[-1]):
392 # This is the type in a type[] expression, so substitute type
393 # variables with Any.
394 result = erasetype.erase_typevars(result)
395 assert result is not None
396 return result
397
398 def analyze_static_reference(
399 self,
400 node: SymbolNode,
401 ctx: Context,
402 is_lvalue: bool,
403 *,
404 include_modules: bool = True,
405 suppress_errors: bool = False,
406 ) -> Type:
407 """
408 This is the version of analyze_ref_expr() that doesn't do any deferrals.
409
410 This function can be used by member access to "static" attributes. For example,
411 when accessing module attributes in protocol checks, or accessing attributes of
412 special kinds (like TypeAlias, TypeInfo, etc.) on an instance or class object.
413 # TODO: merge with analyze_ref_expr() when we are confident about performance.
414 """
415 if isinstance(node, (Var, Decorator, OverloadedFuncDef)):
416 return node.type or AnyType(TypeOfAny.special_form)
417 elif isinstance(node, FuncDef):
418 return function_type(node, self.named_type("builtins.function"))
419 elif isinstance(node, TypeInfo):
420 # Reference to a type object.
421 if node.typeddict_type:
422 # We special-case TypedDict, because they don't define any constructor.
423 return self.typeddict_callable(node)
424 elif node.fullname == "types.NoneType":
425 # We special case NoneType, because its stub definition is not related to None.
426 return TypeType(NoneType())
427 else:
428 return type_object_type(node)
429 elif isinstance(node, TypeAlias):
430 # Something that refers to a type alias appears in runtime context.
431 # Note that we suppress bogus errors for alias redefinitions,
432 # they are already reported in semanal.py.
433 with self.msg.filter_errors() if suppress_errors else nullcontext():
434 return self.alias_type_in_runtime_context(
435 node, ctx=ctx, alias_definition=is_lvalue
436 )
437 elif isinstance(node, TypeVarExpr):
438 return self.named_type("typing.TypeVar")
439 elif isinstance(node, (ParamSpecExpr, TypeVarTupleExpr)):
440 return self.object_type()
441 elif isinstance(node, MypyFile):
442 # Reference to a module object.
443 return self.module_type(node) if include_modules else AnyType(TypeOfAny.special_form)
444 return AnyType(TypeOfAny.from_error)
445
446 def analyze_var_ref(self, var: Var, context: Context) -> Type:
447 if var.type:
448 var_type = get_proper_type(var.type)
449 if isinstance(var_type, Instance):
450 if var.fullname == "typing.Any":
451 # The typeshed type is 'object'; give a more useful type in runtime context
452 return self.named_type("typing._SpecialForm")
453 if self.is_literal_context() and var_type.last_known_value is not None:
454 return var_type.last_known_value
455 if var.name in {"True", "False"}:
456 return self.infer_literal_expr_type(var.name == "True", "builtins.bool")
457 return var.type
458 else:
459 if not var.is_ready and self.chk.in_checked_function():
460 self.chk.handle_cannot_determine_type(var.name, context)
461 # Implicit 'Any' type.
462 return AnyType(TypeOfAny.special_form)
463
464 def module_type(self, node: MypyFile) -> Instance:
465 try:
466 result = self.named_type("types.ModuleType")
467 except KeyError:
468 # In test cases might 'types' may not be available.
469 # Fall back to a dummy 'object' type instead to
470 # avoid a crash.
471 # Make a copy so that we don't set extra_attrs (below) on a shared instance.
472 result = self.named_type("builtins.object").copy_modified()
473 module_attrs: dict[str, Type] = {}
474 immutable = set()
475 for name, n in node.names.items():
476 if not n.module_public:
477 continue
478 if isinstance(n.node, Var) and n.node.is_final:
479 immutable.add(name)
480 if n.node is None:
481 module_attrs[name] = AnyType(TypeOfAny.from_error)
482 else:
483 # TODO: what to do about nested module references?
484 # They are non-trivial because there may be import cycles.
485 module_attrs[name] = self.analyze_static_reference(
486 n.node, n.node, False, include_modules=False, suppress_errors=True
487 )
488 result.extra_attrs = ExtraAttrs(module_attrs, immutable, node.fullname)
489 return result
490
491 def visit_call_expr(self, e: CallExpr, allow_none_return: bool = False) -> Type:
492 """Type check a call expression."""
493 if e.analyzed:
494 if isinstance(e.analyzed, NamedTupleExpr) and not e.analyzed.is_typed:
495 # Type check the arguments, but ignore the results. This relies
496 # on the typeshed stubs to type check the arguments.
497 self.visit_call_expr_inner(e)
498 # It's really a special form that only looks like a call.
499 return self.accept(e.analyzed, self.type_context[-1])
500 return self.visit_call_expr_inner(e, allow_none_return=allow_none_return)
501
502 def refers_to_typeddict(self, base: Expression) -> bool:
503 if not isinstance(base, RefExpr):
504 return False
505 if isinstance(base.node, TypeInfo) and base.node.typeddict_type is not None:
506 # Direct reference.
507 return True
508 return isinstance(base.node, TypeAlias) and isinstance(
509 get_proper_type(base.node.target), TypedDictType
510 )
511
512 def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) -> Type:
513 if (
514 self.refers_to_typeddict(e.callee)
515 or isinstance(e.callee, IndexExpr)
516 and self.refers_to_typeddict(e.callee.base)
517 ):
518 typeddict_callable = get_proper_type(self.accept(e.callee, is_callee=True))
519 if isinstance(typeddict_callable, CallableType):
520 typeddict_type = get_proper_type(typeddict_callable.ret_type)
521 assert isinstance(typeddict_type, TypedDictType)
522 return self.check_typeddict_call(
523 typeddict_type, e.arg_kinds, e.arg_names, e.args, e, typeddict_callable
524 )
525 if (
526 isinstance(e.callee, NameExpr)
527 and e.callee.name in ("isinstance", "issubclass")
528 and len(e.args) == 2
529 ):
530 for typ in mypy.checker.flatten(e.args[1]):
531 node = None
532 if isinstance(typ, NameExpr):
533 try:
534 node = self.chk.lookup_qualified(typ.name)
535 except KeyError:
536 # Undefined names should already be reported in semantic analysis.
537 pass
538 if is_expr_literal_type(typ):
539 self.msg.cannot_use_function_with_type(e.callee.name, "Literal", e)
540 continue
541 if node and isinstance(node.node, TypeAlias):
542 target = get_proper_type(node.node.target)
543 if isinstance(target, AnyType):
544 self.msg.cannot_use_function_with_type(e.callee.name, "Any", e)
545 continue
546 if isinstance(target, NoneType):
547 continue
548 if (
549 isinstance(typ, IndexExpr)
550 and isinstance(typ.analyzed, (TypeApplication, TypeAliasExpr))
551 ) or (
552 isinstance(typ, NameExpr)
553 and node
554 and isinstance(node.node, TypeAlias)
555 and not node.node.no_args
556 and not isinstance(get_proper_type(node.node.target), UnionType)
557 ):
558 self.msg.type_arguments_not_allowed(e)
559 if isinstance(typ, RefExpr) and isinstance(typ.node, TypeInfo):
560 if typ.node.typeddict_type:
561 self.msg.cannot_use_function_with_type(e.callee.name, "TypedDict", e)
562 elif typ.node.is_newtype:
563 self.msg.cannot_use_function_with_type(e.callee.name, "NewType", e)
564 self.try_infer_partial_type(e)
565 type_context = None
566 if isinstance(e.callee, LambdaExpr):
567 formal_to_actual = map_actuals_to_formals(
568 e.arg_kinds,
569 e.arg_names,
570 e.callee.arg_kinds,
571 e.callee.arg_names,
572 lambda i: self.accept(e.args[i]),
573 )
574
575 arg_types = [
576 join.join_type_list([self.accept(e.args[j]) for j in formal_to_actual[i]])
577 for i in range(len(e.callee.arg_kinds))
578 ]
579 type_context = CallableType(
580 arg_types,
581 e.callee.arg_kinds,
582 e.callee.arg_names,
583 ret_type=self.object_type(),
584 fallback=self.named_type("builtins.function"),
585 )
586 callee_type = get_proper_type(
587 self.accept(e.callee, type_context, always_allow_any=True, is_callee=True)
588 )
589
590 # Figure out the full name of the callee for plugin lookup.
591 object_type = None
592 member = None
593 fullname = None
594 if isinstance(e.callee, RefExpr):
595 # There are two special cases where plugins might act:
596 # * A "static" reference/alias to a class or function;
597 # get_function_hook() will be invoked for these.
598 fullname = e.callee.fullname or None
599 if isinstance(e.callee.node, TypeAlias):
600 target = get_proper_type(e.callee.node.target)
601 if isinstance(target, Instance):
602 fullname = target.type.fullname
603 # * Call to a method on object that has a full name (see
604 # method_fullname() for details on supported objects);
605 # get_method_hook() and get_method_signature_hook() will
606 # be invoked for these.
607 if (
608 not fullname
609 and isinstance(e.callee, MemberExpr)
610 and self.chk.has_type(e.callee.expr)
611 ):
612 member = e.callee.name
613 object_type = self.chk.lookup_type(e.callee.expr)
614
615 if (
616 self.chk.options.disallow_untyped_calls
617 and self.chk.in_checked_function()
618 and isinstance(callee_type, CallableType)
619 and callee_type.implicit
620 and callee_type.name != LAMBDA_NAME
621 ):
622 if fullname is None and member is not None:
623 assert object_type is not None
624 fullname = self.method_fullname(object_type, member)
625 if not fullname or not any(
626 fullname == p or fullname.startswith(f"{p}.")
627 for p in self.chk.options.untyped_calls_exclude
628 ):
629 self.msg.untyped_function_call(callee_type, e)
630
631 ret_type = self.check_call_expr_with_callee_type(
632 callee_type, e, fullname, object_type, member
633 )
634 if isinstance(e.callee, RefExpr) and len(e.args) == 2:
635 if e.callee.fullname in ("builtins.isinstance", "builtins.issubclass"):
636 self.check_runtime_protocol_test(e)
637 if e.callee.fullname == "builtins.issubclass":
638 self.check_protocol_issubclass(e)
639 if isinstance(e.callee, MemberExpr) and e.callee.name == "format":
640 self.check_str_format_call(e)
641 ret_type = get_proper_type(ret_type)
642 if isinstance(ret_type, UnionType):
643 ret_type = make_simplified_union(ret_type.items)
644 if isinstance(ret_type, UninhabitedType) and not ret_type.ambiguous:
645 self.chk.binder.unreachable()
646 # Warn on calls to functions that always return None. The check
647 # of ret_type is both a common-case optimization and prevents reporting
648 # the error in dynamic functions (where it will be Any).
649 if (
650 not allow_none_return
651 and isinstance(ret_type, NoneType)
652 and self.always_returns_none(e.callee)
653 ):
654 self.chk.msg.does_not_return_value(callee_type, e)
655 return ret_type
656
657 def check_str_format_call(self, e: CallExpr) -> None:
658 """More precise type checking for str.format() calls on literals and folded constants."""
659 assert isinstance(e.callee, MemberExpr)
660 format_value = None
661 folded_callee_expr = constant_fold_expr(e.callee.expr, "<unused>")
662 if isinstance(folded_callee_expr, str):
663 format_value = folded_callee_expr
664 elif self.chk.has_type(e.callee.expr):
665 typ = get_proper_type(self.chk.lookup_type(e.callee.expr))
666 if (
667 isinstance(typ, Instance)
668 and typ.type.is_enum
669 and isinstance(typ.last_known_value, LiteralType)
670 and isinstance(typ.last_known_value.value, str)
671 ):
672 value_type = typ.type.names[typ.last_known_value.value].type
673 if isinstance(value_type, Type):
674 typ = get_proper_type(value_type)
675 base_typ = try_getting_literal(typ)
676 if isinstance(base_typ, LiteralType) and isinstance(base_typ.value, str):
677 format_value = base_typ.value
678 if format_value is not None:
679 self.strfrm_checker.check_str_format_call(e, format_value)
680
681 def method_fullname(self, object_type: Type, method_name: str) -> str | None:
682 """Convert a method name to a fully qualified name, based on the type of the object that
683 it is invoked on. Return `None` if the name of `object_type` cannot be determined.
684 """
685 object_type = get_proper_type(object_type)
686
687 if isinstance(object_type, CallableType) and object_type.is_type_obj():
688 # For class method calls, object_type is a callable representing the class object.
689 # We "unwrap" it to a regular type, as the class/instance method difference doesn't
690 # affect the fully qualified name.
691 object_type = object_type.get_instance_type()
692 elif isinstance(object_type, TypeType):
693 object_type = object_type.item
694
695 type_name = None
696 if isinstance(object_type, Instance):
697 type_name = object_type.type.fullname
698 elif isinstance(object_type, (TypedDictType, LiteralType)):
699 info = object_type.fallback.type.get_containing_type_info(method_name)
700 type_name = info.fullname if info is not None else None
701 elif isinstance(object_type, TupleType):
702 type_name = tuple_fallback(object_type).type.fullname
703
704 if type_name:
705 return f"{type_name}.{method_name}"
706 else:
707 return None
708
709 def always_returns_none(self, node: Expression) -> bool:
710 """Check if `node` refers to something explicitly annotated as only returning None."""
711 if isinstance(node, RefExpr):
712 if self.defn_returns_none(node.node):
713 return True
714 if isinstance(node, MemberExpr) and node.node is None: # instance or class attribute
715 typ = get_proper_type(self.chk.lookup_type(node.expr))
716 if isinstance(typ, Instance):
717 info = typ.type
718 elif isinstance(typ, CallableType) and typ.is_type_obj():
719 instance_type = typ.get_instance_type(force_fallback=True)
720 if isinstance(instance_type, Instance):
721 info = instance_type.type
722 else:
723 return False
724 else:
725 return False
726 sym = info.get(node.name)
727 if sym and self.defn_returns_none(sym.node):
728 return True
729 return False
730
731 def defn_returns_none(self, defn: SymbolNode | None) -> bool:
732 """Check if `defn` can _only_ return None."""
733 if isinstance(defn, FuncDef):
734 return isinstance(defn.type, CallableType) and isinstance(
735 get_proper_type(defn.type.ret_type), NoneType
736 )
737 if isinstance(defn, OverloadedFuncDef):
738 return all(self.defn_returns_none(item) for item in defn.items)
739 if isinstance(defn, Var):
740 typ = get_proper_type(defn.type)
741 if (
742 not defn.is_inferred
743 and isinstance(typ, CallableType)
744 and isinstance(get_proper_type(typ.ret_type), NoneType)
745 ):
746 return True
747 if isinstance(typ, Instance):
748 sym = typ.type.get("__call__")
749 if sym and self.defn_returns_none(sym.node):
750 return True
751 return False
752
753 def check_runtime_protocol_test(self, e: CallExpr) -> None:
754 for expr in mypy.checker.flatten(e.args[1]):
755 tp = get_proper_type(self.chk.lookup_type(expr))
756 if (
757 isinstance(tp, FunctionLike)
758 and tp.is_type_obj()
759 and tp.type_object().is_protocol
760 and not tp.type_object().runtime_protocol
761 ):
762 self.chk.fail(message_registry.RUNTIME_PROTOCOL_EXPECTED, e)
763
764 def check_protocol_issubclass(self, e: CallExpr) -> None:
765 for expr in mypy.checker.flatten(e.args[1]):
766 tp = get_proper_type(self.chk.lookup_type(expr))
767 if isinstance(tp, FunctionLike) and tp.is_type_obj() and tp.type_object().is_protocol:
768 attr_members = non_method_protocol_members(tp.type_object())
769 if attr_members:
770 self.chk.msg.report_non_method_protocol(tp.type_object(), attr_members, e)
771
772 def check_typeddict_call(
773 self,
774 callee: TypedDictType,
775 arg_kinds: list[ArgKind],
776 arg_names: Sequence[str | None],
777 args: list[Expression],
778 context: Context,
779 orig_callee: Type | None,
780 ) -> Type:
781 if args and all(ak in (ARG_NAMED, ARG_STAR2) for ak in arg_kinds):
782 # ex: Point(x=42, y=1337, **extras)
783 # This is a bit ugly, but this is a price for supporting all possible syntax
784 # variants for TypedDict constructors.
785 kwargs = zip([StrExpr(n) if n is not None else None for n in arg_names], args)
786 result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee)
787 if result is not None:
788 validated_kwargs, always_present_keys = result
789 return self.check_typeddict_call_with_kwargs(
790 callee, validated_kwargs, context, orig_callee, always_present_keys
791 )
792 return AnyType(TypeOfAny.from_error)
793
794 if len(args) == 1 and arg_kinds[0] == ARG_POS:
795 unique_arg = args[0]
796 if isinstance(unique_arg, DictExpr):
797 # ex: Point({'x': 42, 'y': 1337, **extras})
798 return self.check_typeddict_call_with_dict(
799 callee, unique_arg.items, context, orig_callee
800 )
801 if isinstance(unique_arg, CallExpr) and isinstance(unique_arg.analyzed, DictExpr):
802 # ex: Point(dict(x=42, y=1337, **extras))
803 return self.check_typeddict_call_with_dict(
804 callee, unique_arg.analyzed.items, context, orig_callee
805 )
806
807 if not args:
808 # ex: EmptyDict()
809 return self.check_typeddict_call_with_kwargs(callee, {}, context, orig_callee, set())
810
811 self.chk.fail(message_registry.INVALID_TYPEDDICT_ARGS, context)
812 return AnyType(TypeOfAny.from_error)
813
814 def validate_typeddict_kwargs(
815 self, kwargs: Iterable[tuple[Expression | None, Expression]], callee: TypedDictType
816 ) -> tuple[dict[str, list[Expression]], set[str]] | None:
817 # All (actual or mapped from ** unpacks) expressions that can match given key.
818 result = defaultdict(list)
819 # Keys that are guaranteed to be present no matter what (e.g. for all items of a union)
820 always_present_keys = set()
821 # Indicates latest encountered ** unpack of a non-closed type among items.
822 last_open_star_found = None
823
824 for item_name_expr, item_arg in kwargs:
825 if item_name_expr:
826 key_type = self.accept(item_name_expr)
827 values = try_getting_str_literals(item_name_expr, key_type)
828 literal_value = None
829 if values and len(values) == 1:
830 literal_value = values[0]
831 if literal_value is None:
832 key_context = item_name_expr or item_arg
833 self.chk.fail(
834 message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,
835 key_context,
836 code=codes.LITERAL_REQ,
837 )
838 return None
839 else:
840 # A directly present key unconditionally shadows all previously found
841 # values from ** items.
842 # TODO: for duplicate keys, type-check all values.
843 result[literal_value] = [item_arg]
844 always_present_keys.add(literal_value)
845 else:
846 is_valid, is_open = self.validate_star_typeddict_item(
847 item_arg, callee, result, always_present_keys
848 )
849 if not is_valid:
850 return None
851 if is_open:
852 last_open_star_found = item_arg
853 if self.chk.options.extra_checks and last_open_star_found is not None:
854 if callee.is_closed:
855 self.chk.fail(
856 "Cannot unpack item that may contain extra keys into a closed TypedDict",
857 last_open_star_found,
858 code=codes.TYPEDDICT_ITEM,
859 )
860 absent_keys = []
861 for key in callee.items:
862 if key not in callee.required_keys and key not in result:
863 absent_keys.append(key)
864 if absent_keys:
865 # Having an optional key not explicitly declared by a ** unpacked open
866 # TypedDict is unsafe, it may be an (incompatible) subtype at runtime.
867 # TODO: catch the cases where a declared key is overridden by a subsequent
868 # ** item without it (and not again overridden with complete ** item).
869 self.msg.non_required_keys_absent_with_star(absent_keys, last_open_star_found)
870 return result, always_present_keys
871
872 def validate_star_typeddict_item(
873 self,
874 item_arg: Expression,
875 callee: TypedDictType,
876 result: dict[str, list[Expression]],
877 always_present_keys: set[str],
878 ) -> tuple[bool, bool]:
879 """Update keys/expressions from a ** expression in TypedDict constructor.
880
881 Note `result` and `always_present_keys` are updated in place.
882
883 First tuple item returned is true if the expression `item_arg` may valid
884 in `callee` TypedDict context. Second tuple item returned is true if the
885 expression may contain other keys not explicitly declared.
886 """
887 inferred = get_proper_type(self.accept(item_arg, type_context=callee))
888 any_fallback = False
889 possible_tds: list[TypedDictType] = []
890 if isinstance(inferred, TypedDictType):
891 possible_tds = [inferred]
892 elif isinstance(inferred, UnionType):
893 for item in get_proper_types(inferred.relevant_items()):
894 if isinstance(item, TypedDictType):
895 possible_tds.append(item)
896 elif not self.valid_unpack_fallback_item(item):
897 self.msg.unsupported_target_for_star_typeddict(item, item_arg)
898 return False, True
899 else:
900 any_fallback = True
901 elif not self.valid_unpack_fallback_item(inferred):
902 self.msg.unsupported_target_for_star_typeddict(inferred, item_arg)
903 return False, True
904 else:
905 any_fallback = True
906 all_keys: set[str] = set()
907 for td in possible_tds:
908 all_keys |= td.items.keys()
909 for key in all_keys:
910 arg = TempNode(
911 UnionType.make_union([td.items[key] for td in possible_tds if key in td.items])
912 )
913 arg.set_line(item_arg)
914 if all(key in td.required_keys for td in possible_tds):
915 always_present_keys.add(key)
916 # Always present keys override previously found values. This is done
917 # to support use cases like `Config({**defaults, **overrides})`, where
918 # some `overrides` types are narrower that types in `defaults`, and
919 # former are too wide for `Config`.
920 if result[key]:
921 first = result[key][0]
922 if not isinstance(first, TempNode):
923 # We must always preserve any non-synthetic values, so that
924 # we will accept them even if they are shadowed.
925 result[key] = [first, arg]
926 else:
927 result[key] = [arg]
928 else:
929 result[key] = [arg]
930 else:
931 # If this key is not required at least in some item of a union
932 # it may not shadow previous item, so we need to type check both.
933 result[key].append(arg)
934 all_closed = all(t.is_closed for t in possible_tds)
935 return True, any_fallback or not all_closed
936
937 def valid_unpack_fallback_item(self, typ: ProperType) -> bool:
938 if isinstance(typ, AnyType):
939 return True
940 if not isinstance(typ, Instance) or not typ.type.has_base("typing.Mapping"):
941 return False
942 mapped = map_instance_to_supertype(typ, self.chk.lookup_typeinfo("typing.Mapping"))
943 return all(isinstance(a, AnyType) for a in get_proper_types(mapped.args))
944
945 def match_typeddict_call_with_dict(
946 self,
947 callee: TypedDictType,
948 kwargs: list[tuple[Expression | None, Expression]],
949 context: Context,
950 ) -> bool:
951 with self.msg.filter_errors():
952 result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee)
953 if result is not None:
954 validated_kwargs, _ = result
955 return callee.required_keys <= set(validated_kwargs.keys()) <= set(callee.items.keys())
956 else:
957 return False
958
959 def check_typeddict_call_with_dict(
960 self,
961 callee: TypedDictType,
962 kwargs: list[tuple[Expression | None, Expression]],
963 context: Context,
964 orig_callee: Type | None,
965 ) -> Type:
966 result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee)
967 if result is not None:
968 validated_kwargs, always_present_keys = result
969 return self.check_typeddict_call_with_kwargs(
970 callee,
971 kwargs=validated_kwargs,
972 context=context,
973 orig_callee=orig_callee,
974 always_present_keys=always_present_keys,
975 )
976 else:
977 return AnyType(TypeOfAny.from_error)
978
979 def typeddict_callable(self, info: TypeInfo) -> CallableType:
980 """Construct a reasonable type for a TypedDict type in runtime context.
981
982 If it appears as a callee, it will be special-cased anyway, e.g. it is
983 also allowed to accept a single positional argument if it is a dict literal.
984
985 Note it is not safe to move this to type_object_type() since it will crash
986 on plugin-generated TypedDicts, that may not have the special_alias.
987 """
988 assert info.special_alias is not None
989 target = info.special_alias.target
990 assert isinstance(target, ProperType) and isinstance(target, TypedDictType)
991 return self.typeddict_callable_from_context(target, info.defn.type_vars)
992
993 def typeddict_callable_from_context(
994 self, callee: TypedDictType, variables: Sequence[TypeVarLikeType] | None = None
995 ) -> CallableType:
996 return CallableType(
997 list(callee.items.values()),
998 [
999 ArgKind.ARG_NAMED if name in callee.required_keys else ArgKind.ARG_NAMED_OPT
1000 for name in callee.items
1001 ],
1002 list(callee.items.keys()),
1003 callee,
1004 self.named_type("builtins.type"),
1005 variables=variables,
1006 is_bound=True,
1007 )
1008
1009 def check_typeddict_call_with_kwargs(
1010 self,
1011 callee: TypedDictType,
1012 kwargs: dict[str, list[Expression]],
1013 context: Context,
1014 orig_callee: Type | None,
1015 always_present_keys: set[str],
1016 ) -> Type:
1017 actual_keys = kwargs.keys()
1018 if callee.to_be_mutated:
1019 assigned_readonly_keys = actual_keys & callee.readonly_keys
1020 if assigned_readonly_keys:
1021 self.msg.readonly_keys_mutated(assigned_readonly_keys, context=context)
1022 if not (
1023 callee.required_keys <= always_present_keys and actual_keys <= callee.items.keys()
1024 ):
1025 if not (actual_keys <= callee.items.keys()):
1026 self.msg.unexpected_typeddict_keys(
1027 callee,
1028 expected_keys=[
1029 key
1030 for key in callee.items.keys()
1031 if key in callee.required_keys or key in actual_keys
1032 ],
1033 actual_keys=list(actual_keys),
1034 context=context,
1035 )
1036 if not (callee.required_keys <= always_present_keys):
1037 self.msg.unexpected_typeddict_keys(
1038 callee,
1039 expected_keys=[
1040 key for key in callee.items.keys() if key in callee.required_keys
1041 ],
1042 actual_keys=[
1043 key for key in always_present_keys if key in callee.required_keys
1044 ],
1045 context=context,
1046 )
1047 if callee.required_keys > actual_keys:
1048 # found_set is a sub-set of the required_keys
1049 # This means we're missing some keys and as such, we can't
1050 # properly type the object
1051 return AnyType(TypeOfAny.from_error)
1052
1053 orig_callee = get_proper_type(orig_callee)
1054 if isinstance(orig_callee, CallableType):
1055 infer_callee = orig_callee
1056 else:
1057 # Try reconstructing from type context.
1058 if callee.fallback.type.special_alias is not None:
1059 infer_callee = self.typeddict_callable(callee.fallback.type)
1060 else:
1061 # Likely a TypedDict type generated by a plugin.
1062 infer_callee = self.typeddict_callable_from_context(callee)
1063
1064 # We don't show any errors, just infer types in a generic TypedDict type,
1065 # a custom error message will be given below, if there are errors.
1066 with self.msg.filter_errors(), self.chk.local_type_map:
1067 orig_ret_type, _ = self.check_callable_call(
1068 infer_callee,
1069 # We use first expression for each key to infer type variables of a generic
1070 # TypedDict. This is a bit arbitrary, but in most cases will work better than
1071 # trying to infer a union or a join.
1072 [args[0] for args in kwargs.values()],
1073 [ArgKind.ARG_NAMED] * len(kwargs),
1074 context,
1075 list(kwargs.keys()),
1076 None,
1077 None,
1078 None,
1079 )
1080
1081 ret_type = get_proper_type(orig_ret_type)
1082 if not isinstance(ret_type, TypedDictType):
1083 # If something went really wrong, type-check call with original type,
1084 # this may give a better error message.
1085 ret_type = callee
1086
1087 for item_name, item_expected_type in ret_type.items.items():
1088 if item_name in kwargs:
1089 item_values = kwargs[item_name]
1090 for item_value in item_values:
1091 self.chk.check_simple_assignment(
1092 lvalue_type=item_expected_type,
1093 rvalue=item_value,
1094 context=item_value,
1095 msg=ErrorMessage(
1096 message_registry.INCOMPATIBLE_TYPES.value, code=codes.TYPEDDICT_ITEM
1097 ),
1098 lvalue_name=f'TypedDict item "{item_name}"',
1099 rvalue_name="expression",
1100 )
1101
1102 return orig_ret_type
1103
1104 def get_partial_self_var(self, expr: MemberExpr) -> Var | None:
1105 """Get variable node for a partial self attribute.
1106
1107 If the expression is not a self attribute, or attribute is not variable,
1108 or variable is not partial, return None.
1109 """
1110 if not (
1111 isinstance(expr.expr, NameExpr)
1112 and isinstance(expr.expr.node, Var)
1113 and expr.expr.node.is_self
1114 ):
1115 # Not a self.attr expression.
1116 return None
1117 info = self.chk.scope.enclosing_class()
1118 if not info or expr.name not in info.names:
1119 # Don't mess with partial types in superclasses.
1120 return None
1121 sym = info.names[expr.name]
1122 if isinstance(sym.node, Var) and isinstance(sym.node.type, PartialType):
1123 return sym.node
1124 return None
1125
1126 # Types and methods that can be used to infer partial types.
1127 item_args: ClassVar[dict[str, list[str]]] = {
1128 "builtins.list": ["append"],
1129 "builtins.set": ["add", "discard"],
1130 }
1131 container_args: ClassVar[dict[str, dict[str, list[str]]]] = {
1132 "builtins.list": {"extend": ["builtins.list"]},
1133 "builtins.dict": {"update": ["builtins.dict"]},
1134 "collections.OrderedDict": {"update": ["builtins.dict"]},
1135 "builtins.set": {"update": ["builtins.set", "builtins.list"]},
1136 }
1137
1138 def try_infer_partial_type(self, e: CallExpr) -> None:
1139 """Try to make partial type precise from a call."""
1140 if not isinstance(e.callee, MemberExpr):
1141 return
1142 callee = e.callee
1143 if isinstance(callee.expr, RefExpr):
1144 # Call a method with a RefExpr callee, such as 'x.method(...)'.
1145 ret = self.get_partial_var(callee.expr)
1146 if ret is None:
1147 return
1148 var, partial_types = ret
1149 typ = self.try_infer_partial_value_type_from_call(e, callee.name, var)
1150 # Var may be deleted from partial_types in try_infer_partial_value_type_from_call
1151 if typ is not None and var in partial_types:
1152 self.chk.replace_partial_type(var, typ, partial_types)
1153 elif isinstance(callee.expr, IndexExpr) and isinstance(callee.expr.base, RefExpr):
1154 # Call 'x[y].method(...)'; may infer type of 'x' if it's a partial defaultdict.
1155 if callee.expr.analyzed is not None:
1156 return # A special form
1157 base = callee.expr.base
1158 index = callee.expr.index
1159 ret = self.get_partial_var(base)
1160 if ret is None:
1161 return
1162 var, partial_types = ret
1163 partial_type = get_partial_instance_type(var.type)
1164 if partial_type is None or partial_type.value_type is None:
1165 return
1166 value_type = self.try_infer_partial_value_type_from_call(e, callee.name, var)
1167 if value_type is not None:
1168 # Infer key type.
1169 key_type = self.accept(index)
1170 if mypy.checker.is_valid_inferred_type(key_type, self.chk.options):
1171 # Store inferred partial type.
1172 assert partial_type.type is not None
1173 typename = partial_type.type.fullname
1174 new_type = self.chk.named_generic_type(typename, [key_type, value_type])
1175 self.chk.replace_partial_type(var, new_type, partial_types)
1176
1177 def get_partial_var(self, ref: RefExpr) -> tuple[Var, dict[Var, Context]] | None:
1178 var = ref.node
1179 if var is None and isinstance(ref, MemberExpr):
1180 var = self.get_partial_self_var(ref)
1181 if not isinstance(var, Var):
1182 return None
1183 partial_types = self.chk.find_partial_types(var)
1184 if partial_types is None:
1185 return None
1186 return var, partial_types
1187
1188 def try_infer_partial_value_type_from_call(
1189 self, e: CallExpr, methodname: str, var: Var
1190 ) -> Instance | None:
1191 """Try to make partial type precise from a call such as 'x.append(y)'."""
1192 if self.chk.current_node_deferred:
1193 return None
1194 partial_type = get_partial_instance_type(var.type)
1195 if partial_type is None:
1196 return None
1197 if partial_type.value_type:
1198 typename = partial_type.value_type.type.fullname
1199 else:
1200 assert partial_type.type is not None
1201 typename = partial_type.type.fullname
1202 # Sometimes we can infer a full type for a partial List, Dict or Set type.
1203 # TODO: Don't infer argument expression twice.
1204 if (
1205 typename in self.item_args
1206 and methodname in self.item_args[typename]
1207 and e.arg_kinds == [ARG_POS]
1208 ):
1209 item_type = self.accept(e.args[0])
1210 if mypy.checker.is_valid_inferred_type(item_type, self.chk.options):
1211 return self.chk.named_generic_type(typename, [item_type])
1212 elif (
1213 typename in self.container_args
1214 and methodname in self.container_args[typename]
1215 and e.arg_kinds == [ARG_POS]
1216 ):
1217 arg_type = get_proper_type(self.accept(e.args[0]))
1218 if isinstance(arg_type, Instance):
1219 arg_typename = arg_type.type.fullname
1220 if arg_typename in self.container_args[typename][methodname]:
1221 if all(
1222 mypy.checker.is_valid_inferred_type(item_type, self.chk.options)
1223 for item_type in arg_type.args
1224 ):
1225 return self.chk.named_generic_type(typename, list(arg_type.args))
1226 elif isinstance(arg_type, AnyType):
1227 return self.chk.named_type(typename)
1228
1229 return None
1230
1231 def apply_function_plugin(
1232 self,
1233 callee: CallableType,
1234 arg_kinds: list[ArgKind],
1235 arg_types: list[Type],
1236 arg_names: Sequence[str | None] | None,
1237 formal_to_actual: list[list[int]],
1238 args: list[Expression],
1239 fullname: str,
1240 object_type: Type | None,
1241 context: Context,
1242 ) -> Type:
1243 """Use special case logic to infer the return type of a specific named function/method.
1244
1245 Caller must ensure that a plugin hook exists. There are two different cases:
1246
1247 - If object_type is None, the caller must ensure that a function hook exists
1248 for fullname.
1249 - If object_type is not None, the caller must ensure that a method hook exists
1250 for fullname.
1251
1252 Return the inferred return type.
1253 """
1254 num_formals = len(callee.arg_types)
1255 formal_arg_types: list[list[Type]] = [[] for _ in range(num_formals)]
1256 formal_arg_exprs: list[list[Expression]] = [[] for _ in range(num_formals)]
1257 formal_arg_names: list[list[str | None]] = [[] for _ in range(num_formals)]
1258 formal_arg_kinds: list[list[ArgKind]] = [[] for _ in range(num_formals)]
1259 for formal, actuals in enumerate(formal_to_actual):
1260 for actual in actuals:
1261 formal_arg_types[formal].append(arg_types[actual])
1262 formal_arg_exprs[formal].append(args[actual])
1263 if arg_names:
1264 formal_arg_names[formal].append(arg_names[actual])
1265 else:
1266 formal_arg_names[formal].append(None)
1267 formal_arg_kinds[formal].append(arg_kinds[actual])
1268
1269 if object_type is None:
1270 # Apply function plugin
1271 callback = self.plugin.get_function_hook(fullname)
1272 assert callback is not None # Assume that caller ensures this
1273 return callback(
1274 FunctionContext(
1275 arg_types=formal_arg_types,
1276 arg_kinds=formal_arg_kinds,
1277 callee_arg_names=callee.arg_names,
1278 arg_names=formal_arg_names,
1279 default_return_type=callee.ret_type,
1280 args=formal_arg_exprs,
1281 context=context,
1282 api=self.chk,
1283 )
1284 )
1285 else:
1286 # Apply method plugin
1287 method_callback = self.plugin.get_method_hook(fullname)
1288 assert method_callback is not None # Assume that caller ensures this
1289 object_type = get_proper_type(object_type)
1290 return method_callback(
1291 MethodContext(
1292 type=object_type,
1293 arg_types=formal_arg_types,
1294 arg_kinds=formal_arg_kinds,
1295 callee_arg_names=callee.arg_names,
1296 arg_names=formal_arg_names,
1297 default_return_type=callee.ret_type,
1298 args=formal_arg_exprs,
1299 context=context,
1300 api=self.chk,
1301 )
1302 )
1303
1304 def apply_signature_hook(
1305 self,
1306 callee: FunctionLike,
1307 args: list[Expression],
1308 arg_kinds: list[ArgKind],
1309 arg_names: Sequence[str | None] | None,
1310 hook: Callable[[list[list[Expression]], CallableType], FunctionLike],
1311 ) -> FunctionLike:
1312 """Helper to apply a signature hook for either a function or method"""
1313 if isinstance(callee, CallableType):
1314 num_formals = len(callee.arg_kinds)
1315 formal_to_actual = map_actuals_to_formals(
1316 arg_kinds,
1317 arg_names,
1318 callee.arg_kinds,
1319 callee.arg_names,
1320 lambda i: self.accept(args[i]),
1321 )
1322 formal_arg_exprs: list[list[Expression]] = [[] for _ in range(num_formals)]
1323 for formal, actuals in enumerate(formal_to_actual):
1324 for actual in actuals:
1325 formal_arg_exprs[formal].append(args[actual])
1326 return hook(formal_arg_exprs, callee)
1327 else:
1328 assert isinstance(callee, Overloaded)
1329 items = []
1330 for item in callee.items:
1331 adjusted = self.apply_signature_hook(item, args, arg_kinds, arg_names, hook)
1332 assert isinstance(adjusted, CallableType)
1333 items.append(adjusted)
1334 return Overloaded(items)
1335
1336 def apply_function_signature_hook(
1337 self,
1338 callee: FunctionLike,
1339 args: list[Expression],
1340 arg_kinds: list[ArgKind],
1341 context: Context,
1342 arg_names: Sequence[str | None] | None,
1343 signature_hook: Callable[[FunctionSigContext], FunctionLike],
1344 ) -> FunctionLike:
1345 """Apply a plugin hook that may infer a more precise signature for a function."""
1346 return self.apply_signature_hook(
1347 callee,
1348 args,
1349 arg_kinds,
1350 arg_names,
1351 (lambda args, sig: signature_hook(FunctionSigContext(args, sig, context, self.chk))),
1352 )
1353
1354 def apply_method_signature_hook(
1355 self,
1356 callee: FunctionLike,
1357 args: list[Expression],
1358 arg_kinds: list[ArgKind],
1359 context: Context,
1360 arg_names: Sequence[str | None] | None,
1361 object_type: Type,
1362 signature_hook: Callable[[MethodSigContext], FunctionLike],
1363 ) -> FunctionLike:
1364 """Apply a plugin hook that may infer a more precise signature for a method."""
1365 pobject_type = get_proper_type(object_type)
1366 return self.apply_signature_hook(
1367 callee,
1368 args,
1369 arg_kinds,
1370 arg_names,
1371 (
1372 lambda args, sig: signature_hook(
1373 MethodSigContext(pobject_type, args, sig, context, self.chk)
1374 )
1375 ),
1376 )
1377
1378 def transform_callee_type(
1379 self,
1380 callable_name: str | None,
1381 callee: Type,
1382 args: list[Expression],
1383 arg_kinds: list[ArgKind],
1384 context: Context,
1385 arg_names: Sequence[str | None] | None = None,
1386 object_type: Type | None = None,
1387 ) -> Type:
1388 """Attempt to determine a more accurate signature for a method call.
1389
1390 This is done by looking up and applying a method signature hook (if one exists for the
1391 given method name).
1392
1393 If no matching method signature hook is found, callee is returned unmodified. The same
1394 happens if the arguments refer to a non-method callable (this is allowed so that the code
1395 calling transform_callee_type needs to perform fewer boilerplate checks).
1396
1397 Note: this method is *not* called automatically as part of check_call, because in some
1398 cases check_call is called multiple times while checking a single call (for example when
1399 dealing with overloads). Instead, this method needs to be called explicitly
1400 (if appropriate) before the signature is passed to check_call.
1401 """
1402 callee = get_proper_type(callee)
1403 if callable_name is not None and isinstance(callee, FunctionLike):
1404 if object_type is not None:
1405 method_sig_hook = self.plugin.get_method_signature_hook(callable_name)
1406 if method_sig_hook:
1407 return self.apply_method_signature_hook(
1408 callee, args, arg_kinds, context, arg_names, object_type, method_sig_hook
1409 )
1410 else:
1411 function_sig_hook = self.plugin.get_function_signature_hook(callable_name)
1412 if function_sig_hook:
1413 return self.apply_function_signature_hook(
1414 callee, args, arg_kinds, context, arg_names, function_sig_hook
1415 )
1416
1417 return callee
1418
1419 def is_generic_decorator_overload_call(
1420 self, callee_type: CallableType, args: list[Expression]
1421 ) -> Overloaded | None:
1422 """Check if this looks like an application of a generic function to overload argument."""
1423 assert callee_type.variables
1424 if len(callee_type.arg_types) != 1 or len(args) != 1:
1425 # TODO: can we handle more general cases?
1426 return None
1427 if not isinstance(get_proper_type(callee_type.arg_types[0]), CallableType):
1428 return None
1429 if not isinstance(get_proper_type(callee_type.ret_type), CallableType):
1430 return None
1431 with self.chk.local_type_map:
1432 with self.msg.filter_errors():
1433 arg_type = get_proper_type(self.accept(args[0], type_context=None))
1434 if isinstance(arg_type, Overloaded):
1435 return arg_type
1436 return None
1437
1438 def handle_decorator_overload_call(
1439 self, callee_type: CallableType, overloaded: Overloaded, ctx: Context
1440 ) -> tuple[Type, Type] | None:
1441 """Type-check application of a generic callable to an overload.
1442
1443 We check call on each individual overload item, and then combine results into a new
1444 overload. This function should be only used if callee_type takes and returns a Callable.
1445 """
1446 result = []
1447 inferred_args = []
1448 for item in overloaded.items:
1449 arg = TempNode(typ=item)
1450 with self.msg.filter_errors() as err:
1451 item_result, inferred_arg = self.check_call(callee_type, [arg], [ARG_POS], ctx)
1452 if err.has_new_errors():
1453 # This overload doesn't match.
1454 continue
1455 p_item_result = get_proper_type(item_result)
1456 if not isinstance(p_item_result, CallableType):
1457 continue
1458 p_inferred_arg = get_proper_type(inferred_arg)
1459 if not isinstance(p_inferred_arg, CallableType):
1460 continue
1461 inferred_args.append(p_inferred_arg)
1462 result.append(p_item_result)
1463 if not result or not inferred_args:
1464 # None of the overload matched (or overload was initially malformed).
1465 return None
1466 return Overloaded(result), Overloaded(inferred_args)
1467
1468 def check_call_expr_with_callee_type(
1469 self,
1470 callee_type: Type,
1471 e: CallExpr,
1472 callable_name: str | None,
1473 object_type: Type | None,
1474 member: str | None = None,
1475 ) -> Type:
1476 """Type check call expression.
1477
1478 The callee_type should be used as the type of callee expression. In particular,
1479 in case of a union type this can be a particular item of the union, so that we can
1480 apply plugin hooks to each item.
1481
1482 The 'member', 'callable_name' and 'object_type' are only used to call plugin hooks.
1483 If 'callable_name' is None but 'member' is not None (member call), try constructing
1484 'callable_name' using 'object_type' (the base type on which the method is called),
1485 for example 'typing.Mapping.get'.
1486 """
1487 if callable_name is None and member is not None:
1488 assert object_type is not None
1489 callable_name = self.method_fullname(object_type, member)
1490 object_type = get_proper_type(object_type)
1491 if callable_name:
1492 # Try to refine the call signature using plugin hooks before checking the call.
1493 callee_type = self.transform_callee_type(
1494 callable_name, callee_type, e.args, e.arg_kinds, e, e.arg_names, object_type
1495 )
1496 # Unions are special-cased to allow plugins to act on each item in the union.
1497 elif member is not None and isinstance(object_type, UnionType):
1498 return self.check_union_call_expr(e, object_type, member)
1499 ret_type, callee_type = self.check_call(
1500 callee_type,
1501 e.args,
1502 e.arg_kinds,
1503 e,
1504 e.arg_names,
1505 callable_node=e.callee,
1506 callable_name=callable_name,
1507 object_type=object_type,
1508 )
1509 proper_callee = get_proper_type(callee_type)
1510 if isinstance(e.callee, RefExpr) and isinstance(proper_callee, CallableType):
1511 # Cache it for find_isinstance_check()
1512 if proper_callee.type_guard is not None:
1513 e.callee.type_guard = proper_callee.type_guard
1514 if proper_callee.type_is is not None:
1515 e.callee.type_is = proper_callee.type_is
1516 return ret_type
1517
1518 def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str) -> Type:
1519 """Type check calling a member expression where the base type is a union."""
1520 res: list[Type] = []
1521 for typ in flatten_nested_unions(object_type.relevant_items()):
1522 # Member access errors are already reported when visiting the member expression.
1523 with self.msg.filter_errors():
1524 item = analyze_member_access(
1525 member,
1526 typ,
1527 e,
1528 is_lvalue=False,
1529 is_super=False,
1530 is_operator=False,
1531 original_type=object_type,
1532 chk=self.chk,
1533 in_literal_context=self.is_literal_context(),
1534 self_type=typ,
1535 )
1536 narrowed = self.narrow_type_from_binder(e.callee, item, skip_non_overlapping=True)
1537 if narrowed is None:
1538 continue
1539 callable_name = self.method_fullname(typ, member)
1540 item_object_type = typ if callable_name else None
1541 res.append(
1542 self.check_call_expr_with_callee_type(narrowed, e, callable_name, item_object_type)
1543 )
1544 return make_simplified_union(res)
1545
1546 def check_call(
1547 self,
1548 callee: Type,
1549 args: list[Expression],
1550 arg_kinds: list[ArgKind],
1551 context: Context,
1552 arg_names: Sequence[str | None] | None = None,
1553 callable_node: Expression | None = None,
1554 callable_name: str | None = None,
1555 object_type: Type | None = None,
1556 original_type: Type | None = None,
1557 ) -> tuple[Type, Type]:
1558 """Type check a call.
1559
1560 Also infer type arguments if the callee is a generic function.
1561
1562 Return (result type, inferred callee type).
1563
1564 Arguments:
1565 callee: type of the called value
1566 args: actual argument expressions
1567 arg_kinds: contains nodes.ARG_* constant for each argument in args
1568 describing whether the argument is positional, *arg, etc.
1569 context: current expression context, used for inference.
1570 arg_names: names of arguments (optional)
1571 callable_node: associate the inferred callable type to this node,
1572 if specified
1573 callable_name: Fully-qualified name of the function/method to call,
1574 or None if unavailable (examples: 'builtins.open', 'typing.Mapping.get')
1575 object_type: If callable_name refers to a method, the type of the object
1576 on which the method is being called
1577 """
1578 callee = get_proper_type(callee)
1579
1580 if isinstance(callee, CallableType):
1581 if callee.variables:
1582 overloaded = self.is_generic_decorator_overload_call(callee, args)
1583 if overloaded is not None:
1584 # Special casing for inline application of generic callables to overloads.
1585 # Supporting general case would be tricky, but this should cover 95% of cases.
1586 overloaded_result = self.handle_decorator_overload_call(
1587 callee, overloaded, context
1588 )
1589 if overloaded_result is not None:
1590 return overloaded_result
1591
1592 return self.check_callable_call(
1593 callee,
1594 args,
1595 arg_kinds,
1596 context,
1597 arg_names,
1598 callable_node,
1599 callable_name,
1600 object_type,
1601 )
1602 elif isinstance(callee, Overloaded):
1603 return self.check_overload_call(
1604 callee, args, arg_kinds, arg_names, callable_name, object_type, context
1605 )
1606 elif isinstance(callee, AnyType) or not self.chk.in_checked_function():
1607 return self.check_any_type_call(args, arg_kinds, callee, context)
1608 elif isinstance(callee, UnionType):
1609 return self.check_union_call(callee, args, arg_kinds, arg_names, context)
1610 elif isinstance(callee, Instance):
1611 call_function = analyze_member_access(
1612 "__call__",
1613 callee,
1614 context,
1615 is_lvalue=False,
1616 is_super=False,
1617 is_operator=True,
1618 original_type=original_type or callee,
1619 chk=self.chk,
1620 in_literal_context=self.is_literal_context(),
1621 )
1622 callable_name = callee.type.fullname + ".__call__"
1623 # Apply method signature hook, if one exists
1624 call_function = self.transform_callee_type(
1625 callable_name, call_function, args, arg_kinds, context, arg_names, callee
1626 )
1627 result = self.check_call(
1628 call_function,
1629 args,
1630 arg_kinds,
1631 context,
1632 arg_names,
1633 callable_node,
1634 callable_name,
1635 callee,
1636 )
1637 if callable_node:
1638 # check_call() stored "call_function" as the type, which is incorrect.
1639 # Override the type.
1640 self.chk.store_type(callable_node, callee)
1641 return result
1642 elif isinstance(callee, TypeVarType):
1643 return self.check_call(
1644 callee.upper_bound, args, arg_kinds, context, arg_names, callable_node
1645 )
1646 elif isinstance(callee, TypeType):
1647 item = self.analyze_type_type_callee(callee.item, context)
1648 return self.check_call(item, args, arg_kinds, context, arg_names, callable_node)
1649 elif isinstance(callee, TupleType):
1650 return self.check_call(
1651 tuple_fallback(callee),
1652 args,
1653 arg_kinds,
1654 context,
1655 arg_names,
1656 callable_node,
1657 callable_name,
1658 object_type,
1659 original_type=callee,
1660 )
1661 elif isinstance(callee, UninhabitedType):
1662 ret = UninhabitedType()
1663 ret.ambiguous = callee.ambiguous
1664 return callee, ret
1665 else:
1666 return self.msg.not_callable(callee, context), AnyType(TypeOfAny.from_error)
1667
1668 def check_callable_call(
1669 self,
1670 callee: CallableType,
1671 args: list[Expression],
1672 arg_kinds: list[ArgKind],
1673 context: Context,
1674 arg_names: Sequence[str | None] | None,
1675 callable_node: Expression | None,
1676 callable_name: str | None,
1677 object_type: Type | None,
1678 ) -> tuple[Type, Type]:
1679 """Type check a call that targets a callable value.
1680
1681 See the docstring of check_call for more information.
1682 """
1683 # Always unpack **kwargs before checking a call.
1684 callee = callee.with_unpacked_kwargs().with_normalized_var_args()
1685 if callable_name is None and callee.name:
1686 callable_name = callee.name
1687 if callee.is_type_obj():
1688 instance_type = callee.get_instance_type(force_fallback=True)
1689 if isinstance(instance_type, Instance):
1690 callable_name = instance_type.type.fullname
1691 if isinstance(callable_node, RefExpr) and callable_node.fullname in ENUM_BASES:
1692 # An Enum() call that failed SemanticAnalyzerPass2.check_enum_call().
1693 return callee.ret_type, callee
1694
1695 if (
1696 callee.is_type_obj()
1697 and callee.type_object().is_protocol
1698 # Exception for Type[...]
1699 and not callee.from_type_type
1700 ):
1701 self.chk.fail(
1702 message_registry.CANNOT_INSTANTIATE_PROTOCOL.format(callee.type_object().name),
1703 context,
1704 )
1705 elif (
1706 callee.is_type_obj()
1707 and callee.type_object().is_abstract
1708 # Exception for Type[...]
1709 and not callee.from_type_type
1710 and not callee.type_object().fallback_to_any
1711 ):
1712 type = callee.type_object()
1713 # Determine whether the implicitly abstract attributes are functions with
1714 # None-compatible return types.
1715 abstract_attributes: dict[str, bool] = {}
1716 for attr_name, abstract_status in type.abstract_attributes:
1717 if abstract_status == IMPLICITLY_ABSTRACT:
1718 abstract_attributes[attr_name] = self.can_return_none(type, attr_name)
1719 else:
1720 abstract_attributes[attr_name] = False
1721 self.msg.cannot_instantiate_abstract_class(
1722 callee.type_object().name, abstract_attributes, context
1723 )
1724
1725 var_arg = callee.var_arg()
1726 if var_arg and isinstance(var_arg.typ, UnpackType):
1727 # It is hard to support multiple variadic unpacks (except for old-style *args: int),
1728 # fail gracefully to avoid crashes later.
1729 seen_unpack = False
1730 for arg, arg_kind in zip(args, arg_kinds):
1731 if arg_kind != ARG_STAR:
1732 continue
1733 arg_type = get_proper_type(self.accept(arg))
1734 if not isinstance(arg_type, TupleType) or any(
1735 isinstance(t, UnpackType) for t in arg_type.items
1736 ):
1737 if seen_unpack:
1738 self.msg.fail(
1739 "Passing multiple variadic unpacks in a call is not supported",
1740 context,
1741 code=codes.CALL_ARG,
1742 )
1743 return AnyType(TypeOfAny.from_error), callee
1744 seen_unpack = True
1745
1746 # This is tricky: return type may contain its own type variables, like in
1747 # def [S] (S) -> def [T] (T) -> tuple[S, T], so we need to update their ids
1748 # to avoid possible id clashes if this call itself appears in a generic
1749 # function body.
1750 ret_type = get_proper_type(callee.ret_type)
1751 if isinstance(ret_type, CallableType) and ret_type.variables:
1752 fresh_ret_type = freshen_all_functions_type_vars(callee.ret_type)
1753 freeze_all_type_vars(fresh_ret_type)
1754 callee = callee.copy_modified(ret_type=fresh_ret_type)
1755
1756 if callee.is_generic():
1757 callee = freshen_function_type_vars(callee)
1758 callee = self.infer_function_type_arguments_using_context(callee, context)
1759
1760 formal_to_actual = map_actuals_to_formals(
1761 arg_kinds,
1762 arg_names,
1763 callee.arg_kinds,
1764 callee.arg_names,
1765 lambda i: self.accept(args[i]),
1766 )
1767
1768 if callee.special_sig == "tuple" and len(args) == 1:
1769 with self.msg.filter_errors():
1770 arg_type = get_proper_type(self.accept(args[0]))
1771 # Give precise constructor signature for situations like this:
1772 # class Shape[*Ts](tuple[*Ts]): ...
1773 # Shape((1, 2))
1774 # The argument type is the same as return type, but with builtins.tuple fallback.
1775 if isinstance(arg_type, TupleType):
1776 assert isinstance(callee.ret_type, ProperType)
1777 if isinstance(callee.ret_type, TupleType):
1778 # Actual type argument is ignored by tuple_fallback() in this case.
1779 any_type = AnyType(TypeOfAny.special_form)
1780 new_arg_type = callee.ret_type.copy_modified(
1781 fallback=self.chk.named_generic_type("builtins.tuple", [any_type])
1782 )
1783 callee = callee.copy_modified(arg_types=[new_arg_type])
1784 elif isinstance(callee.ret_type, Instance):
1785 new_arg_type = map_instance_to_supertype(
1786 callee.ret_type, self.chk.lookup_typeinfo("builtins.tuple")
1787 )
1788 callee = callee.copy_modified(arg_types=[new_arg_type])
1789
1790 if callee.is_generic():
1791 need_refresh = any(
1792 isinstance(v, (ParamSpecType, TypeVarTupleType)) for v in callee.variables
1793 )
1794 callee = self.infer_function_type_arguments(
1795 callee, args, arg_kinds, arg_names, formal_to_actual, need_refresh, context
1796 )
1797 if need_refresh:
1798 # Argument kinds etc. may have changed due to
1799 # ParamSpec or TypeVarTuple variables being replaced with an arbitrary
1800 # number of arguments; recalculate actual-to-formal map
1801 formal_to_actual = map_actuals_to_formals(
1802 arg_kinds,
1803 arg_names,
1804 callee.arg_kinds,
1805 callee.arg_names,
1806 lambda i: self.accept(args[i]),
1807 )
1808
1809 param_spec = callee.param_spec()
1810 if (
1811 param_spec is not None
1812 and arg_kinds == [ARG_STAR, ARG_STAR2]
1813 and len(formal_to_actual) == 2
1814 ):
1815 arg1 = self.accept(args[0])
1816 arg2 = self.accept(args[1])
1817 if (
1818 isinstance(arg1, ParamSpecType)
1819 and isinstance(arg2, ParamSpecType)
1820 and arg1.flavor == ParamSpecFlavor.ARGS
1821 and arg2.flavor == ParamSpecFlavor.KWARGS
1822 and arg1.id == arg2.id == param_spec.id
1823 ):
1824 return callee.ret_type, callee
1825
1826 arg_types = self.infer_arg_types_in_context(callee, args, arg_kinds, formal_to_actual)
1827
1828 might_have_shifted_args = (
1829 not self.msg.prefer_simple_messages()
1830 and len(args) >= 2 # see gh-21427
1831 and all(k == ARG_POS for k in callee.arg_kinds)
1832 and all(k == ARG_POS for k in arg_kinds)
1833 and len(arg_kinds) == len(callee.arg_kinds) - 1
1834 )
1835
1836 if might_have_shifted_args:
1837 with self.msg.filter_errors(save_filtered_errors=True) as w:
1838 ok = self.check_argument_count(
1839 callee,
1840 arg_types,
1841 arg_kinds,
1842 arg_names,
1843 formal_to_actual,
1844 context,
1845 object_type,
1846 callable_name,
1847 )
1848 if not ok and self._detect_missing_positional_arg(
1849 callee, arg_types, arg_kinds, args, context
1850 ):
1851 pass
1852 else:
1853 self.msg.add_errors(w.filtered_errors())
1854 self.check_argument_types(
1855 arg_types,
1856 arg_kinds,
1857 args,
1858 callee,
1859 formal_to_actual,
1860 context,
1861 object_type=object_type,
1862 )
1863 else:
1864 self.check_argument_count(
1865 callee,
1866 arg_types,
1867 arg_kinds,
1868 arg_names,
1869 formal_to_actual,
1870 context,
1871 object_type,
1872 callable_name,
1873 )
1874 self.check_argument_types(
1875 arg_types,
1876 arg_kinds,
1877 args,
1878 callee,
1879 formal_to_actual,
1880 context,
1881 object_type=object_type,
1882 )
1883
1884 if (
1885 callee.is_type_obj()
1886 and (len(arg_types) == 1)
1887 and is_named_instance(callee.get_instance_type(), "builtins.type")
1888 ):
1889 callee = callee.copy_modified(ret_type=TypeType.make_normalized(arg_types[0]))
1890
1891 if callable_node:
1892 # Store the inferred callable type.
1893 self.chk.store_type(callable_node, callee)
1894
1895 if callable_name and (
1896 (object_type is None and self.plugin.get_function_hook(callable_name))
1897 or (object_type is not None and self.plugin.get_method_hook(callable_name))
1898 ):
1899 new_ret_type = self.apply_function_plugin(
1900 callee,
1901 arg_kinds,
1902 arg_types,
1903 arg_names,
1904 formal_to_actual,
1905 args,
1906 callable_name,
1907 object_type,
1908 context,
1909 )
1910 callee = callee.copy_modified(ret_type=new_ret_type)
1911 return callee.ret_type, callee
1912
1913 def can_return_none(self, type: TypeInfo, attr_name: str) -> bool:
1914 """Is the given attribute a method with a None-compatible return type?
1915
1916 Overloads are only checked if there is an implementation.
1917 """
1918 if not state.strict_optional:
1919 # If strict-optional is not set, is_subtype(NoneType(), T) is always True.
1920 # So, we cannot do anything useful here in that case.
1921 return False
1922 for base in type.mro:
1923 symnode = base.names.get(attr_name)
1924 if symnode is None:
1925 continue
1926 node = symnode.node
1927 if isinstance(node, OverloadedFuncDef):
1928 node = node.impl
1929 if isinstance(node, Decorator):
1930 node = node.func
1931 if isinstance(node, FuncDef):
1932 if node.type is not None:
1933 assert isinstance(node.type, CallableType)
1934 return is_subtype(NoneType(), node.type.ret_type)
1935 return False
1936
1937 def analyze_type_type_callee(self, item: ProperType, context: Context) -> Type:
1938 """Analyze the callee X in X(...) where X is Type[item].
1939
1940 Return a Y that we can pass to check_call(Y, ...).
1941 """
1942 if isinstance(item, AnyType):
1943 return AnyType(TypeOfAny.from_another_any, source_any=item)
1944 if isinstance(item, Instance):
1945 res = type_object_type(item.type)
1946 if isinstance(res, CallableType):
1947 res = res.copy_modified(from_type_type=True)
1948 expanded = expand_type_by_instance(res, item)
1949 if isinstance(expanded, CallableType):
1950 # Callee of the form Type[...] should never be generic, only
1951 # proper class objects can be.
1952 expanded = expanded.copy_modified(variables=[])
1953 return expanded
1954 if isinstance(item, UnionType):
1955 return UnionType(
1956 [
1957 self.analyze_type_type_callee(get_proper_type(tp), context)
1958 for tp in item.relevant_items()
1959 ],
1960 item.line,
1961 )
1962 if isinstance(item, TypeVarType):
1963 # Pretend we're calling the typevar's upper bound,
1964 # i.e. its constructor (a poor approximation for reality,
1965 # but better than AnyType...), but replace the return type
1966 # with typevar.
1967 callee = self.analyze_type_type_callee(get_proper_type(item.upper_bound), context)
1968 return self.replace_type_type_callee_ret_type(callee, item)
1969 # We support Type of namedtuples but not of tuples in general
1970 if isinstance(item, TupleType) and tuple_fallback(item).type.fullname != "builtins.tuple":
1971 return self.analyze_type_type_callee(tuple_fallback(item), context)
1972 if isinstance(item, TypedDictType):
1973 return self.typeddict_callable_from_context(item)
1974
1975 self.msg.unsupported_type_type(item, context)
1976 return AnyType(TypeOfAny.from_error)
1977
1978 def replace_type_type_callee_ret_type(self, callee: Type, ret_type: Type) -> Type:
1979 callee = get_proper_type(callee)
1980 if isinstance(callee, CallableType):
1981 return callee.copy_modified(ret_type=ret_type)
1982 if isinstance(callee, Overloaded):
1983 return Overloaded([c.copy_modified(ret_type=ret_type) for c in callee.items])
1984 if isinstance(callee, UnionType):
1985 return UnionType(
1986 [
1987 self.replace_type_type_callee_ret_type(item, ret_type)
1988 for item in callee.relevant_items()
1989 ],
1990 line=callee.line,
1991 column=callee.column,
1992 )
1993 return callee
1994
1995 def infer_arg_types_in_empty_context(self, args: list[Expression]) -> list[Type]:
1996 """Infer argument expression types in an empty context.
1997
1998 In short, we basically recurse on each argument without considering
1999 in what context the argument was called.
2000 """
2001 res: list[Type] = []
2002
2003 for arg in args:
2004 arg_type = self.accept(arg)
2005 if has_erased_component(arg_type):
2006 res.append(NoneType())
2007 else:
2008 res.append(arg_type)
2009 return res
2010
2011 def infer_more_unions_for_recursive_type(self, type_context: Type) -> bool:
2012 """Adjust type inference of unions if type context has a recursive type.
2013
2014 Return the old state. The caller must assign it to type_state.infer_unions
2015 afterwards.
2016
2017 This is a hack to better support inference for recursive types.
2018
2019 Note: This is performance-sensitive and must not be a context manager
2020 until mypyc supports them better.
2021 """
2022 old = type_state.infer_unions
2023 if has_recursive_types(type_context):
2024 type_state.infer_unions = True
2025 return old
2026
2027 def infer_arg_types_in_context(
2028 self,
2029 callee: CallableType,
2030 args: list[Expression],
2031 arg_kinds: list[ArgKind],
2032 formal_to_actual: list[list[int]],
2033 ) -> list[Type]:
2034 """Infer argument expression types using a callable type as context.
2035
2036 For example, if callee argument 2 has type List[int], infer the
2037 argument expression with List[int] type context.
2038
2039 Returns the inferred types of *actual arguments*.
2040 """
2041 # Precompute arg_context so that we type check argument expressions in evaluation order
2042 arg_context: list[Type | None] = [None] * len(args)
2043 for fi, actuals in enumerate(formal_to_actual):
2044 for ai in actuals:
2045 if arg_kinds[ai].is_star():
2046 continue
2047 arg_context[ai] = callee.arg_types[fi]
2048
2049 res = []
2050 for arg, ctx in zip(args, arg_context):
2051 if ctx is not None:
2052 # When the outer context for a function call is known to be recursive,
2053 # we solve type constraints inferred from arguments using unions instead
2054 # of joins. This is a bit arbitrary, but in practice it works for most
2055 # cases. A cleaner alternative would be to switch to single bin type
2056 # inference, but this is a lot of work.
2057 old = self.infer_more_unions_for_recursive_type(ctx)
2058 res.append(self.accept(arg, ctx))
2059 # We need to manually restore union inference state, ugh.
2060 type_state.infer_unions = old
2061 else:
2062 res.append(self.accept(arg))
2063 return res
2064
2065 def infer_function_type_arguments_using_context(
2066 self, callable: CallableType, error_context: Context
2067 ) -> CallableType:
2068 """Unify callable return type to type context to infer type vars.
2069
2070 For example, if the return type is set[t] where 't' is a type variable
2071 of callable, and if the context is set[int], return callable modified
2072 by substituting 't' with 'int'.
2073 """
2074 ctx = self.type_context[-1]
2075 if not ctx:
2076 return callable
2077 # The return type may have references to type metavariables that
2078 # we are inferring right now. We must consider them as indeterminate
2079 # and they are not potential results; thus we replace them with the
2080 # special ErasedType type. On the other hand, class type variables are
2081 # valid results.
2082 erased_ctx = replace_meta_vars(ctx, ErasedType())
2083 ret_type = callable.ret_type
2084 if is_overlapping_none(ret_type) and is_overlapping_none(ctx):
2085 # If both the context and the return type are optional, unwrap the optional,
2086 # since in 99% cases this is what a user expects. In other words, we replace
2087 # Optional[T] <: Optional[int]
2088 # with
2089 # T <: int
2090 # while the former would infer T <: Optional[int].
2091 ret_type = remove_optional(ret_type)
2092 erased_ctx = remove_optional(erased_ctx)
2093 #
2094 # TODO: Instead of this hack and the one below, we need to use outer and
2095 # inner contexts at the same time. This is however not easy because of two
2096 # reasons:
2097 # * We need to support constraints like [1 <: 2, 2 <: X], i.e. with variables
2098 # on both sides. (This is not too hard.)
2099 # * We need to update all the inference "infrastructure", so that all
2100 # variables in an expression are inferred at the same time.
2101 # (And this is hard, also we need to be careful with lambdas that require
2102 # two passes.)
2103 proper_ret = get_proper_type(ret_type)
2104 if (
2105 isinstance(proper_ret, TypeVarType)
2106 or isinstance(proper_ret, UnionType)
2107 and all(isinstance(get_proper_type(u), TypeVarType) for u in proper_ret.items)
2108 ):
2109 # Another special case: the return type is a type variable. If it's unrestricted,
2110 # we could infer a too general type for the type variable if we use context,
2111 # and this could result in confusing and spurious type errors elsewhere.
2112 #
2113 # So we give up and just use function arguments for type inference, with just two
2114 # exceptions:
2115 #
2116 # 1. If the context is a generic instance type, actually use it as context, as
2117 # this *seems* to usually be the reasonable thing to do.
2118 #
2119 # See also github issues #462 and #360.
2120 #
2121 # 2. If the context is some literal type, we want to "propagate" that information
2122 # down so that we infer a more precise type for literal expressions. For example,
2123 # the expression `3` normally has an inferred type of `builtins.int`: but if it's
2124 # in a literal context like below, we want it to infer `Literal[3]` instead.
2125 #
2126 # def expects_literal(x: Literal[3]) -> None: pass
2127 # def identity(x: T) -> T: return x
2128 #
2129 # expects_literal(identity(3)) # Should type-check
2130 # TODO: we may want to add similar exception if all arguments are lambdas, since
2131 # in this case external context is almost everything we have.
2132 if not is_generic_instance(ctx) and not is_literal_type_like(ctx):
2133 return callable.copy_modified()
2134 args = infer_type_arguments(
2135 callable.variables, ret_type, erased_ctx, skip_unsatisfied=True
2136 )
2137 # Only substitute non-Uninhabited and non-erased types.
2138 new_args: list[Type | None] = []
2139 for arg in args:
2140 if has_ambiguous_uninhabited_component(arg) or has_erased_component(arg):
2141 new_args.append(None)
2142 else:
2143 new_args.append(arg)
2144 # Don't show errors after we have only used the outer context for inference.
2145 # We will use argument context to infer more variables.
2146 return self.apply_generic_arguments(
2147 callable, new_args, error_context, skip_unsatisfied=True
2148 )
2149
2150 def infer_function_type_arguments(
2151 self,
2152 callee_type: CallableType,
2153 args: list[Expression],
2154 arg_kinds: list[ArgKind],
2155 arg_names: Sequence[str | None] | None,
2156 formal_to_actual: list[list[int]],
2157 need_refresh: bool,
2158 context: Context,
2159 ) -> CallableType:
2160 """Infer the type arguments for a generic callee type.
2161
2162 Infer based on the types of arguments.
2163
2164 Return a derived callable type that has the arguments applied.
2165 """
2166 if self.chk.in_checked_function():
2167 # Disable type errors during type inference. There may be errors
2168 # due to partial available context information at this time, but
2169 # these errors can be safely ignored as the arguments will be
2170 # inferred again later.
2171 with self.msg.filter_errors():
2172 arg_types = self.infer_arg_types_in_context(
2173 callee_type, args, arg_kinds, formal_to_actual
2174 )
2175
2176 arg_pass_nums = self.get_arg_infer_passes(
2177 callee_type, args, arg_types, formal_to_actual, len(args)
2178 )
2179
2180 pass1_args: list[Type | None] = []
2181 for i, arg in enumerate(arg_types):
2182 if arg_pass_nums[i] > 1:
2183 pass1_args.append(None)
2184 else:
2185 pass1_args.append(arg)
2186
2187 inferred_args, _ = infer_function_type_arguments(
2188 callee_type,
2189 pass1_args,
2190 arg_kinds,
2191 arg_names,
2192 formal_to_actual,
2193 context=self.argument_infer_context(),
2194 strict=self.chk.in_checked_function(),
2195 )
2196
2197 if 2 in arg_pass_nums:
2198 # Second pass of type inference.
2199 callee_type, inferred_args = self.infer_function_type_arguments_pass2(
2200 callee_type,
2201 args,
2202 arg_kinds,
2203 arg_names,
2204 formal_to_actual,
2205 inferred_args,
2206 need_refresh,
2207 context,
2208 )
2209
2210 if (
2211 callee_type.special_sig == "dict"
2212 and len(inferred_args) == 2
2213 and (ARG_NAMED in arg_kinds or ARG_STAR2 in arg_kinds)
2214 ):
2215 # HACK: Infer str key type for dict(...) with keyword args. The type system
2216 # can't represent this so we special case it, as this is a pretty common
2217 # thing. This doesn't quite work with all possible subclasses of dict
2218 # if they shuffle type variables around, as we assume that there is a 1-1
2219 # correspondence with dict type variables. This is a marginal issue and
2220 # a little tricky to fix so it's left unfixed for now.
2221 first_arg = get_proper_type(inferred_args[0])
2222 if isinstance(first_arg, (NoneType, UninhabitedType)):
2223 inferred_args[0] = self.named_type("builtins.str")
2224 elif not first_arg or not is_subtype(self.named_type("builtins.str"), first_arg):
2225 self.chk.fail(message_registry.KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE, context)
2226
2227 if not self.chk.options.old_type_inference and any(
2228 a is None
2229 or isinstance(get_proper_type(a), UninhabitedType)
2230 or set(get_type_vars(a)) & set(callee_type.variables)
2231 for a in inferred_args
2232 ):
2233 if need_refresh:
2234 # Technically we need to refresh formal_to_actual after *each* inference pass,
2235 # since each pass can expand ParamSpec or TypeVarTuple. Although such situations
2236 # are very rare, not doing this can cause crashes.
2237 formal_to_actual = map_actuals_to_formals(
2238 arg_kinds,
2239 arg_names,
2240 callee_type.arg_kinds,
2241 callee_type.arg_names,
2242 lambda a: self.accept(args[a]),
2243 )
2244 # If the regular two-phase inference didn't work, try inferring type
2245 # variables while allowing for polymorphic solutions, i.e. for solutions
2246 # potentially involving free variables.
2247 # TODO: support the similar inference for return type context.
2248 poly_inferred_args, free_vars = infer_function_type_arguments(
2249 callee_type,
2250 arg_types,
2251 arg_kinds,
2252 arg_names,
2253 formal_to_actual,
2254 context=self.argument_infer_context(),
2255 strict=self.chk.in_checked_function(),
2256 allow_polymorphic=True,
2257 )
2258 poly_callee_type = self.apply_generic_arguments(
2259 callee_type, poly_inferred_args, context
2260 )
2261 # Try applying inferred polymorphic type if possible, e.g. Callable[[T], T] can
2262 # be interpreted as def [T] (T) -> T, but dict[T, T] cannot be expressed.
2263 applied = applytype.apply_poly(poly_callee_type, free_vars)
2264 if applied is not None and all(
2265 a is not None and not isinstance(get_proper_type(a), UninhabitedType)
2266 for a in poly_inferred_args
2267 ):
2268 freeze_all_type_vars(applied)
2269 return applied
2270 # If it didn't work, erase free variables as uninhabited, to avoid confusing errors.
2271 unknown = UninhabitedType()
2272 unknown.ambiguous = True
2273 inferred_args = [
2274 (
2275 expand_type(
2276 a, {v.id: unknown for v in list(callee_type.variables) + free_vars}
2277 )
2278 if a is not None
2279 else None
2280 )
2281 for a in poly_inferred_args
2282 ]
2283 else:
2284 # In dynamically typed functions use implicit 'Any' types for
2285 # type variables.
2286 inferred_args = [AnyType(TypeOfAny.unannotated)] * len(callee_type.variables)
2287 return self.apply_inferred_arguments(callee_type, inferred_args, context)
2288
2289 def infer_function_type_arguments_pass2(
2290 self,
2291 callee_type: CallableType,
2292 args: list[Expression],
2293 arg_kinds: list[ArgKind],
2294 arg_names: Sequence[str | None] | None,
2295 formal_to_actual: list[list[int]],
2296 old_inferred_args: Sequence[Type | None],
2297 need_refresh: bool,
2298 context: Context,
2299 ) -> tuple[CallableType, list[Type | None]]:
2300 """Perform second pass of generic function type argument inference.
2301
2302 The second pass is needed for arguments with types such as Callable[[T], S],
2303 where both T and S are type variables, when the actual argument is a
2304 lambda with inferred types. The idea is to infer the type variable T
2305 in the first pass (based on the types of other arguments). This lets
2306 us infer the argument and return type of the lambda expression and
2307 thus also the type variable S in this second pass.
2308
2309 Return (the callee with type vars applied, inferred actual arg types).
2310 """
2311 # None or erased types in inferred types mean that there was not enough
2312 # information to infer the argument. Replace them with None values so
2313 # that they are not applied yet below.
2314 inferred_args = list(old_inferred_args)
2315 for i, arg in enumerate(get_proper_types(inferred_args)):
2316 if isinstance(arg, (NoneType, UninhabitedType)) or has_erased_component(arg):
2317 inferred_args[i] = None
2318 callee_type = self.apply_generic_arguments(callee_type, inferred_args, context)
2319
2320 if not callee_type.is_generic():
2321 # Fast path, second pass can't give new information.
2322 return callee_type, []
2323
2324 if need_refresh:
2325 formal_to_actual = map_actuals_to_formals(
2326 arg_kinds,
2327 arg_names,
2328 callee_type.arg_kinds,
2329 callee_type.arg_names,
2330 lambda a: self.accept(args[a]),
2331 )
2332
2333 # Same as during first pass, disable type errors (we still have partial context).
2334 with self.msg.filter_errors():
2335 arg_types = self.infer_arg_types_in_context(
2336 callee_type, args, arg_kinds, formal_to_actual
2337 )
2338
2339 inferred_args, _ = infer_function_type_arguments(
2340 callee_type,
2341 arg_types,
2342 arg_kinds,
2343 arg_names,
2344 formal_to_actual,
2345 context=self.argument_infer_context(),
2346 )
2347
2348 return callee_type, inferred_args
2349
2350 def argument_infer_context(self) -> ArgumentInferContext:
2351 if self._arg_infer_context_cache is None:
2352 self._arg_infer_context_cache = ArgumentInferContext(
2353 self.chk.named_type("typing.Mapping"), self.chk.named_type("typing.Iterable")
2354 )
2355 return self._arg_infer_context_cache
2356
2357 def get_arg_infer_passes(
2358 self,
2359 callee: CallableType,
2360 args: list[Expression],
2361 arg_types: list[Type],
2362 formal_to_actual: list[list[int]],
2363 num_actuals: int,
2364 ) -> list[int]:
2365 """Return pass numbers for args for two-pass argument type inference.
2366
2367 For each actual, the pass number is either 1 (first pass) or 2 (second
2368 pass).
2369
2370 Two-pass argument type inference primarily lets us infer types of
2371 lambdas more effectively.
2372 """
2373 res = [1] * num_actuals
2374 for i, arg in enumerate(callee.arg_types):
2375 skip_param_spec = False
2376 p_formal = get_proper_type(callee.arg_types[i])
2377 if isinstance(p_formal, CallableType) and p_formal.param_spec():
2378 for j in formal_to_actual[i]:
2379 p_actual = get_proper_type(arg_types[j])
2380 # This is an exception from the usual logic where we put generic Callable
2381 # arguments in the second pass. If we have a non-generic actual, it is
2382 # likely to infer good constraints, for example if we have:
2383 # def run(Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...
2384 # def test(x: int, y: int) -> int: ...
2385 # run(test, 1, 2)
2386 # we will use `test` for inference, since it will allow to infer also
2387 # argument *names* for P <: [x: int, y: int].
2388 if isinstance(p_actual, Instance):
2389 call_method = find_member("__call__", p_actual, p_actual, is_operator=True)
2390 if call_method is not None:
2391 p_actual = get_proper_type(call_method)
2392 if (
2393 isinstance(p_actual, CallableType)
2394 and not p_actual.variables
2395 and not isinstance(args[j], LambdaExpr)
2396 ):
2397 skip_param_spec = True
2398 break
2399 if not skip_param_spec and arg.accept(ArgInferSecondPassQuery()):
2400 for j in formal_to_actual[i]:
2401 res[j] = 2
2402 return res
2403
2404 def apply_inferred_arguments(
2405 self, callee_type: CallableType, inferred_args: Sequence[Type | None], context: Context
2406 ) -> CallableType:
2407 """Apply inferred values of type arguments to a generic function.
2408
2409 Inferred_args contains the values of function type arguments.
2410 """
2411 # Report error if some of the variables could not be solved. In that
2412 # case assume that all variables have type Any to avoid extra
2413 # bogus error messages.
2414 for inferred_type, tv in zip(inferred_args, callee_type.variables):
2415 if not inferred_type or has_erased_component(inferred_type):
2416 # Could not infer a non-trivial type for a type variable.
2417 self.msg.could_not_infer_type_arguments(callee_type, tv, context)
2418 inferred_args = [AnyType(TypeOfAny.from_error)] * len(inferred_args)
2419 # Apply the inferred types to the function type. In this case the
2420 # return type must be CallableType, since we give the right number of type
2421 # arguments.
2422 return self.apply_generic_arguments(callee_type, inferred_args, context)
2423
2424 def _detect_missing_positional_arg(
2425 self,
2426 callee: CallableType,
2427 arg_types: list[Type],
2428 arg_kinds: list[ArgKind],
2429 args: list[Expression],
2430 context: Context,
2431 ) -> bool:
2432 """Try to identify a single missing positional argument using type alignment.
2433
2434 If the caller and callee are just positional arguments and exactly one arg is missing,
2435 we scan left to right to find which argument skipped. If only the last argument is missing,
2436 we return False since it's already handled in a desired manner. If there is an error,
2437 report it and return True, or return False to fall back to normal checking.
2438 """
2439 if not all(k == ARG_POS for k in callee.arg_kinds):
2440 return False
2441 if not all(k == ARG_POS for k in arg_kinds):
2442 return False
2443 if len(arg_kinds) != len(callee.arg_kinds) - 1:
2444 return False
2445
2446 skip_idx: int | None = None
2447 j = 0
2448 for i in range(len(callee.arg_types)):
2449 if j >= len(arg_types):
2450 skip_idx = i
2451 break
2452 if is_subtype(arg_types[j], callee.arg_types[i], options=self.chk.options):
2453 j += 1
2454 elif skip_idx is None:
2455 skip_idx = i
2456 else:
2457 return False
2458
2459 if skip_idx is None or j != len(arg_types):
2460 return False
2461
2462 if skip_idx == len(callee.arg_types) - 1:
2463 return False
2464
2465 param_name = callee.arg_names[skip_idx]
2466 callee_name = callable_name(callee)
2467 if param_name is None or callee_name is None:
2468 return False
2469
2470 msg = f'Missing positional argument "{param_name}" in call to {callee_name}'
2471 ctx = args[skip_idx] if skip_idx < len(args) else context
2472 self.msg.fail(msg, ctx, code=codes.CALL_ARG)
2473 return True
2474
2475 def check_argument_count(
2476 self,
2477 callee: CallableType,
2478 actual_types: list[Type],
2479 actual_kinds: list[ArgKind],
2480 actual_names: Sequence[str | None] | None,
2481 formal_to_actual: list[list[int]],
2482 context: Context | None,
2483 object_type: Type | None = None,
2484 callable_name: str | None = None,
2485 ) -> bool:
2486 """Check that there is a value for all required arguments to a function.
2487
2488 Also check that there are no duplicate values for arguments. Report found errors
2489 using 'messages' if it's not None. If 'messages' is given, 'context' must also be given.
2490
2491 Return False if there were any errors. Otherwise return True
2492 """
2493 if context is None:
2494 # Avoid "is None" checks
2495 context = TempNode(AnyType(TypeOfAny.special_form))
2496
2497 # TODO(jukka): We could return as soon as we find an error if messages is None.
2498
2499 # Collect dict of all actual arguments matched to formal arguments, with occurrence count
2500 all_actuals: dict[int, int] = {}
2501 for actuals in formal_to_actual:
2502 for a in actuals:
2503 all_actuals[a] = all_actuals.get(a, 0) + 1
2504
2505 ok, is_unexpected_arg_error = self.check_for_extra_actual_arguments(
2506 callee, actual_types, actual_kinds, actual_names, all_actuals, context
2507 )
2508
2509 # Check for too many or few values for formals.
2510 for i, kind in enumerate(callee.arg_kinds):
2511 mapped_args = formal_to_actual[i]
2512 if kind.is_required() and not mapped_args and not is_unexpected_arg_error:
2513 # No actual for a mandatory formal
2514 if kind.is_positional():
2515 self.msg.too_few_arguments(callee, context, actual_names)
2516 if object_type and callable_name and "." in callable_name:
2517 self.missing_classvar_callable_note(object_type, callable_name, context)
2518 else:
2519 argname = callee.arg_names[i] or "?"
2520 self.msg.missing_named_argument(callee, context, argname)
2521 ok = False
2522 elif not kind.is_star() and is_duplicate_mapping(
2523 mapped_args, actual_types, actual_kinds
2524 ):
2525 if self.chk.in_checked_function() or isinstance(
2526 get_proper_type(actual_types[mapped_args[0]]), TupleType
2527 ):
2528 self.msg.duplicate_argument_value(callee, i, context)
2529 ok = False
2530 elif (
2531 kind.is_named()
2532 and mapped_args
2533 and actual_kinds[mapped_args[0]] not in [nodes.ARG_NAMED, nodes.ARG_STAR2]
2534 ):
2535 # Positional argument when expecting a keyword argument.
2536 self.msg.too_many_positional_arguments(callee, context)
2537 ok = False
2538 elif callee.param_spec() is not None:
2539 if not mapped_args and callee.special_sig != "partial":
2540 self.msg.too_few_arguments(callee, context, actual_names)
2541 ok = False
2542 elif len(mapped_args) > 1:
2543 paramspec_entries = sum(
2544 isinstance(get_proper_type(actual_types[k]), ParamSpecType)
2545 for k in mapped_args
2546 )
2547 if actual_kinds[mapped_args[0]] == nodes.ARG_STAR and paramspec_entries > 1:
2548 self.msg.fail("ParamSpec.args should only be passed once", context)
2549 ok = False
2550 if actual_kinds[mapped_args[0]] == nodes.ARG_STAR2 and paramspec_entries > 1:
2551 self.msg.fail("ParamSpec.kwargs should only be passed once", context)
2552 ok = False
2553 return ok
2554
2555 def check_for_extra_actual_arguments(
2556 self,
2557 callee: CallableType,
2558 actual_types: list[Type],
2559 actual_kinds: list[ArgKind],
2560 actual_names: Sequence[str | None] | None,
2561 all_actuals: dict[int, int],
2562 context: Context,
2563 ) -> tuple[bool, bool]:
2564 """Check for extra actual arguments.
2565
2566 Return tuple (was everything ok,
2567 was there an extra keyword argument error [used to avoid duplicate errors]).
2568 """
2569
2570 is_unexpected_arg_error = False # Keep track of errors to avoid duplicate errors
2571 ok = True # False if we've found any error
2572
2573 for i, kind in enumerate(actual_kinds):
2574 if (
2575 i not in all_actuals
2576 and
2577 # We accept the other iterables than tuple (including Any)
2578 # as star arguments because they could be empty, resulting no arguments.
2579 (kind != nodes.ARG_STAR or is_non_empty_tuple(actual_types[i]))
2580 and
2581 # Accept all types for double-starred arguments, because they could be empty
2582 # dictionaries and we can't tell it from their types
2583 kind != nodes.ARG_STAR2
2584 ):
2585 # Extra actual: not matched by a formal argument.
2586 ok = False
2587 if kind != nodes.ARG_NAMED:
2588 self.msg.too_many_arguments(callee, context)
2589 else:
2590 assert actual_names, "Internal error: named kinds without names given"
2591 act_name = actual_names[i]
2592 assert act_name is not None
2593 act_type = actual_types[i]
2594 self.msg.unexpected_keyword_argument(callee, act_name, act_type, context)
2595 is_unexpected_arg_error = True
2596 elif (
2597 kind == nodes.ARG_STAR and nodes.ARG_STAR not in callee.arg_kinds
2598 ) or kind == nodes.ARG_STAR2:
2599 actual_type = get_proper_type(actual_types[i])
2600 if isinstance(actual_type, (TupleType, TypedDictType)):
2601 if all_actuals.get(i, 0) < len(actual_type.items):
2602 # Too many tuple/dict items as some did not match.
2603 if kind != nodes.ARG_STAR2 or not isinstance(actual_type, TypedDictType):
2604 self.msg.too_many_arguments(callee, context)
2605 else:
2606 self.msg.too_many_arguments_from_typed_dict(
2607 callee, actual_type, context
2608 )
2609 is_unexpected_arg_error = True
2610 ok = False
2611 # *args/**kwargs can be applied even if the function takes a fixed
2612 # number of positional arguments. This may succeed at runtime.
2613
2614 return ok, is_unexpected_arg_error
2615
2616 def missing_classvar_callable_note(
2617 self, object_type: Type, callable_name: str, context: Context
2618 ) -> None:
2619 if isinstance(object_type, ProperType) and isinstance(object_type, Instance):
2620 _, var_name = callable_name.rsplit(".", maxsplit=1)
2621 node = object_type.type.get(var_name)
2622 if node is not None and isinstance(node.node, Var):
2623 if not node.node.is_inferred and not node.node.is_classvar:
2624 self.msg.note(
2625 f'"{var_name}" is considered instance variable,'
2626 " to make it class variable use ClassVar[...]",
2627 context,
2628 )
2629
2630 def check_var_args_kwargs(
2631 self, arg_types: list[Type], arg_kinds: list[ArgKind], context: Context
2632 ) -> None:
2633 for arg_type, arg_kind in zip(arg_types, arg_kinds):
2634 arg_type = get_proper_type(arg_type)
2635 if arg_kind == nodes.ARG_STAR and not self.is_valid_var_arg(arg_type):
2636 self.msg.invalid_var_arg(arg_type, context)
2637 if arg_kind == nodes.ARG_STAR2 and not self.is_valid_keyword_var_arg(arg_type):
2638 is_mapping = is_subtype(
2639 arg_type, self.chk.named_type("_typeshed.SupportsKeysAndGetItem")
2640 )
2641 self.msg.invalid_keyword_var_arg(arg_type, is_mapping, context)
2642
2643 def check_argument_types(
2644 self,
2645 arg_types: list[Type],
2646 arg_kinds: list[ArgKind],
2647 args: list[Expression],
2648 callee: CallableType,
2649 formal_to_actual: list[list[int]],
2650 context: Context,
2651 check_arg: ArgChecker | None = None,
2652 object_type: Type | None = None,
2653 ) -> None:
2654 """Check argument types against a callable type.
2655
2656 Report errors if the argument types are not compatible.
2657
2658 The check_call docstring describes some of the arguments.
2659 """
2660 self.check_var_args_kwargs(arg_types, arg_kinds, context)
2661
2662 check_arg = check_arg or self.check_arg
2663 # Keep track of consumed tuple *arg items.
2664 mapper = ArgTypeExpander(self.argument_infer_context())
2665
2666 for i, actuals in enumerate(formal_to_actual):
2667 orig_callee_arg_type = get_proper_type(callee.arg_types[i])
2668
2669 # Checking the case that we have more than one item but the first argument
2670 # is an unpack, so this would be something like:
2671 # [Tuple[Unpack[Ts]], int]
2672 #
2673 # In this case we have to check everything together, we do this by re-unifying
2674 # the suffices to the tuple, e.g. a single actual like
2675 # Tuple[Unpack[Ts], int]
2676 expanded_tuple = False
2677 actual_kinds = [arg_kinds[a] for a in actuals]
2678 if len(actuals) > 1:
2679 p_actual_type = get_proper_type(arg_types[actuals[0]])
2680 if (
2681 isinstance(p_actual_type, TupleType)
2682 and len(p_actual_type.items) == 1
2683 and isinstance(p_actual_type.items[0], UnpackType)
2684 and actual_kinds == [nodes.ARG_STAR] + [nodes.ARG_POS] * (len(actuals) - 1)
2685 ):
2686 actual_types = [p_actual_type.items[0]] + [arg_types[a] for a in actuals[1:]]
2687 if isinstance(orig_callee_arg_type, UnpackType):
2688 p_callee_type = get_proper_type(orig_callee_arg_type.type)
2689 if isinstance(p_callee_type, TupleType):
2690 assert p_callee_type.items
2691 callee_arg_types = p_callee_type.items
2692 callee_arg_kinds = [nodes.ARG_STAR] + [nodes.ARG_POS] * (
2693 len(p_callee_type.items) - 1
2694 )
2695 expanded_tuple = True
2696
2697 if not expanded_tuple:
2698 actual_types = [arg_types[a] for a in actuals]
2699 if isinstance(orig_callee_arg_type, UnpackType):
2700 unpacked_type = get_proper_type(orig_callee_arg_type.type)
2701 if isinstance(unpacked_type, TupleType):
2702 inner_unpack_index = find_unpack_in_list(unpacked_type.items)
2703 if inner_unpack_index is None:
2704 callee_arg_types = unpacked_type.items
2705 callee_arg_kinds = [ARG_POS] * len(actuals)
2706 else:
2707 inner_unpack = unpacked_type.items[inner_unpack_index]
2708 assert isinstance(inner_unpack, UnpackType)
2709 inner_unpacked_type = get_proper_type(inner_unpack.type)
2710 if isinstance(inner_unpacked_type, TypeVarTupleType):
2711 # This branch mimics the expanded_tuple case above but for
2712 # the case where caller passed a single * unpacked tuple argument.
2713 callee_arg_types = unpacked_type.items
2714 callee_arg_kinds = [
2715 ARG_POS if i != inner_unpack_index else ARG_STAR
2716 for i in range(len(unpacked_type.items))
2717 ]
2718 else:
2719 # We assume heterogeneous tuples are desugared earlier.
2720 assert isinstance(inner_unpacked_type, Instance)
2721 assert inner_unpacked_type.type.fullname == "builtins.tuple"
2722 callee_arg_types = (
2723 unpacked_type.items[:inner_unpack_index]
2724 + [inner_unpacked_type.args[0]]
2725 * (len(actuals) - len(unpacked_type.items) + 1)
2726 + unpacked_type.items[inner_unpack_index + 1 :]
2727 )
2728 callee_arg_kinds = [ARG_POS] * len(actuals)
2729 elif isinstance(unpacked_type, TypeVarTupleType):
2730 callee_arg_types = [orig_callee_arg_type]
2731 callee_arg_kinds = [ARG_STAR]
2732 else:
2733 assert isinstance(unpacked_type, Instance)
2734 assert unpacked_type.type.fullname == "builtins.tuple"
2735 callee_arg_types = [unpacked_type.args[0]] * len(actuals)
2736 callee_arg_kinds = [ARG_POS] * len(actuals)
2737 else:
2738 callee_arg_types = [orig_callee_arg_type] * len(actuals)
2739 callee_arg_kinds = [callee.arg_kinds[i]] * len(actuals)
2740
2741 assert len(actual_types) == len(actuals) == len(actual_kinds)
2742
2743 if len(callee_arg_types) != len(actual_types):
2744 if len(actual_types) > len(callee_arg_types):
2745 self.chk.msg.too_many_arguments(callee, context)
2746 else:
2747 self.chk.msg.too_few_arguments(callee, context, None)
2748 continue
2749
2750 assert len(callee_arg_types) == len(actual_types)
2751 assert len(callee_arg_types) == len(callee_arg_kinds)
2752 for actual, actual_type, actual_kind, callee_arg_type, callee_arg_kind in zip(
2753 actuals, actual_types, actual_kinds, callee_arg_types, callee_arg_kinds
2754 ):
2755 # Check that a *arg is valid as varargs.
2756 expanded_actual = mapper.expand_actual_type(
2757 actual_type,
2758 actual_kind,
2759 callee.arg_names[i],
2760 callee_arg_kind,
2761 allow_unpack=isinstance(callee_arg_type, UnpackType),
2762 )
2763 check_arg(
2764 expanded_actual,
2765 actual_type,
2766 actual_kind,
2767 callee_arg_type,
2768 actual + 1,
2769 i + 1,
2770 callee,
2771 object_type,
2772 args[actual],
2773 context,
2774 )
2775
2776 def check_arg(
2777 self,
2778 caller_type: Type,
2779 original_caller_type: Type,
2780 caller_kind: ArgKind,
2781 callee_type: Type,
2782 n: int,
2783 m: int,
2784 callee: CallableType,
2785 object_type: Type | None,
2786 context: Context,
2787 outer_context: Context,
2788 ) -> None:
2789 """Check the type of a single argument in a call."""
2790 caller_type = get_proper_type(caller_type)
2791 original_caller_type = get_proper_type(original_caller_type)
2792 callee_type = get_proper_type(callee_type)
2793
2794 if isinstance(caller_type, DeletedType):
2795 self.msg.deleted_as_rvalue(caller_type, context)
2796 # Only non-abstract non-protocol class can be given where Type[...] is expected...
2797 elif self.has_abstract_type_part(caller_type, callee_type):
2798 self.msg.concrete_only_call(callee_type, context)
2799 elif not is_subtype(caller_type, callee_type, options=self.chk.options):
2800 error = self.msg.incompatible_argument(
2801 n,
2802 m,
2803 callee,
2804 original_caller_type,
2805 caller_kind,
2806 object_type=object_type,
2807 context=context,
2808 outer_context=outer_context,
2809 )
2810 if not caller_kind.is_star():
2811 # For *args and **kwargs this note would be incorrect - we're comparing
2812 # iterable/mapping type with union of relevant arg types.
2813 self.msg.incompatible_argument_note(
2814 original_caller_type, callee_type, context, parent_error=error
2815 )
2816 if not self.msg.prefer_simple_messages():
2817 self.chk.check_possible_missing_await(
2818 caller_type, callee_type, context, error.code
2819 )
2820
2821 def check_overload_call(
2822 self,
2823 callee: Overloaded,
2824 args: list[Expression],
2825 arg_kinds: list[ArgKind],
2826 arg_names: Sequence[str | None] | None,
2827 callable_name: str | None,
2828 object_type: Type | None,
2829 context: Context,
2830 ) -> tuple[Type, Type]:
2831 """Checks a call to an overloaded function."""
2832 # Normalize unpacked kwargs before checking the call.
2833 callee = callee.with_unpacked_kwargs()
2834 arg_types = self.infer_arg_types_in_empty_context(args)
2835 # Step 1: Filter call targets to remove ones where the argument counts don't match
2836 plausible_targets = self.plausible_overload_call_targets(
2837 arg_types, arg_kinds, arg_names, callee
2838 )
2839
2840 # Step 2: If the arguments contain a union, we try performing union math first,
2841 # instead of picking the first matching overload.
2842 # This is because picking the first overload often ends up being too greedy:
2843 # for example, when we have a fallback alternative that accepts an unrestricted
2844 # typevar. See https://github.com/python/mypy/issues/4063 for related discussion.
2845 erased_targets: list[CallableType] | None = None
2846 inferred_types: list[Type] | None = None
2847 unioned_result: tuple[Type, Type] | None = None
2848
2849 # Determine whether we need to encourage union math. This should be generally safe,
2850 # as union math infers better results in the vast majority of cases, but it is very
2851 # computationally intensive.
2852 none_type_var_overlap = self.possible_none_type_var_overlap(arg_types, plausible_targets)
2853 union_interrupted = False # did we try all union combinations?
2854 if any(self.real_union(arg) for arg in arg_types):
2855 try:
2856 with self.msg.filter_errors():
2857 unioned_return = self.union_overload_result(
2858 plausible_targets,
2859 args,
2860 arg_types,
2861 arg_kinds,
2862 arg_names,
2863 callable_name,
2864 object_type,
2865 none_type_var_overlap,
2866 context,
2867 )
2868 except TooManyUnions:
2869 union_interrupted = True
2870 else:
2871 # Record if we succeeded. Next we need to see if maybe normal procedure
2872 # gives a narrower type.
2873 if unioned_return:
2874 returns = [u[0] for u in unioned_return]
2875 inferred_types = [u[1] for u in unioned_return]
2876 # Note that we use `combine_function_signatures` instead of just returning
2877 # a union of inferred callables because for example a call
2878 # Union[int -> int, str -> str](Union[int, str]) is invalid and
2879 # we don't want to introduce internal inconsistencies.
2880 unioned_result = (
2881 make_simplified_union(returns, context.line, context.column),
2882 self.combine_function_signatures(get_proper_types(inferred_types)),
2883 )
2884
2885 # Step 3: We try checking each branch one-by-one.
2886 inferred_result = self.infer_overload_return_type(
2887 plausible_targets,
2888 args,
2889 arg_types,
2890 arg_kinds,
2891 arg_names,
2892 callable_name,
2893 object_type,
2894 context,
2895 )
2896 # If any of checks succeed, perform deprecation tests and stop early.
2897 if inferred_result is not None and unioned_result is not None:
2898 # Both unioned and direct checks succeeded, choose the more precise type.
2899 if (
2900 is_subtype(inferred_result[0], unioned_result[0])
2901 and not isinstance(get_proper_type(inferred_result[0]), AnyType)
2902 and not none_type_var_overlap
2903 ):
2904 unioned_result = None
2905 else:
2906 inferred_result = None
2907 if unioned_result is not None:
2908 if inferred_types is not None:
2909 for inferred_type in inferred_types:
2910 if isinstance(c := get_proper_type(inferred_type), CallableType):
2911 self.chk.warn_deprecated(c.definition, context)
2912 return unioned_result
2913 if inferred_result is not None:
2914 if isinstance(c := get_proper_type(inferred_result[1]), CallableType):
2915 self.chk.warn_deprecated(c.definition, context)
2916 return inferred_result
2917
2918 # Step 4: Failure. At this point, we know there is no match. We fall back to trying
2919 # to find a somewhat plausible overload target using the erased types
2920 # so we can produce a nice error message.
2921 #
2922 # For example, suppose the user passes a value of type 'List[str]' into an
2923 # overload with signatures f(x: int) -> int and f(x: List[int]) -> List[int].
2924 #
2925 # Neither alternative matches, but we can guess the user probably wants the
2926 # second one.
2927 erased_targets = self.overload_erased_call_targets(
2928 plausible_targets, arg_types, arg_kinds, arg_names, args, context
2929 )
2930
2931 # Step 5: We try and infer a second-best alternative if possible. If not, fall back
2932 # to using 'Any'.
2933 if len(erased_targets) > 0:
2934 # Pick the first plausible erased target as the fallback
2935 # TODO: Adjust the error message here to make it clear there was no match.
2936 # In order to do this, we need to find a clean way of associating
2937 # a note with whatever error message 'self.check_call' will generate.
2938 # In particular, the note's line and column numbers need to be the same
2939 # as the error's.
2940 target: Type = erased_targets[0]
2941 else:
2942 # There was no plausible match: give up
2943 target = AnyType(TypeOfAny.from_error)
2944 if not is_operator_method(callable_name):
2945 code = None
2946 else:
2947 code = codes.OPERATOR
2948 self.msg.no_variant_matches_arguments(
2949 callee, arg_types, context, arg_names=arg_names, arg_kinds=arg_kinds, code=code
2950 )
2951
2952 result = self.check_call(
2953 target,
2954 args,
2955 arg_kinds,
2956 context,
2957 arg_names,
2958 callable_name=callable_name,
2959 object_type=object_type,
2960 )
2961 # Do not show the extra error if the union math was forced.
2962 if union_interrupted and not none_type_var_overlap:
2963 self.chk.fail(message_registry.TOO_MANY_UNION_COMBINATIONS, context)
2964 return result
2965
2966 def plausible_overload_call_targets(
2967 self,
2968 arg_types: list[Type],
2969 arg_kinds: list[ArgKind],
2970 arg_names: Sequence[str | None] | None,
2971 overload: Overloaded,
2972 ) -> list[CallableType]:
2973 """Returns all overload call targets that having matching argument counts.
2974
2975 If the given args contains a star-arg (*arg or **kwarg argument, except for
2976 ParamSpec), this method will ensure all star-arg overloads appear at the start
2977 of the list, instead of their usual location.
2978
2979 The only exception is if the starred argument is something like a Tuple or a
2980 NamedTuple, which has a definitive "shape". If so, we don't move the corresponding
2981 alternative to the front since we can infer a more precise match using the original
2982 order."""
2983
2984 def has_shape(typ: Type) -> bool:
2985 typ = get_proper_type(typ)
2986 return isinstance(typ, (TupleType, TypedDictType)) or (
2987 isinstance(typ, Instance) and typ.type.is_named_tuple
2988 )
2989
2990 matches: list[CallableType] = []
2991 star_matches: list[CallableType] = []
2992
2993 args_have_var_arg = False
2994 args_have_kw_arg = False
2995 for kind, typ in zip(arg_kinds, arg_types):
2996 if kind == ARG_STAR and not has_shape(typ):
2997 args_have_var_arg = True
2998 if kind == ARG_STAR2 and not has_shape(typ):
2999 args_have_kw_arg = True
3000
3001 for typ in overload.items:
3002 formal_to_actual = map_actuals_to_formals(
3003 arg_kinds, arg_names, typ.arg_kinds, typ.arg_names, lambda i: arg_types[i]
3004 )
3005 with self.msg.filter_errors():
3006 if typ.param_spec() is not None:
3007 # ParamSpec can be expanded in a lot of different ways. We may try
3008 # to expand it here instead, but picking an impossible overload
3009 # is safe: it will be filtered out later.
3010 # Unlike other var-args signatures, ParamSpec produces essentially
3011 # a fixed signature, so there's no need to push them to the top.
3012 matches.append(typ)
3013 elif self.check_argument_count(
3014 typ, arg_types, arg_kinds, arg_names, formal_to_actual, None
3015 ):
3016 if args_have_var_arg and typ.is_var_arg:
3017 star_matches.append(typ)
3018 elif args_have_kw_arg and typ.is_kw_arg:
3019 star_matches.append(typ)
3020 else:
3021 matches.append(typ)
3022
3023 return star_matches + matches
3024
3025 def infer_overload_return_type(
3026 self,
3027 plausible_targets: list[CallableType],
3028 args: list[Expression],
3029 arg_types: list[Type],
3030 arg_kinds: list[ArgKind],
3031 arg_names: Sequence[str | None] | None,
3032 callable_name: str | None,
3033 object_type: Type | None,
3034 context: Context,
3035 ) -> tuple[Type, Type] | None:
3036 """Attempts to find the first matching callable from the given list.
3037
3038 If a match is found, returns a tuple containing the result type and the inferred
3039 callee type. (This tuple is meant to be eventually returned by check_call.)
3040 If multiple targets match due to ambiguous Any parameters, returns (AnyType, AnyType).
3041 If no targets match, returns None.
3042
3043 Assumes all of the given targets have argument counts compatible with the caller.
3044 """
3045
3046 matches: list[CallableType] = []
3047 return_types: list[Type] = []
3048 inferred_types: list[Type] = []
3049 args_contain_any = any(map(has_any_type, arg_types))
3050 type_maps: list[dict[Expression, Type]] = []
3051
3052 for typ in plausible_targets:
3053 assert self.msg is self.chk.msg
3054 with self.msg.filter_errors(filter_revealed_type=True) as w:
3055 with self.chk.local_type_map as m:
3056 ret_type, infer_type = self.check_call(
3057 callee=typ,
3058 args=args,
3059 arg_kinds=arg_kinds,
3060 arg_names=arg_names,
3061 context=context,
3062 callable_name=callable_name,
3063 object_type=object_type,
3064 )
3065 is_match = not w.has_new_errors()
3066 if is_match:
3067 # Return early if possible; otherwise record info, so we can
3068 # check for ambiguity due to 'Any' below.
3069 if not args_contain_any:
3070 self.chk.store_types(m)
3071 return ret_type, infer_type
3072 p_infer_type = get_proper_type(infer_type)
3073 if isinstance(p_infer_type, CallableType):
3074 # Prefer inferred types if possible, this will avoid false triggers for
3075 # Any-ambiguity caused by arguments with Any passed to generic overloads.
3076 matches.append(p_infer_type)
3077 else:
3078 matches.append(typ)
3079 return_types.append(ret_type)
3080 inferred_types.append(infer_type)
3081 type_maps.append(m)
3082
3083 if not matches:
3084 return None
3085 elif any_causes_overload_ambiguity(matches, return_types, arg_types, arg_kinds, arg_names):
3086 # An argument of type or containing the type 'Any' caused ambiguity.
3087 # We try returning a precise type if we can. If not, we give up and just return 'Any'.
3088 if all_same_types(return_types):
3089 self.chk.store_types(type_maps[0])
3090 return return_types[0], inferred_types[0]
3091 elif all_same_types([erase_type(typ) for typ in return_types]):
3092 self.chk.store_types(type_maps[0])
3093 return erase_type(return_types[0]), erase_type(inferred_types[0])
3094 else:
3095 return self.check_call(
3096 callee=AnyType(TypeOfAny.special_form),
3097 args=args,
3098 arg_kinds=arg_kinds,
3099 arg_names=arg_names,
3100 context=context,
3101 callable_name=callable_name,
3102 object_type=object_type,
3103 )
3104 else:
3105 # Success! No ambiguity; return the first match.
3106 self.chk.store_types(type_maps[0])
3107 return return_types[0], inferred_types[0]
3108
3109 def overload_erased_call_targets(
3110 self,
3111 plausible_targets: list[CallableType],
3112 arg_types: list[Type],
3113 arg_kinds: list[ArgKind],
3114 arg_names: Sequence[str | None] | None,
3115 args: list[Expression],
3116 context: Context,
3117 ) -> list[CallableType]:
3118 """Returns a list of all targets that match the caller after erasing types.
3119
3120 Assumes all of the given targets have argument counts compatible with the caller.
3121 """
3122 matches: list[CallableType] = []
3123 for typ in plausible_targets:
3124 if self.erased_signature_similarity(
3125 arg_types, arg_kinds, arg_names, args, typ, context
3126 ):
3127 matches.append(typ)
3128 return matches
3129
3130 def possible_none_type_var_overlap(
3131 self, arg_types: list[Type], plausible_targets: list[CallableType]
3132 ) -> bool:
3133 """Heuristic to determine whether we need to try forcing union math.
3134
3135 This is needed to avoid greedy type variable match in situations like this:
3136 @overload
3137 def foo(x: None) -> None: ...
3138 @overload
3139 def foo(x: T) -> list[T]: ...
3140
3141 x: int | None
3142 foo(x)
3143 we want this call to infer list[int] | None, not list[int | None].
3144 """
3145 if not plausible_targets or not arg_types:
3146 return False
3147 has_optional_arg = False
3148 for arg_type in get_proper_types(arg_types):
3149 if not isinstance(arg_type, UnionType):
3150 continue
3151 for item in get_proper_types(arg_type.items):
3152 if isinstance(item, NoneType):
3153 has_optional_arg = True
3154 break
3155 if not has_optional_arg:
3156 return False
3157
3158 min_prefix = min(len(c.arg_types) for c in plausible_targets)
3159 for i in range(min_prefix):
3160 if any(
3161 isinstance(get_proper_type(c.arg_types[i]), NoneType) for c in plausible_targets
3162 ) and any(
3163 isinstance(get_proper_type(c.arg_types[i]), TypeVarType) for c in plausible_targets
3164 ):
3165 return True
3166 return False
3167
3168 def union_overload_result(
3169 self,
3170 plausible_targets: list[CallableType],
3171 args: list[Expression],
3172 arg_types: list[Type],
3173 arg_kinds: list[ArgKind],
3174 arg_names: Sequence[str | None] | None,
3175 callable_name: str | None,
3176 object_type: Type | None,
3177 none_type_var_overlap: bool,
3178 context: Context,
3179 level: int = 0,
3180 ) -> list[tuple[Type, Type]] | None:
3181 """Accepts a list of overload signatures and attempts to match calls by destructuring
3182 the first union.
3183
3184 Return a list of (<return type>, <inferred variant type>) if call succeeds for every
3185 item of the desctructured union. Returns None if there is no match.
3186 """
3187 # Step 1: If we are already too deep, then stop immediately. Otherwise mypy might
3188 # hang for long time because of a weird overload call. The caller will get
3189 # the exception and generate an appropriate note message, if needed.
3190 if level >= MAX_UNIONS:
3191 raise TooManyUnions
3192
3193 # Step 2: Find position of the first union in arguments. Return the normal inferred
3194 # type if no more unions left.
3195 for idx, typ in enumerate(arg_types):
3196 if self.real_union(typ):
3197 break
3198 else:
3199 # No unions in args, just fall back to normal inference
3200 with self.type_overrides_set(args, arg_types):
3201 res = self.infer_overload_return_type(
3202 plausible_targets,
3203 args,
3204 arg_types,
3205 arg_kinds,
3206 arg_names,
3207 callable_name,
3208 object_type,
3209 context,
3210 )
3211 if res is not None:
3212 return [res]
3213 return None
3214
3215 # Step 3: Try a direct match before splitting to avoid unnecessary union splits
3216 # and save performance.
3217 if not none_type_var_overlap:
3218 with self.type_overrides_set(args, arg_types):
3219 direct = self.infer_overload_return_type(
3220 plausible_targets,
3221 args,
3222 arg_types,
3223 arg_kinds,
3224 arg_names,
3225 callable_name,
3226 object_type,
3227 context,
3228 )
3229 if direct is not None and not isinstance(
3230 get_proper_type(direct[0]), (UnionType, AnyType)
3231 ):
3232 # We only return non-unions soon, to avoid greedy match.
3233 return [direct]
3234
3235 # Step 4: Split the first remaining union type in arguments into items and
3236 # try to match each item individually (recursive).
3237 first_union = get_proper_type(arg_types[idx])
3238 assert isinstance(first_union, UnionType)
3239 res_items = []
3240 for item in first_union.relevant_items():
3241 new_arg_types = arg_types.copy()
3242 new_arg_types[idx] = item
3243 sub_result = self.union_overload_result(
3244 plausible_targets,
3245 args,
3246 new_arg_types,
3247 arg_kinds,
3248 arg_names,
3249 callable_name,
3250 object_type,
3251 none_type_var_overlap,
3252 context,
3253 level + 1,
3254 )
3255 if sub_result is not None:
3256 res_items.extend(sub_result)
3257 else:
3258 # Some item doesn't match, return soon.
3259 return None
3260
3261 # Step 5: If splitting succeeded, then filter out duplicate items before returning.
3262 seen: set[tuple[Type, Type]] = set()
3263 result = []
3264 for pair in res_items:
3265 if pair not in seen:
3266 seen.add(pair)
3267 result.append(pair)
3268 return result
3269
3270 def real_union(self, typ: Type) -> bool:
3271 typ = get_proper_type(typ)
3272 return isinstance(typ, UnionType) and len(typ.relevant_items()) > 1
3273
3274 @contextmanager
3275 def type_overrides_set(
3276 self, exprs: Sequence[Expression], overrides: Sequence[Type]
3277 ) -> Iterator[None]:
3278 """Set _temporary_ type overrides for given expressions."""
3279 assert len(exprs) == len(overrides)
3280 for expr, typ in zip(exprs, overrides):
3281 self.type_overrides[expr] = typ
3282 try:
3283 yield
3284 finally:
3285 for expr in exprs:
3286 del self.type_overrides[expr]
3287
3288 def combine_function_signatures(self, types: list[ProperType]) -> AnyType | CallableType:
3289 """Accepts a list of function signatures and attempts to combine them together into a
3290 new CallableType consisting of the union of all of the given arguments and return types.
3291
3292 If there is at least one non-callable type, return Any (this can happen if there is
3293 an ambiguity because of Any in arguments).
3294 """
3295 assert types, "Trying to merge no callables"
3296 if not all(isinstance(c, CallableType) for c in types):
3297 return AnyType(TypeOfAny.special_form)
3298
3299 callables = cast("list[CallableType]", types)
3300 if len(callables) == 1:
3301 return callables[0]
3302
3303 # Note: we are assuming here that if a user uses some TypeVar 'T' in
3304 # two different functions, they meant for that TypeVar to mean the
3305 # same thing.
3306 #
3307 # This function will make sure that all instances of that TypeVar 'T'
3308 # refer to the same underlying TypeVarType objects to simplify the union-ing
3309 # logic below.
3310 #
3311 # (If the user did *not* mean for 'T' to be consistently bound to the
3312 # same type in their overloads, well, their code is probably too
3313 # confusing and ought to be re-written anyways.)
3314 callables, variables = merge_typevars_in_callables_by_name(callables)
3315
3316 new_args: list[list[Type]] = [[] for _ in callables[0].arg_types]
3317 new_kinds = list(callables[0].arg_kinds)
3318 new_returns: list[Type] = []
3319 too_complex = False
3320
3321 for target in callables:
3322 # We fall back to Callable[..., Union[<returns>]] if the functions do not have
3323 # the exact same signature. The only exception is if one arg is optional and
3324 # the other is positional: in that case, we continue unioning (and expect a
3325 # positional arg).
3326 # TODO: Enhance the merging logic to handle a wider variety of signatures.
3327 if len(new_kinds) != len(target.arg_kinds):
3328 too_complex = True
3329 break
3330 for i, (new_kind, target_kind) in enumerate(zip(new_kinds, target.arg_kinds)):
3331 if new_kind == target_kind:
3332 continue
3333 if new_kind.is_positional() and target_kind.is_positional():
3334 new_kinds[i] = ARG_POS
3335 else:
3336 too_complex = True
3337 break
3338 if too_complex:
3339 break
3340 for i, arg in enumerate(target.arg_types):
3341 new_args[i].append(arg)
3342 new_returns.append(target.ret_type)
3343
3344 union_return = make_simplified_union(new_returns)
3345 if too_complex:
3346 any = AnyType(TypeOfAny.special_form)
3347 return callables[0].copy_modified(
3348 arg_types=[any, any],
3349 arg_kinds=[ARG_STAR, ARG_STAR2],
3350 arg_names=[None, None],
3351 ret_type=union_return,
3352 variables=variables,
3353 implicit=True,
3354 )
3355
3356 return callables[0].copy_modified(
3357 arg_types=[make_simplified_union(args) for args in new_args],
3358 arg_kinds=new_kinds,
3359 ret_type=union_return,
3360 variables=variables,
3361 implicit=True,
3362 )
3363
3364 def erased_signature_similarity(
3365 self,
3366 arg_types: list[Type],
3367 arg_kinds: list[ArgKind],
3368 arg_names: Sequence[str | None] | None,
3369 args: list[Expression],
3370 callee: CallableType,
3371 context: Context,
3372 ) -> bool:
3373 """Determine whether arguments could match the signature at runtime, after
3374 erasing types."""
3375 formal_to_actual = map_actuals_to_formals(
3376 arg_kinds, arg_names, callee.arg_kinds, callee.arg_names, lambda i: arg_types[i]
3377 )
3378
3379 with self.msg.filter_errors():
3380 if not self.check_argument_count(
3381 callee, arg_types, arg_kinds, arg_names, formal_to_actual, None
3382 ):
3383 # Too few or many arguments -> no match.
3384 return False
3385
3386 def check_arg(
3387 caller_type: Type,
3388 original_ccaller_type: Type,
3389 caller_kind: ArgKind,
3390 callee_type: Type,
3391 n: int,
3392 m: int,
3393 callee: CallableType,
3394 object_type: Type | None,
3395 context: Context,
3396 outer_context: Context,
3397 ) -> None:
3398 if not arg_approximate_similarity(caller_type, callee_type):
3399 # No match -- exit early since none of the remaining work can change
3400 # the result.
3401 raise Finished
3402
3403 try:
3404 self.check_argument_types(
3405 arg_types,
3406 arg_kinds,
3407 args,
3408 callee,
3409 formal_to_actual,
3410 context=context,
3411 check_arg=check_arg,
3412 )
3413 return True
3414 except Finished:
3415 return False
3416
3417 def apply_generic_arguments(
3418 self,
3419 callable: CallableType,
3420 types: Sequence[Type | None],
3421 context: Context,
3422 skip_unsatisfied: bool = False,
3423 ) -> CallableType:
3424 """Simple wrapper around mypy.applytype.apply_generic_arguments."""
3425 return applytype.apply_generic_arguments(
3426 callable,
3427 types,
3428 self.msg.incompatible_typevar_value,
3429 context,
3430 skip_unsatisfied=skip_unsatisfied,
3431 )
3432
3433 def check_any_type_call(
3434 self, args: list[Expression], arg_kinds: list[ArgKind], callee: Type, context: Context
3435 ) -> tuple[Type, Type]:
3436 arg_types = self.infer_arg_types_in_empty_context(args)
3437 self.check_var_args_kwargs(arg_types, arg_kinds, context)
3438
3439 callee = get_proper_type(callee)
3440 if isinstance(callee, AnyType):
3441 return (
3442 AnyType(TypeOfAny.from_another_any, source_any=callee),
3443 AnyType(TypeOfAny.from_another_any, source_any=callee),
3444 )
3445 else:
3446 return AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)
3447
3448 def check_union_call(
3449 self,
3450 callee: UnionType,
3451 args: list[Expression],
3452 arg_kinds: list[ArgKind],
3453 arg_names: Sequence[str | None] | None,
3454 context: Context,
3455 ) -> tuple[Type, Type]:
3456 with self.msg.disable_type_names():
3457 results = [
3458 self.check_call(subtype, args, arg_kinds, context, arg_names)
3459 for subtype in callee.relevant_items()
3460 ]
3461
3462 return (make_simplified_union([res[0] for res in results]), callee)
3463
3464 def visit_member_expr(self, e: MemberExpr, is_lvalue: bool = False) -> Type:
3465 """Visit member expression (of form e.id)."""
3466 result = self.analyze_ordinary_member_access(e, is_lvalue)
3467 narrowed = self.narrow_type_from_binder(e, result)
3468 self.chk.warn_deprecated(e.node, e)
3469 return narrowed
3470
3471 def analyze_ordinary_member_access(
3472 self, e: MemberExpr, is_lvalue: bool, rvalue: Expression | None = None
3473 ) -> Type:
3474 """Analyse member expression or member lvalue.
3475
3476 An rvalue can be provided optionally to infer better setter type when is_lvalue is True.
3477 """
3478 if e.kind is not None:
3479 # This is a reference to a module attribute.
3480 return self.analyze_ref_expr(e)
3481 else:
3482 # This is a reference to a non-module attribute.
3483 original_type = self.accept(e.expr, is_callee=self.is_callee)
3484 base = e.expr
3485 module_symbol_table = None
3486
3487 if isinstance(base, RefExpr) and isinstance(base.node, MypyFile):
3488 module_symbol_table = base.node.names
3489 if isinstance(base, RefExpr) and isinstance(base.node, Var):
3490 # This is needed to special case self-types, so we don't need to track
3491 # these flags separately in checkmember.py.
3492 is_self = base.node.is_self or base.node.is_cls
3493 else:
3494 is_self = False
3495
3496 member_type = analyze_member_access(
3497 e.name,
3498 original_type,
3499 e,
3500 is_lvalue=is_lvalue,
3501 is_super=False,
3502 is_operator=False,
3503 original_type=original_type,
3504 chk=self.chk,
3505 in_literal_context=self.is_literal_context(),
3506 module_symbol_table=module_symbol_table,
3507 is_self=is_self,
3508 rvalue=rvalue,
3509 )
3510
3511 return member_type
3512
3513 def analyze_external_member_access(
3514 self, member: str, base_type: Type, context: Context
3515 ) -> Type:
3516 """Analyse member access that is external, i.e. it cannot
3517 refer to private definitions. Return the result type.
3518 """
3519 # TODO remove; no private definitions in mypy
3520 return analyze_member_access(
3521 member,
3522 base_type,
3523 context,
3524 is_lvalue=False,
3525 is_super=False,
3526 is_operator=False,
3527 original_type=base_type,
3528 chk=self.chk,
3529 in_literal_context=self.is_literal_context(),
3530 )
3531
3532 def is_literal_context(self) -> bool:
3533 return is_literal_type_like(self.type_context[-1])
3534
3535 def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type:
3536 """Analyzes the given literal expression and determines if we should be
3537 inferring an Instance type, a Literal[...] type, or an Instance that
3538 remembers the original literal. We...
3539
3540 1. ...Infer a normal Instance in most circumstances.
3541
3542 2. ...Infer a Literal[...] if we're in a literal context. For example, if we
3543 were analyzing the "3" in "foo(3)" where "foo" has a signature of
3544 "def foo(Literal[3]) -> None", we'd want to infer that the "3" has a
3545 type of Literal[3] instead of Instance.
3546
3547 3. ...Infer an Instance that remembers the original Literal if we're declaring
3548 a Final variable with an inferred type -- for example, "bar" in "bar: Final = 3"
3549 would be assigned an Instance that remembers it originated from a '3'. See
3550 the comments in Instance's constructor for more details.
3551 """
3552 typ = self.named_type(fallback_name)
3553 if self.is_literal_context():
3554 return LiteralType(value=value, fallback=typ)
3555 else:
3556 if value is True:
3557 if self._literal_true is None:
3558 self._literal_true = typ.copy_modified(
3559 last_known_value=LiteralType(value=value, fallback=typ)
3560 )
3561 return self._literal_true
3562 if value is False:
3563 if self._literal_false is None:
3564 self._literal_false = typ.copy_modified(
3565 last_known_value=LiteralType(value=value, fallback=typ)
3566 )
3567 return self._literal_false
3568 return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ))
3569
3570 def concat_tuples(self, left: TupleType, right: TupleType) -> TupleType:
3571 """Concatenate two fixed length tuples."""
3572 assert not (find_unpack_in_list(left.items) and find_unpack_in_list(right.items))
3573 return TupleType(
3574 items=left.items + right.items, fallback=self.named_type("builtins.tuple")
3575 )
3576
3577 def visit_int_expr(self, e: IntExpr) -> Type:
3578 """Type check an integer literal (trivial)."""
3579 return self.infer_literal_expr_type(e.value, "builtins.int")
3580
3581 def visit_str_expr(self, e: StrExpr) -> Type:
3582 """Type check a string literal (trivial)."""
3583 return self.infer_literal_expr_type(e.value, "builtins.str")
3584
3585 def visit_bytes_expr(self, e: BytesExpr) -> Type:
3586 """Type check a bytes literal (trivial)."""
3587 return self.infer_literal_expr_type(e.value, "builtins.bytes")
3588
3589 def visit_float_expr(self, e: FloatExpr) -> Type:
3590 """Type check a float literal (trivial)."""
3591 return self.named_type("builtins.float")
3592
3593 def visit_complex_expr(self, e: ComplexExpr) -> Type:
3594 """Type check a complex literal."""
3595 return self.named_type("builtins.complex")
3596
3597 def visit_ellipsis(self, e: EllipsisExpr) -> Type:
3598 """Type check '...'."""
3599 return self.named_type("builtins.ellipsis")
3600
3601 def visit_op_expr(self, e: OpExpr) -> Type:
3602 """Type check a binary operator expression."""
3603 if e.analyzed:
3604 # It's actually a type expression X | Y.
3605 return self.accept(e.analyzed)
3606 if e.op == "and" or e.op == "or":
3607 return self.check_boolean_op(e)
3608 if e.op == "*" and isinstance(e.left, ListExpr):
3609 # Expressions of form [...] * e get special type inference.
3610 return self.check_list_multiply(e)
3611 if e.op == "%":
3612 if isinstance(e.left, BytesExpr):
3613 return self.strfrm_checker.check_str_interpolation(e.left, e.right)
3614 if isinstance(e.left, StrExpr):
3615 return self.strfrm_checker.check_str_interpolation(e.left, e.right)
3616 left_type = self.accept(e.left)
3617
3618 proper_left_type = get_proper_type(left_type)
3619 if isinstance(proper_left_type, TupleType) and e.op == "+":
3620 left_add_method = proper_left_type.partial_fallback.type.get("__add__")
3621 if left_add_method and left_add_method.fullname == "builtins.tuple.__add__":
3622 proper_right_type = get_proper_type(self.accept(e.right))
3623 if isinstance(proper_right_type, TupleType):
3624 right_radd_method = proper_right_type.partial_fallback.type.get("__radd__")
3625 if right_radd_method is None:
3626 # One cannot have two variadic items in the same tuple.
3627 if (
3628 find_unpack_in_list(proper_left_type.items) is None
3629 or find_unpack_in_list(proper_right_type.items) is None
3630 ):
3631 return self.concat_tuples(proper_left_type, proper_right_type)
3632 elif (
3633 PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature
3634 and isinstance(proper_right_type, Instance)
3635 and self.chk.type_is_iterable(proper_right_type)
3636 ):
3637 # Handle tuple[X, Y] + tuple[Z, ...] = tuple[X, Y, *tuple[Z, ...]].
3638 right_radd_method = proper_right_type.type.get("__radd__")
3639 if (
3640 right_radd_method is None
3641 and proper_left_type.partial_fallback.type.fullname == "builtins.tuple"
3642 and find_unpack_in_list(proper_left_type.items) is None
3643 ):
3644 item_type = self.chk.iterable_item_type(proper_right_type, e)
3645 mapped = self.chk.named_generic_type("builtins.tuple", [item_type])
3646 return proper_left_type.copy_modified(
3647 items=proper_left_type.items + [UnpackType(mapped)]
3648 )
3649
3650 use_reverse: UseReverse = USE_REVERSE_DEFAULT
3651 if e.op == "|":
3652 if is_named_instance(proper_left_type, "builtins.dict"):
3653 # This is a special case for `dict | TypedDict`.
3654 # 1. Find `dict | TypedDict` case
3655 # 2. Switch `dict.__or__` to `TypedDict.__ror__` (the same from both runtime and typing perspective)
3656 proper_right_type = get_proper_type(self.accept(e.right))
3657 if isinstance(proper_right_type, TypedDictType):
3658 use_reverse = USE_REVERSE_ALWAYS
3659 if isinstance(proper_left_type, TypedDictType):
3660 # This is the reverse case: `TypedDict | dict`,
3661 # simply do not allow the reverse checking:
3662 # do not call `__dict__.__ror__`.
3663 proper_right_type = get_proper_type(self.accept(e.right))
3664 if is_named_instance(proper_right_type, "builtins.dict"):
3665 use_reverse = USE_REVERSE_NEVER
3666
3667 if PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature:
3668 # Handle tuple[X, ...] + tuple[Y, Z] = tuple[*tuple[X, ...], Y, Z].
3669 if (
3670 e.op == "+"
3671 and isinstance(proper_left_type, Instance)
3672 and proper_left_type.type.fullname == "builtins.tuple"
3673 ):
3674 proper_right_type = get_proper_type(self.accept(e.right))
3675 if (
3676 isinstance(proper_right_type, TupleType)
3677 and proper_right_type.partial_fallback.type.fullname == "builtins.tuple"
3678 and find_unpack_in_list(proper_right_type.items) is None
3679 ):
3680 return proper_right_type.copy_modified(
3681 items=[UnpackType(proper_left_type)] + proper_right_type.items
3682 )
3683
3684 if e.op in operators.op_methods:
3685 method = operators.op_methods[e.op]
3686 if use_reverse is UseReverse.DEFAULT or use_reverse is UseReverse.NEVER:
3687 result, method_type = self.check_op(
3688 method,
3689 base_type=left_type,
3690 arg=e.right,
3691 context=e,
3692 allow_reverse=use_reverse is UseReverse.DEFAULT,
3693 )
3694 elif use_reverse is UseReverse.ALWAYS:
3695 result, method_type = self.check_op(
3696 # The reverse operator here gives better error messages:
3697 operators.reverse_op_methods[method],
3698 base_type=self.accept(e.right),
3699 arg=e.left,
3700 context=e,
3701 allow_reverse=False,
3702 )
3703 else:
3704 assert_never(use_reverse)
3705 e.method_type = method_type
3706 return result
3707 else:
3708 raise RuntimeError(f"Unknown operator {e.op}")
3709
3710 def visit_comparison_expr(self, e: ComparisonExpr) -> Type:
3711 """Type check a comparison expression.
3712
3713 Comparison expressions are type checked consecutive-pair-wise
3714 That is, 'a < b > c == d' is check as 'a < b and b > c and c == d'
3715 """
3716 result: Type | None = None
3717 sub_result: Type
3718
3719 # Check each consecutive operand pair and their operator
3720 for left, right, operator in zip(e.operands, e.operands[1:], e.operators):
3721 left_type = self.accept(left)
3722
3723 if operator == "in" or operator == "not in":
3724 # This case covers both iterables and containers, which have different meanings.
3725 # For a container, the in operator calls the __contains__ method.
3726 # For an iterable, the in operator iterates over the iterable, and compares each item one-by-one.
3727 # We allow `in` for a union of containers and iterables as long as at least one of them matches the
3728 # type of the left operand, as the operation will simply return False if the union's container/iterator
3729 # type doesn't match the left operand.
3730
3731 # If the right operand has partial type, look it up without triggering
3732 # a "Need type annotation ..." message, as it would be noise.
3733 right_type = self.find_partial_type_ref_fast_path(right)
3734 if right_type is None:
3735 right_type = self.accept(right) # Validate the right operand
3736
3737 right_type = get_proper_type(right_type)
3738 item_types: Sequence[Type] = [right_type]
3739 if isinstance(right_type, UnionType):
3740 item_types = list(right_type.relevant_items())
3741
3742 sub_result = self.bool_type()
3743
3744 container_types: list[Type] = []
3745 iterable_types: list[Type] = []
3746 failed_out = False
3747 encountered_partial_type = False
3748
3749 for item_type in item_types:
3750 # Keep track of whether we get type check errors (these won't be reported, they
3751 # are just to verify whether something is valid typing wise).
3752 with self.msg.filter_errors(save_filtered_errors=True) as container_errors:
3753 _, method_type = self.check_method_call_by_name(
3754 method="__contains__",
3755 base_type=item_type,
3756 args=[left],
3757 arg_kinds=[ARG_POS],
3758 context=e,
3759 original_type=right_type,
3760 )
3761 # Container item type for strict type overlap checks. Note: we need to only
3762 # check for nominal type, because a usual "Unsupported operands for in"
3763 # will be reported for types incompatible with __contains__().
3764 # See testCustomContainsCheckStrictEquality for an example.
3765 cont_type = self.chk.analyze_container_item_type(item_type)
3766
3767 if isinstance(item_type, PartialType):
3768 # We don't really know if this is an error or not, so just shut up.
3769 encountered_partial_type = True
3770 pass
3771 elif (
3772 container_errors.has_new_errors()
3773 and
3774 # is_valid_var_arg is True for any Iterable
3775 self.is_valid_var_arg(item_type)
3776 ):
3777 # it's not a container, but it is an iterable
3778 with self.msg.filter_errors(save_filtered_errors=True) as iterable_errors:
3779 _, itertype = self.chk.analyze_iterable_item_type_without_expression(
3780 item_type, e
3781 )
3782 if iterable_errors.has_new_errors():
3783 self.msg.add_errors(iterable_errors.filtered_errors())
3784 failed_out = True
3785 else:
3786 method_type = CallableType(
3787 [left_type],
3788 [nodes.ARG_POS],
3789 [None],
3790 self.bool_type(),
3791 self.named_type("builtins.function"),
3792 )
3793 e.method_types.append(method_type)
3794 iterable_types.append(itertype)
3795 elif not container_errors.has_new_errors() and cont_type:
3796 container_types.append(cont_type)
3797 e.method_types.append(method_type)
3798 else:
3799 self.msg.add_errors(container_errors.filtered_errors())
3800 failed_out = True
3801
3802 if not encountered_partial_type and not failed_out:
3803 iterable_type = UnionType.make_union(iterable_types)
3804 if not is_subtype(left_type, iterable_type):
3805 if not container_types:
3806 self.msg.unsupported_operand_types("in", left_type, right_type, e)
3807 else:
3808 container_type = UnionType.make_union(container_types)
3809 if not self.chk.can_skip_diagnostics and self.dangerous_comparison(
3810 left_type,
3811 container_type,
3812 original_container=right_type,
3813 prefer_literal=False,
3814 ):
3815 self.msg.dangerous_comparison(
3816 left_type, container_type, "container", e
3817 )
3818
3819 elif operator in operators.op_methods:
3820 method = operators.op_methods[operator]
3821
3822 with ErrorWatcher(self.msg.errors) as w:
3823 sub_result, method_type = self.check_op(
3824 method, left_type, right, e, allow_reverse=True
3825 )
3826 e.method_types.append(method_type)
3827
3828 # Only show dangerous overlap if there are no other errors. See
3829 # testCustomEqCheckStrictEquality for an example.
3830 if not w.has_new_errors() and operator in ("==", "!="):
3831 right_type = self.accept(right)
3832 if not self.chk.can_skip_diagnostics and self.dangerous_comparison(
3833 left_type, right_type
3834 ):
3835 # Show the most specific literal types possible
3836 left_type = try_getting_literal(left_type)
3837 right_type = try_getting_literal(right_type)
3838 self.msg.dangerous_comparison(left_type, right_type, "equality", e)
3839
3840 elif operator == "is" or operator == "is not":
3841 right_type = self.accept(right) # validate the right operand
3842 sub_result = self.bool_type()
3843 if (
3844 not self.chk.can_skip_diagnostics
3845 and self.dangerous_comparison(left_type, right_type, identity_check=True)
3846 # Allow dangerous identity comparisons with objects explicitly typed as Any
3847 and not (
3848 isinstance(left, NameExpr)
3849 and isinstance(left.node, Var)
3850 and not left.node.is_inferred
3851 and isinstance(get_proper_type(left.node.type), AnyType)
3852 )
3853 and not (
3854 isinstance(right, NameExpr)
3855 and isinstance(right.node, Var)
3856 and not right.node.is_inferred
3857 and isinstance(get_proper_type(right.node.type), AnyType)
3858 )
3859 ):
3860 # Show the most specific literal types possible
3861 left_type = try_getting_literal(left_type)
3862 right_type = try_getting_literal(right_type)
3863 self.msg.dangerous_comparison(left_type, right_type, "identity", e)
3864 e.method_types.append(None)
3865 else:
3866 raise RuntimeError(f"Unknown comparison operator {operator}")
3867
3868 # Determine type of boolean-and of result and sub_result
3869 if result is None:
3870 result = sub_result
3871 else:
3872 result = join.join_types(result, sub_result)
3873
3874 assert result is not None
3875 return result
3876
3877 def find_partial_type_ref_fast_path(self, expr: Expression) -> Type | None:
3878 """If expression has a partial generic type, return it without additional checks.
3879
3880 In particular, this does not generate an error about a missing annotation.
3881
3882 Otherwise, return None.
3883 """
3884 if not isinstance(expr, RefExpr):
3885 return None
3886 if isinstance(expr.node, Var):
3887 result = self.analyze_var_ref(expr.node, expr)
3888 if isinstance(result, PartialType) and result.type is not None:
3889 self.chk.store_type(expr, fixup_partial_type(result))
3890 return result
3891 return None
3892
3893 def dangerous_comparison(
3894 self,
3895 left: Type,
3896 right: Type,
3897 *,
3898 original_container: Type | None = None,
3899 seen_types: set[tuple[Type, Type]] | None = None,
3900 prefer_literal: bool = True,
3901 identity_check: bool = False,
3902 ) -> bool:
3903 """Check for dangerous non-overlapping comparisons like 42 == 'no'.
3904
3905 The original_container is the original container type for 'in' checks
3906 (and None for equality checks).
3907
3908 Rules:
3909 * X and None are overlapping even in strict-optional mode. This is to allow
3910 'assert x is not None' for x defined as 'x = None # type: str' in class body
3911 (otherwise mypy itself would have couple dozen errors because of this).
3912 * Optional[X] and Optional[Y] are non-overlapping if X and Y are
3913 non-overlapping, although technically None is overlap, it is most
3914 likely an error.
3915 * Any overlaps with everything, i.e. always safe.
3916 * Special case: b'abc' in b'cde' is safe.
3917 """
3918 if not self.chk.options.strict_equality:
3919 return False
3920
3921 if seen_types is None:
3922 seen_types = set()
3923 if (left, right) in seen_types:
3924 return False
3925 seen_types.add((left, right))
3926
3927 left, right = get_proper_types((left, right))
3928
3929 # We suppress the error for equality and container checks if there is a custom __eq__()
3930 # method on either side. User defined (or even standard library) classes can define this
3931 # to return True for comparisons between non-overlapping types.
3932 if (
3933 custom_special_method(left, "__eq__") or custom_special_method(right, "__eq__")
3934 ) and not identity_check:
3935 return False
3936
3937 if prefer_literal:
3938 # Also flag non-overlapping literals in situations like:
3939 # x: Literal['a', 'b']
3940 # if x == 'c':
3941 # ...
3942 left = try_getting_literal(left)
3943 right = try_getting_literal(right)
3944
3945 if self.chk.binder.is_unreachable_warning_suppressed():
3946 # We are inside a function that contains type variables with value restrictions in
3947 # its signature. In this case we just suppress all strict-equality checks to avoid
3948 # false positives for code like:
3949 #
3950 # T = TypeVar('T', str, int)
3951 # def f(x: T) -> T:
3952 # if x == 0:
3953 # ...
3954 # return x
3955 #
3956 # TODO: find a way of disabling the check only for types resulted from the expansion.
3957 return False
3958 if self.chk.options.strict_equality_for_none:
3959 if isinstance(left, NoneType) and isinstance(right, NoneType):
3960 return False
3961 elif isinstance(left, NoneType) or isinstance(right, NoneType):
3962 return False
3963 if isinstance(left, UnionType) and isinstance(right, UnionType):
3964 left = remove_optional(left)
3965 right = remove_optional(right)
3966 left, right = get_proper_types((left, right))
3967 if (
3968 original_container
3969 and has_bytes_component(original_container)
3970 and has_bytes_component(left)
3971 ):
3972 # We need to special case bytes and bytearray, because 97 in b'abc', b'a' in b'abc',
3973 # b'a' in bytearray(b'abc') etc. all return True (and we want to show the error only
3974 # if the check can _never_ be True).
3975 return False
3976 if isinstance(left, Instance) and isinstance(right, Instance):
3977 # Special case some builtin implementations of AbstractSet.
3978 left_name = left.type.fullname
3979 right_name = right.type.fullname
3980 if (
3981 left_name in OVERLAPPING_TYPES_ALLOWLIST
3982 and right_name in OVERLAPPING_TYPES_ALLOWLIST
3983 ):
3984 abstract_set = self.chk.lookup_typeinfo("typing.AbstractSet")
3985 left = map_instance_to_supertype(left, abstract_set)
3986 right = map_instance_to_supertype(right, abstract_set)
3987 return self.dangerous_comparison(
3988 left.args[0], right.args[0], seen_types=seen_types
3989 )
3990 elif left.type.has_base("typing.Mapping") and right.type.has_base("typing.Mapping"):
3991 # Similar to above: Mapping ignores the classes, it just compares items.
3992 abstract_map = self.chk.lookup_typeinfo("typing.Mapping")
3993 left = map_instance_to_supertype(left, abstract_map)
3994 right = map_instance_to_supertype(right, abstract_map)
3995 return self.dangerous_comparison(
3996 left.args[0], right.args[0], seen_types=seen_types
3997 ) or self.dangerous_comparison(left.args[1], right.args[1], seen_types=seen_types)
3998 elif left_name in ("builtins.list", "builtins.tuple") and right_name == left_name:
3999 return self.dangerous_comparison(
4000 left.args[0], right.args[0], seen_types=seen_types
4001 )
4002 elif left_name in OVERLAPPING_BYTES_ALLOWLIST and right_name in (
4003 OVERLAPPING_BYTES_ALLOWLIST
4004 ):
4005 return False
4006 if isinstance(left, LiteralType) and isinstance(right, LiteralType):
4007 if isinstance(left.value, bool) and isinstance(right.value, bool):
4008 # Comparing different booleans is not dangerous.
4009 return False
4010 if isinstance(left, LiteralType) and isinstance(right, Instance):
4011 # bytes/bytearray comparisons are supported
4012 if left.fallback.type.fullname == "builtins.bytes" and right.type.has_base(
4013 "builtins.bytearray"
4014 ):
4015 return False
4016 if isinstance(right, LiteralType) and isinstance(left, Instance):
4017 # bytes/bytearray comparisons are supported
4018 if right.fallback.type.fullname == "builtins.bytes" and left.type.has_base(
4019 "builtins.bytearray"
4020 ):
4021 return False
4022 return not is_overlapping_types(left, right, ignore_promotions=False)
4023
4024 def check_method_call_by_name(
4025 self,
4026 method: str,
4027 base_type: Type,
4028 args: list[Expression],
4029 arg_kinds: list[ArgKind],
4030 context: Context,
4031 original_type: Type | None = None,
4032 self_type: Type | None = None,
4033 ) -> tuple[Type, Type]:
4034 """Type check a call to a named method on an object.
4035
4036 Return tuple (result type, inferred method type). The 'original_type'
4037 is used for error messages. The self_type is to bind self in methods
4038 (see analyze_member_access for more details).
4039 """
4040 original_type = original_type or base_type
4041 self_type = self_type or base_type
4042 # Unions are special-cased to allow plugins to act on each element of the union.
4043 base_type = get_proper_type(base_type)
4044 if isinstance(base_type, UnionType):
4045 return self.check_union_method_call_by_name(
4046 method, base_type, args, arg_kinds, context, original_type
4047 )
4048
4049 method_type = analyze_member_access(
4050 method,
4051 base_type,
4052 context,
4053 is_lvalue=False,
4054 is_super=False,
4055 is_operator=True,
4056 original_type=original_type,
4057 self_type=self_type,
4058 chk=self.chk,
4059 in_literal_context=self.is_literal_context(),
4060 )
4061 return self.check_method_call(method, base_type, method_type, args, arg_kinds, context)
4062
4063 def check_union_method_call_by_name(
4064 self,
4065 method: str,
4066 base_type: UnionType,
4067 args: list[Expression],
4068 arg_kinds: list[ArgKind],
4069 context: Context,
4070 original_type: Type | None = None,
4071 ) -> tuple[Type, Type]:
4072 """Type check a call to a named method on an object with union type.
4073
4074 This essentially checks the call using check_method_call_by_name() for each
4075 union item and unions the result. We do this to allow plugins to act on
4076 individual union items.
4077 """
4078 res: list[Type] = []
4079 meth_res: list[Type] = []
4080 for typ in base_type.relevant_items():
4081 # Format error messages consistently with
4082 # mypy.checkmember.analyze_union_member_access().
4083 with self.msg.disable_type_names():
4084 item, meth_item = self.check_method_call_by_name(
4085 method, typ, args, arg_kinds, context, original_type
4086 )
4087 res.append(item)
4088 meth_res.append(meth_item)
4089 return make_simplified_union(res), make_simplified_union(meth_res)
4090
4091 def check_method_call(
4092 self,
4093 method_name: str,
4094 base_type: Type,
4095 method_type: Type,
4096 args: list[Expression],
4097 arg_kinds: list[ArgKind],
4098 context: Context,
4099 ) -> tuple[Type, Type]:
4100 """Type check a call to a method with the given name and type on an object.
4101
4102 Return tuple (result type, inferred method type).
4103 """
4104 callable_name = self.method_fullname(base_type, method_name)
4105 object_type = base_type if callable_name is not None else None
4106
4107 # Try to refine the method signature using plugin hooks before checking the call.
4108 method_type = self.transform_callee_type(
4109 callable_name, method_type, args, arg_kinds, context, object_type=object_type
4110 )
4111
4112 return self.check_call(
4113 method_type,
4114 args,
4115 arg_kinds,
4116 context,
4117 callable_name=callable_name,
4118 object_type=base_type,
4119 )
4120
4121 def lookup_operator(self, op_name: str, base_type: Type, context: Context) -> Type | None:
4122 """Looks up the given operator and returns the corresponding type,
4123 if it exists."""
4124
4125 # This check is an important performance optimization.
4126 if not has_operator(base_type, op_name):
4127 return None
4128
4129 with self.msg.filter_errors() as w:
4130 member = analyze_member_access(
4131 name=op_name,
4132 typ=base_type,
4133 is_lvalue=False,
4134 is_super=False,
4135 is_operator=True,
4136 original_type=base_type,
4137 context=context,
4138 chk=self.chk,
4139 in_literal_context=self.is_literal_context(),
4140 )
4141 return None if w.has_new_errors() else member
4142
4143 def lookup_definer(self, typ: Instance, attr_name: str) -> str | None:
4144 """Returns the name of the class that contains the actual definition of attr_name.
4145
4146 So if class A defines foo and class B subclasses A, running
4147 `get_class_defined_in(B, "foo")` would return the full name of A.
4148
4149 However, if B were to override and redefine foo, that method call would
4150 return the full name of B instead.
4151
4152 If the attr name is not present in the given class or its MRO, returns None.
4153 """
4154 for cls in typ.type.mro:
4155 if cls.names.get(attr_name):
4156 return cls.fullname
4157 return None
4158
4159 def check_op_reversible(
4160 self,
4161 op_name: str,
4162 left_type: Type,
4163 left_expr: Expression,
4164 right_type: Type,
4165 right_expr: Expression,
4166 context: Context,
4167 ) -> tuple[Type, Type]:
4168 left_type = get_proper_type(left_type)
4169 right_type = get_proper_type(right_type)
4170
4171 # If either the LHS or the RHS are Any, we can't really conclude anything
4172 # about the operation since the Any type may or may not define an
4173 # __op__ or __rop__ method. So, we punt and return Any instead.
4174
4175 if isinstance(left_type, AnyType):
4176 any_type = AnyType(TypeOfAny.from_another_any, source_any=left_type)
4177 return any_type, any_type
4178 if isinstance(right_type, AnyType):
4179 any_type = AnyType(TypeOfAny.from_another_any, source_any=right_type)
4180 return any_type, any_type
4181
4182 # STEP 1:
4183 # We start by getting the __op__ and __rop__ methods, if they exist.
4184
4185 rev_op_name = operators.reverse_op_methods[op_name]
4186
4187 left_op = self.lookup_operator(op_name, left_type, context)
4188 right_op = self.lookup_operator(rev_op_name, right_type, context)
4189
4190 # STEP 2a:
4191 # We figure out in which order Python will call the operator methods. As it
4192 # turns out, it's not as simple as just trying to call __op__ first and
4193 # __rop__ second.
4194 #
4195 # We store the determined order inside the 'variants_raw' variable,
4196 # which records tuples containing the method, base type, and the argument.
4197
4198 if op_name in operators.op_methods_that_shortcut and is_same_type(left_type, right_type):
4199 # When we do "A() + A()", for example, Python will only call the __add__ method,
4200 # never the __radd__ method.
4201 #
4202 # This is the case even if the __add__ method is completely missing and the __radd__
4203 # method is defined.
4204
4205 variants_raw = [(op_name, left_op, left_type, right_expr)]
4206 elif (
4207 (
4208 # Checking (A implies B) using the logically equivalent (not A or B), where
4209 # A: left and right are both `Instance` objects
4210 # B: right's __rop__ method is different from left's __op__ method
4211 not (isinstance(left_type, Instance) and isinstance(right_type, Instance))
4212 or (
4213 self.lookup_definer(left_type, op_name)
4214 != self.lookup_definer(right_type, rev_op_name)
4215 and (
4216 left_type.type.alt_promote is None
4217 or left_type.type.alt_promote.type is not right_type.type
4218 )
4219 )
4220 )
4221 # Note: use `covers_at_runtime` instead of `is_subtype` (#19006)
4222 and covers_at_runtime(right_type, left_type)
4223 ):
4224 # When we do "A() + B()" where B is a subclass of A, we'll actually try calling
4225 # B's __radd__ method first, but ONLY if B explicitly defines or overrides the
4226 # __radd__ method.
4227 #
4228 # This mechanism lets subclasses "refine" the expected outcome of the operation, even
4229 # if they're located on the RHS.
4230 #
4231 # As a special case, the alt_promote check makes sure that we don't use the
4232 # __radd__ method of int if the LHS is a native int type.
4233
4234 variants_raw = [
4235 (rev_op_name, right_op, right_type, left_expr),
4236 (op_name, left_op, left_type, right_expr),
4237 ]
4238 else:
4239 # In all other cases, we do the usual thing and call __add__ first and
4240 # __radd__ second when doing "A() + B()".
4241
4242 variants_raw = [
4243 (op_name, left_op, left_type, right_expr),
4244 (rev_op_name, right_op, right_type, left_expr),
4245 ]
4246
4247 # STEP 3:
4248 # We now filter out all non-existent operators. The 'variants' list contains
4249 # all operator methods that are actually present, in the order that Python
4250 # attempts to invoke them.
4251
4252 variants = [(na, op, obj, arg) for (na, op, obj, arg) in variants_raw if op is not None]
4253
4254 # STEP 4:
4255 # We now try invoking each one. If an operation succeeds, end early and return
4256 # the corresponding result. Otherwise, return the result and errors associated
4257 # with the first entry.
4258
4259 errors = []
4260 results = []
4261 for name, method, obj, arg in variants:
4262 with self.msg.filter_errors(save_filtered_errors=True) as local_errors:
4263 result = self.check_method_call(name, obj, method, [arg], [ARG_POS], context)
4264 if local_errors.has_new_errors():
4265 errors.append(local_errors.filtered_errors())
4266 results.append(result)
4267 else:
4268 return result
4269
4270 # We finish invoking above operators and no early return happens. Therefore,
4271 # we check if either the LHS or the RHS is Instance and fallbacks to Any,
4272 # if so, we also return Any
4273 if (isinstance(left_type, Instance) and left_type.type.fallback_to_any) or (
4274 isinstance(right_type, Instance) and right_type.type.fallback_to_any
4275 ):
4276 any_type = AnyType(TypeOfAny.special_form)
4277 return any_type, any_type
4278
4279 # STEP 4b:
4280 # Sometimes, the variants list is empty. In that case, we fall-back to attempting to
4281 # call the __op__ method (even though it's missing).
4282
4283 if not variants:
4284 with self.msg.filter_errors(save_filtered_errors=True) as local_errors:
4285 result = self.check_method_call_by_name(
4286 op_name, left_type, [right_expr], [ARG_POS], context
4287 )
4288
4289 if local_errors.has_new_errors():
4290 errors.append(local_errors.filtered_errors())
4291 results.append(result)
4292 else:
4293 # Although we should not need this case anymore, we keep it just in case, as
4294 # otherwise we will get a crash if we introduce inconsistency in checkmember.py
4295 return result
4296
4297 self.msg.add_errors(errors[0])
4298 if len(results) == 1:
4299 return results[0]
4300 else:
4301 error_any = AnyType(TypeOfAny.from_error)
4302 result = error_any, error_any
4303 return result
4304
4305 def check_op(
4306 self,
4307 method: str,
4308 base_type: Type,
4309 arg: Expression,
4310 context: Context,
4311 allow_reverse: bool = False,
4312 ) -> tuple[Type, Type]:
4313 """Type check a binary operation which maps to a method call.
4314
4315 Return tuple (result type, inferred operator method type).
4316 """
4317
4318 if allow_reverse:
4319 left_variants = [base_type]
4320 base_type = get_proper_type(base_type)
4321 if isinstance(base_type, UnionType):
4322 left_variants = list(flatten_nested_unions(base_type.relevant_items()))
4323 right_type = self.accept(arg)
4324
4325 # Step 1: We first try leaving the right arguments alone and destructure
4326 # just the left ones. (Mypy can sometimes perform some more precise inference
4327 # if we leave the right operands a union -- see testOperatorWithEmptyListAndSum.)
4328 all_results = []
4329 all_inferred = []
4330
4331 with self.msg.filter_errors() as local_errors:
4332 for left_possible_type in left_variants:
4333 result, inferred = self.check_op_reversible(
4334 op_name=method,
4335 left_type=left_possible_type,
4336 left_expr=TempNode(left_possible_type, context=context),
4337 right_type=right_type,
4338 right_expr=arg,
4339 context=context,
4340 )
4341 all_results.append(result)
4342 all_inferred.append(inferred)
4343
4344 if not local_errors.has_new_errors():
4345 results_final = make_simplified_union(all_results)
4346 inferred_final = make_simplified_union(all_inferred)
4347 return results_final, inferred_final
4348
4349 # Step 2: If that fails, we try again but also destructure the right argument.
4350 # This is also necessary to make certain edge cases work -- see
4351 # testOperatorDoubleUnionInterwovenUnionAdd, for example.
4352
4353 # Note: We want to pass in the original 'arg' for 'left_expr' and 'right_expr'
4354 # whenever possible so that plugins and similar things can introspect on the original
4355 # node if possible.
4356 #
4357 # We don't do the same for the base expression because it could lead to weird
4358 # type inference errors -- e.g. see 'testOperatorDoubleUnionSum'.
4359 # TODO: Can we use `type_overrides_set()` here?
4360 right_variants = [(right_type, arg)]
4361 right_type = get_proper_type(right_type)
4362 if isinstance(right_type, UnionType):
4363 right_variants = [
4364 (item, TempNode(item, context=context))
4365 for item in flatten_nested_unions(right_type.relevant_items())
4366 ]
4367
4368 all_results = []
4369 all_inferred = []
4370
4371 with self.msg.filter_errors(save_filtered_errors=True) as local_errors:
4372 for left_possible_type in left_variants:
4373 for right_possible_type, right_expr in right_variants:
4374 result, inferred = self.check_op_reversible(
4375 op_name=method,
4376 left_type=left_possible_type,
4377 left_expr=TempNode(left_possible_type, context=context),
4378 right_type=right_possible_type,
4379 right_expr=right_expr,
4380 context=context,
4381 )
4382 all_results.append(result)
4383 all_inferred.append(inferred)
4384
4385 if local_errors.has_new_errors():
4386 self.msg.add_errors(local_errors.filtered_errors())
4387 # Point any notes to the same location as an existing message.
4388 err = local_errors.filtered_errors()[-1]
4389 recent_context = TempNode(NoneType())
4390 recent_context.line = err.line
4391 recent_context.column = err.column
4392 if len(left_variants) >= 2 and len(right_variants) >= 2:
4393 self.msg.warn_both_operands_are_from_unions(recent_context)
4394 elif len(left_variants) >= 2:
4395 self.msg.warn_operand_was_from_union("Left", base_type, context=recent_context)
4396 elif len(right_variants) >= 2:
4397 self.msg.warn_operand_was_from_union(
4398 "Right", right_type, context=recent_context
4399 )
4400
4401 # See the comment in 'check_overload_call' for more details on why
4402 # we call 'combine_function_signature' instead of just unioning the inferred
4403 # callable types.
4404 results_final = make_simplified_union(all_results)
4405 inferred_final = self.combine_function_signatures(get_proper_types(all_inferred))
4406 return results_final, inferred_final
4407 else:
4408 return self.check_method_call_by_name(
4409 method=method,
4410 base_type=base_type,
4411 args=[arg],
4412 arg_kinds=[ARG_POS],
4413 context=context,
4414 )
4415
4416 def check_boolean_op(self, e: OpExpr) -> Type:
4417 """Type check a boolean operation ('and' or 'or')."""
4418
4419 # A boolean operation can evaluate to either of the operands.
4420
4421 # We use the current type context to guide the type inference of
4422 # the left operand. We also use the left operand type to guide the type
4423 # inference of the right operand so that expressions such as
4424 # '[1] or []' are inferred correctly.
4425 ctx = self.type_context[-1]
4426 left_type = self.accept(e.left, ctx)
4427 expanded_left_type = try_expanding_sum_type_to_union(left_type, "builtins.bool")
4428
4429 assert e.op in ("and", "or") # Checked by visit_op_expr
4430
4431 left_map: mypy.checker.TypeMap
4432 right_map: mypy.checker.TypeMap
4433 if e.right_always:
4434 left_map, right_map = {e.left: UninhabitedType()}, {}
4435 elif e.right_unreachable:
4436 left_map, right_map = {}, {e.right: UninhabitedType()}
4437 elif e.op == "and":
4438 right_map, left_map = self.chk.find_isinstance_check(e.left)
4439 elif e.op == "or":
4440 left_map, right_map = self.chk.find_isinstance_check(e.left)
4441
4442 # If left_map is unreachable then we know mypy considers the left expression
4443 # to be redundant.
4444 left_unreachable = mypy.checker.is_unreachable_map(left_map)
4445 if (
4446 codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes
4447 and left_unreachable
4448 # don't report an error if it's intentional
4449 and not e.right_always
4450 ):
4451 self.msg.redundant_left_operand(e.op, e.left)
4452
4453 right_unreachable = mypy.checker.is_unreachable_map(right_map)
4454 if (
4455 self.chk.should_report_unreachable_issues()
4456 and right_unreachable
4457 # don't report an error if it's intentional
4458 and not e.right_unreachable
4459 ):
4460 self.msg.unreachable_right_operand(e.op, e.right)
4461
4462 right_type = self.analyze_cond_branch(
4463 right_map, e.right, self._combined_context(expanded_left_type)
4464 )
4465
4466 if left_unreachable and right_unreachable:
4467 return UninhabitedType()
4468
4469 if right_unreachable:
4470 # The boolean expression is statically known to be the left value
4471 return left_type
4472 if left_unreachable:
4473 # The boolean expression is statically known to be the right value
4474 return right_type
4475
4476 if e.op == "and":
4477 restricted_left_type = false_only(expanded_left_type)
4478 result_is_left = not expanded_left_type.can_be_true
4479 elif e.op == "or":
4480 restricted_left_type = true_only(expanded_left_type)
4481 result_is_left = not expanded_left_type.can_be_false
4482
4483 if isinstance(restricted_left_type, UninhabitedType):
4484 # The left operand can never be the result
4485 return right_type
4486 elif result_is_left:
4487 # The left operand is always the result
4488 return left_type
4489 else:
4490 return make_simplified_union([restricted_left_type, right_type])
4491
4492 def check_list_multiply(self, e: OpExpr) -> Type:
4493 """Type check an expression of form '[...] * e'.
4494
4495 Type inference is special-cased for this common construct.
4496 """
4497 right_type = self.accept(e.right)
4498 if is_subtype(right_type, self.named_type("builtins.int")):
4499 # Special case: [...] * <int value>. Use the type context of the
4500 # OpExpr, since the multiplication does not affect the type.
4501 left_type = self.accept(e.left, type_context=self.type_context[-1])
4502 else:
4503 left_type = self.accept(e.left)
4504 result, method_type = self.check_op("__mul__", left_type, e.right, e)
4505 e.method_type = method_type
4506 return result
4507
4508 def visit_assignment_expr(self, e: AssignmentExpr) -> Type:
4509 value = self.accept(e.value)
4510 binder_version = self.chk.binder.version
4511 self.chk.check_assignment(e.target, e.value)
4512 if self.chk.binder.version != binder_version:
4513 self.chk.assignment_expression_effect += 1
4514 self.chk.check_final(e)
4515 if not has_uninhabited_component(value):
4516 # TODO: can we get rid of this extra store_type()?
4517 # Usually, check_assignment() already stores the lvalue type correctly.
4518 self.chk.store_type(e.target, value)
4519 self.find_partial_type_ref_fast_path(e.target)
4520 return value
4521
4522 def visit_unary_expr(self, e: UnaryExpr) -> Type:
4523 """Type check an unary operation ('not', '-', '+' or '~')."""
4524 operand_type = self.accept(e.expr)
4525 op = e.op
4526 if op == "not":
4527 result: Type = self.bool_type()
4528 self.chk.check_for_truthy_type(operand_type, e.expr)
4529 else:
4530 method = operators.unary_op_methods[op]
4531 result, method_type = self.check_method_call_by_name(method, operand_type, [], [], e)
4532 e.method_type = method_type
4533 return result
4534
4535 def visit_index_expr(self, e: IndexExpr) -> Type:
4536 """Type check an index expression (base[index]).
4537
4538 It may also represent type application.
4539 """
4540 result = self.visit_index_expr_helper(e)
4541 result = self.narrow_type_from_binder(e, result)
4542 p_result = get_proper_type(result)
4543 if (
4544 self.is_literal_context()
4545 and isinstance(p_result, Instance)
4546 and p_result.last_known_value is not None
4547 ):
4548 result = p_result.last_known_value
4549 return result
4550
4551 def visit_index_expr_helper(self, e: IndexExpr) -> Type:
4552 if e.analyzed:
4553 # It's actually a type application.
4554 return self.accept(e.analyzed)
4555 left_type = self.accept(e.base)
4556 return self.visit_index_with_type(left_type, e)
4557
4558 def visit_index_with_type(
4559 self,
4560 left_type: Type,
4561 e: IndexExpr,
4562 original_type: ProperType | None = None,
4563 self_type: Type | None = None,
4564 ) -> Type:
4565 """Analyze type of an index expression for a given type of base expression.
4566
4567 The 'original_type' is used for error messages (currently used for union types). The
4568 'self_type' is to bind self in methods (see analyze_member_access for more details).
4569 """
4570 index = e.index
4571 self_type = self_type or left_type
4572 left_type = get_proper_type(left_type)
4573
4574 # Visit the index, just to make sure we have a type for it available
4575 self.accept(index)
4576
4577 if isinstance(left_type, TupleType) and any(
4578 isinstance(it, UnpackType) for it in left_type.items
4579 ):
4580 # Normalize variadic tuples for consistency.
4581 left_type = expand_type(left_type, {})
4582
4583 if isinstance(left_type, UnionType):
4584 original_type = original_type or left_type
4585 # Don't combine literal types, since we may need them for type narrowing.
4586 return make_simplified_union(
4587 [
4588 self.visit_index_with_type(typ, e, original_type)
4589 for typ in left_type.relevant_items()
4590 ],
4591 contract_literals=False,
4592 )
4593 elif isinstance(left_type, TupleType) and self.chk.in_checked_function():
4594 # Special case for tuples. They return a more specific type when
4595 # indexed by an integer literal.
4596 if isinstance(index, SliceExpr):
4597 return self.visit_tuple_slice_helper(left_type, index)
4598
4599 ns = self.try_getting_int_literals(index)
4600 if ns is not None:
4601 out = []
4602 for n in ns:
4603 item = self.visit_tuple_index_helper(left_type, n)
4604 if item is not None:
4605 out.append(item)
4606 else:
4607 self.chk.fail(message_registry.TUPLE_INDEX_OUT_OF_RANGE, e)
4608 if any(isinstance(t, UnpackType) for t in left_type.items):
4609 min_len = self.min_tuple_length(left_type)
4610 self.chk.note(f"Variadic tuple can have length {min_len}", e)
4611 return AnyType(TypeOfAny.from_error)
4612 return make_simplified_union(out)
4613 else:
4614 return self.nonliteral_tuple_index_helper(left_type, index)
4615 elif isinstance(left_type, TypedDictType):
4616 return self.visit_typeddict_index_expr(left_type, e.index)[0]
4617 elif isinstance(left_type, FunctionLike) and left_type.is_type_obj():
4618 if left_type.type_object().is_enum:
4619 return self.visit_enum_index_expr(left_type.type_object(), e.index, e)
4620 elif (
4621 left_type.type_object().type_vars
4622 or left_type.type_object().fullname == "builtins.type"
4623 ):
4624 return self.named_type("types.GenericAlias")
4625
4626 if isinstance(left_type, TypeVarType):
4627 return self.visit_index_with_type(
4628 left_type.values_or_bound(), e, original_type, left_type
4629 )
4630 elif isinstance(left_type, Instance) and left_type.type.fullname == "typing._SpecialForm":
4631 # Allow special forms to be indexed and used to create union types
4632 return self.named_type("typing._SpecialForm")
4633 else:
4634 result, method_type = self.check_method_call_by_name(
4635 "__getitem__",
4636 left_type,
4637 [e.index],
4638 [ARG_POS],
4639 e,
4640 original_type=original_type,
4641 self_type=self_type,
4642 )
4643 e.method_type = method_type
4644 return result
4645
4646 def min_tuple_length(self, left: TupleType) -> int:
4647 unpack_index = find_unpack_in_list(left.items)
4648 if unpack_index is None:
4649 return left.length()
4650 unpack = left.items[unpack_index]
4651 assert isinstance(unpack, UnpackType)
4652 if isinstance(unpack.type, TypeVarTupleType):
4653 return left.length() - 1 + unpack.type.min_len
4654 return left.length() - 1
4655
4656 def visit_tuple_index_helper(self, left: TupleType, n: int) -> Type | None:
4657 unpack_index = find_unpack_in_list(left.items)
4658 if unpack_index is None:
4659 if n < 0:
4660 n += len(left.items)
4661 if 0 <= n < len(left.items):
4662 return left.items[n]
4663 return None
4664 unpack = left.items[unpack_index]
4665 assert isinstance(unpack, UnpackType)
4666 unpacked = get_proper_type(unpack.type)
4667 if isinstance(unpacked, TypeVarTupleType):
4668 # Usually we say that TypeVarTuple can't be split, be in case of
4669 # indexing it seems benign to just return the upper bound item, similar
4670 # to what we do when indexing a regular TypeVar.
4671 bound = get_proper_type(unpacked.upper_bound)
4672 assert isinstance(bound, Instance)
4673 assert bound.type.fullname == "builtins.tuple"
4674 middle = bound.args[0]
4675 else:
4676 assert isinstance(unpacked, Instance)
4677 assert unpacked.type.fullname == "builtins.tuple"
4678 middle = unpacked.args[0]
4679
4680 extra_items = self.min_tuple_length(left) - left.length() + 1
4681 if n >= 0:
4682 if n >= self.min_tuple_length(left):
4683 # For tuple[int, *tuple[str, ...], int] we allow either index 0 or 1,
4684 # since variadic item may have zero items.
4685 return None
4686 if n < unpack_index:
4687 return left.items[n]
4688 return UnionType.make_union(
4689 [middle]
4690 + left.items[unpack_index + 1 : max(n - extra_items + 2, unpack_index + 1)],
4691 left.line,
4692 left.column,
4693 )
4694 n += self.min_tuple_length(left)
4695 if n < 0:
4696 # Similar to above, we only allow -1, and -2 for tuple[int, *tuple[str, ...], int]
4697 return None
4698 if n >= unpack_index + extra_items:
4699 return left.items[n - extra_items + 1]
4700 return UnionType.make_union(
4701 left.items[min(n, unpack_index) : unpack_index] + [middle], left.line, left.column
4702 )
4703
4704 def visit_tuple_slice_helper(self, left_type: TupleType, slic: SliceExpr) -> Type:
4705 begin: Sequence[int | None] = [None]
4706 end: Sequence[int | None] = [None]
4707 stride: Sequence[int | None] = [None]
4708
4709 if slic.begin_index:
4710 begin_raw = self.try_getting_int_literals(slic.begin_index)
4711 if begin_raw is None:
4712 return self.nonliteral_tuple_index_helper(left_type, slic)
4713 begin = begin_raw
4714
4715 if slic.end_index:
4716 end_raw = self.try_getting_int_literals(slic.end_index)
4717 if end_raw is None:
4718 return self.nonliteral_tuple_index_helper(left_type, slic)
4719 end = end_raw
4720
4721 if slic.stride:
4722 stride_raw = self.try_getting_int_literals(slic.stride)
4723 if stride_raw is None:
4724 return self.nonliteral_tuple_index_helper(left_type, slic)
4725 stride = stride_raw
4726
4727 items: list[Type] = []
4728 for b, e, s in itertools.product(begin, end, stride):
4729 item = left_type.slice(b, e, s, fallback=self.named_type("builtins.tuple"))
4730 if item is None:
4731 self.chk.fail(message_registry.AMBIGUOUS_SLICE_OF_VARIADIC_TUPLE, slic)
4732 return AnyType(TypeOfAny.from_error)
4733 items.append(item)
4734 return make_simplified_union(items)
4735
4736 def try_getting_int_literals(self, index: Expression) -> list[int] | None:
4737 """If the given expression or type corresponds to an int literal
4738 or a union of int literals, returns a list of the underlying ints.
4739 Otherwise, returns None.
4740
4741 Specifically, this function is guaranteed to return a list with
4742 one or more ints if one the following is true:
4743
4744 1. 'expr' is a IntExpr or a UnaryExpr backed by an IntExpr
4745 2. 'typ' is a LiteralType containing an int
4746 3. 'typ' is a UnionType containing only LiteralType of ints
4747 """
4748 if isinstance(index, IntExpr):
4749 return [index.value]
4750 elif isinstance(index, UnaryExpr):
4751 if index.op == "-":
4752 operand = index.expr
4753 if isinstance(operand, IntExpr):
4754 return [-1 * operand.value]
4755 if index.op == "+":
4756 operand = index.expr
4757 if isinstance(operand, IntExpr):
4758 return [operand.value]
4759 typ = get_proper_type(self.accept(index))
4760 if isinstance(typ, Instance) and typ.last_known_value is not None:
4761 typ = typ.last_known_value
4762 if isinstance(typ, LiteralType) and isinstance(typ.value, int):
4763 return [typ.value]
4764 if isinstance(typ, UnionType):
4765 out = []
4766 for item in get_proper_types(typ.items):
4767 if isinstance(item, LiteralType) and isinstance(item.value, int):
4768 out.append(item.value)
4769 else:
4770 return None
4771 return out
4772 return None
4773
4774 def nonliteral_tuple_index_helper(self, left_type: TupleType, index: Expression) -> Type:
4775 self.check_method_call_by_name("__getitem__", left_type, [index], [ARG_POS], context=index)
4776 # We could return the return type from above, but unions are often better than the join
4777 union = self.union_tuple_fallback_item(left_type)
4778 if isinstance(index, SliceExpr):
4779 return self.chk.named_generic_type("builtins.tuple", [union])
4780 return union
4781
4782 def union_tuple_fallback_item(self, left_type: TupleType) -> Type:
4783 # TODO: this duplicates logic in typeops.tuple_fallback().
4784 items = []
4785 for item in left_type.items:
4786 if isinstance(item, UnpackType):
4787 unpacked_type = get_proper_type(item.type)
4788 if isinstance(unpacked_type, TypeVarTupleType):
4789 unpacked_type = get_proper_type(unpacked_type.upper_bound)
4790 if (
4791 isinstance(unpacked_type, Instance)
4792 and unpacked_type.type.fullname == "builtins.tuple"
4793 ):
4794 items.append(unpacked_type.args[0])
4795 else:
4796 raise NotImplementedError
4797 else:
4798 items.append(item)
4799 return make_simplified_union(items)
4800
4801 def visit_typeddict_index_expr(
4802 self, td_type: TypedDictType, index: Expression, setitem: bool = False
4803 ) -> tuple[Type, set[str]]:
4804 if isinstance(index, StrExpr):
4805 key_names = [index.value]
4806 else:
4807 typ = get_proper_type(self.accept(index))
4808 if isinstance(typ, UnionType):
4809 key_types: list[Type] = list(typ.items)
4810 else:
4811 key_types = [typ]
4812
4813 key_names = []
4814 for key_type in get_proper_types(key_types):
4815 if isinstance(key_type, Instance) and key_type.last_known_value is not None:
4816 key_type = key_type.last_known_value
4817
4818 if (
4819 isinstance(key_type, LiteralType)
4820 and isinstance(key_type.value, str)
4821 and key_type.fallback.type.fullname != "builtins.bytes"
4822 ):
4823 key_names.append(key_type.value)
4824 else:
4825 self.msg.typeddict_key_must_be_string_literal(td_type, index)
4826 return AnyType(TypeOfAny.from_error), set()
4827
4828 value_types = []
4829 for key_name in key_names:
4830 value_type = td_type.items.get(key_name)
4831 if value_type is None:
4832 self.msg.typeddict_key_not_found(td_type, key_name, index, setitem)
4833 return AnyType(TypeOfAny.from_error), set()
4834 else:
4835 value_types.append(value_type)
4836 return make_simplified_union(value_types), set(key_names)
4837
4838 def visit_enum_index_expr(
4839 self, enum_type: TypeInfo, index: Expression, context: Context
4840 ) -> Type:
4841 string_type: Type = self.named_type("builtins.str")
4842 self.chk.check_subtype(
4843 self.accept(index),
4844 string_type,
4845 context,
4846 "Enum index should be a string",
4847 "actual index type",
4848 )
4849 return Instance(enum_type, [])
4850
4851 def visit_cast_expr(self, expr: CastExpr) -> Type:
4852 """Type check a cast expression."""
4853 source_type = self.accept(
4854 expr.expr,
4855 type_context=AnyType(TypeOfAny.special_form),
4856 allow_none_return=True,
4857 always_allow_any=True,
4858 )
4859 target_type = expr.type
4860 options = self.chk.options
4861 if (
4862 options.warn_redundant_casts
4863 and not is_same_type(target_type, AnyType(TypeOfAny.special_form))
4864 and is_same_type(source_type, target_type)
4865 ):
4866 self.msg.redundant_cast(target_type, expr)
4867 if options.disallow_any_unimported and has_any_from_unimported_type(target_type):
4868 self.msg.unimported_type_becomes_any("Target type of cast", target_type, expr)
4869 check_for_explicit_any(
4870 target_type, self.chk.options, self.chk.is_typeshed_stub, self.msg, context=expr
4871 )
4872 return target_type
4873
4874 def visit_type_form_expr(self, expr: TypeFormExpr) -> Type:
4875 typ = expr.type
4876 return TypeType.make_normalized(typ, line=typ.line, column=typ.column, is_type_form=True)
4877
4878 def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type:
4879 source_type = self.accept(
4880 expr.expr,
4881 type_context=self.type_context[-1],
4882 allow_none_return=True,
4883 always_allow_any=True,
4884 )
4885 if self.chk.current_node_deferred:
4886 return source_type
4887
4888 target_type = expr.type
4889 proper_source_type = get_proper_type(source_type)
4890 if (
4891 isinstance(proper_source_type, mypy.types.Instance)
4892 and proper_source_type.last_known_value is not None
4893 ):
4894 source_type = proper_source_type.last_known_value
4895 if not is_same_type(source_type, target_type):
4896 if not self.chk.in_checked_function():
4897 self.msg.note(
4898 '"assert_type" expects everything to be "Any" in unchecked functions',
4899 expr.expr,
4900 )
4901 self.msg.assert_type_fail(source_type, target_type, expr)
4902 return source_type
4903
4904 def visit_reveal_expr(self, expr: RevealExpr) -> Type:
4905 """Type check a reveal_type expression."""
4906 if expr.kind == REVEAL_TYPE:
4907 assert expr.expr is not None
4908 revealed_type = self.accept(
4909 expr.expr, type_context=self.type_context[-1], allow_none_return=True
4910 )
4911 if not self.chk.current_node_deferred:
4912 self.msg.reveal_type(revealed_type, expr.expr)
4913 if not self.chk.in_checked_function():
4914 self.msg.note(
4915 "'reveal_type' always outputs 'Any' in unchecked functions", expr.expr
4916 )
4917 self.check_reveal_imported(expr)
4918 return revealed_type
4919 else:
4920 # REVEAL_LOCALS
4921 if not self.chk.current_node_deferred:
4922 # the RevealExpr contains a local_nodes attribute,
4923 # calculated at semantic analysis time. Use it to pull out the
4924 # corresponding subset of variables in self.chk.type_map
4925 names_to_types = (
4926 {var_node.name: var_node.type for var_node in expr.local_nodes}
4927 if expr.local_nodes is not None
4928 else {}
4929 )
4930
4931 self.msg.reveal_locals(names_to_types, expr)
4932 self.check_reveal_imported(expr)
4933 return NoneType()
4934
4935 def check_reveal_imported(self, expr: RevealExpr) -> None:
4936 if codes.UNIMPORTED_REVEAL not in self.chk.options.enabled_error_codes:
4937 return
4938
4939 name = ""
4940 if expr.kind == REVEAL_LOCALS:
4941 name = "reveal_locals"
4942 elif expr.kind == REVEAL_TYPE and not expr.is_imported:
4943 name = "reveal_type"
4944 else:
4945 return
4946
4947 self.chk.fail(f'Name "{name}" is not defined', expr, code=codes.UNIMPORTED_REVEAL)
4948 if name == "reveal_type":
4949 module = (
4950 "typing" if self.chk.options.python_version >= (3, 11) else "typing_extensions"
4951 )
4952 hint = (
4953 'Did you forget to import it from "{module}"?'
4954 ' (Suggestion: "from {module} import {name}")'
4955 ).format(module=module, name=name)
4956 self.chk.note(hint, expr, code=codes.UNIMPORTED_REVEAL)
4957
4958 def visit_type_application(self, tapp: TypeApplication) -> Type:
4959 """Type check a type application (expr[type, ...]).
4960
4961 There are two different options here, depending on whether expr refers
4962 to a type alias or directly to a generic class. In the first case we need
4963 to use a dedicated function typeanal.instantiate_type_alias(). This
4964 is due to slight differences in how type arguments are applied and checked.
4965 """
4966 if isinstance(tapp.expr, RefExpr) and isinstance(tapp.expr.node, TypeAlias):
4967 if tapp.expr.node.python_3_12_type_alias:
4968 return self.type_alias_type_type()
4969 # Subscription of a (generic) alias in runtime context, expand the alias.
4970 item, _ = instantiate_type_alias(
4971 tapp.expr.node,
4972 tapp.types,
4973 self.chk.fail,
4974 self.chk.note,
4975 tapp.expr.node.no_args,
4976 tapp,
4977 self.chk.options,
4978 )
4979 item = get_proper_type(item)
4980 if isinstance(item, Instance):
4981 tp = type_object_type(item.type)
4982 return self.apply_type_arguments_to_callable(tp, item.args, tapp)
4983 elif isinstance(item, TupleType) and item.partial_fallback.type.is_named_tuple:
4984 tp = type_object_type(item.partial_fallback.type)
4985 return self.apply_type_arguments_to_callable(tp, item.partial_fallback.args, tapp)
4986 elif isinstance(item, TypedDictType):
4987 return self.typeddict_callable_from_context(item)
4988 else:
4989 self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp)
4990 return AnyType(TypeOfAny.from_error)
4991 # Type application of a normal generic class in runtime context.
4992 # This is typically used as `x = G[int]()`.
4993 tp = get_proper_type(self.accept(tapp.expr))
4994 if isinstance(tp, (CallableType, Overloaded)):
4995 if not tp.is_type_obj():
4996 self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp)
4997 return self.apply_type_arguments_to_callable(tp, tapp.types, tapp)
4998 if isinstance(tp, AnyType):
4999 return AnyType(TypeOfAny.from_another_any, source_any=tp)
5000 return AnyType(TypeOfAny.special_form)
5001
5002 def visit_type_alias_expr(self, alias: TypeAliasExpr) -> Type:
5003 """Right hand side of a type alias definition.
5004
5005 It has the same type as if the alias itself was used in a runtime context.
5006 For example, here:
5007
5008 A = reveal_type(List[T])
5009 reveal_type(A)
5010
5011 both `reveal_type` instances will reveal the same type `def (...) -> builtins.list[Any]`.
5012 Note that type variables are implicitly substituted with `Any`.
5013 """
5014 return self.alias_type_in_runtime_context(alias.node, ctx=alias, alias_definition=True)
5015
5016 def alias_type_in_runtime_context(
5017 self, alias: TypeAlias, *, ctx: Context, alias_definition: bool = False
5018 ) -> Type:
5019 """Get type of a type alias (could be generic) in a runtime expression.
5020
5021 Note that this function can be called only if the alias appears _not_
5022 as a target of type application, which is treated separately in the
5023 visit_type_application method. Some examples where this method is called are
5024 casts and instantiation:
5025
5026 class LongName(Generic[T]): ...
5027 A = LongName[int]
5028
5029 x = A()
5030 y = cast(A, ...)
5031 """
5032 if alias.python_3_12_type_alias:
5033 return self.type_alias_type_type()
5034 # If this is a generic alias, we set all variables to `Any`.
5035 # For example:
5036 # A = List[Tuple[T, T]]
5037 # x = A() <- same as List[Tuple[Any, Any]], see PEP 484.
5038 disallow_any = self.chk.options.disallow_any_generics and self.is_callee
5039 item, _ = set_any_tvars(
5040 alias,
5041 [],
5042 ctx.line,
5043 ctx.column,
5044 self.chk.options,
5045 disallow_any=disallow_any,
5046 fail=self.msg.fail,
5047 )
5048 item = get_proper_type(item)
5049 if isinstance(item, Instance):
5050 # Normally we get a callable type (or overloaded) with .is_type_obj() true
5051 # representing the class's constructor
5052 tp = type_object_type(item.type)
5053 if alias.no_args:
5054 return tp
5055 return self.apply_type_arguments_to_callable(tp, item.args, ctx)
5056 elif (
5057 isinstance(item, TupleType)
5058 and
5059 # Tuple[str, int]() fails at runtime, only named tuples and subclasses work.
5060 tuple_fallback(item).type.fullname != "builtins.tuple"
5061 ):
5062 return type_object_type(tuple_fallback(item).type)
5063 elif isinstance(item, TypedDictType):
5064 return self.typeddict_callable_from_context(item)
5065 elif isinstance(item, NoneType):
5066 return TypeType(item, line=item.line, column=item.column)
5067 elif isinstance(item, AnyType):
5068 return AnyType(TypeOfAny.from_another_any, source_any=item)
5069 elif isinstance(item, UnionType) and item.uses_pep604_syntax:
5070 return self.chk.named_generic_type("types.UnionType", item.items)
5071 else:
5072 if alias_definition:
5073 return AnyType(TypeOfAny.special_form)
5074 # The _SpecialForm type can be used in some runtime contexts (e.g. it may have __or__).
5075 return self.named_type("typing._SpecialForm")
5076
5077 def split_for_callable(
5078 self, t: CallableType, args: Sequence[Type], ctx: Context
5079 ) -> list[Type]:
5080 """Handle directly applying type arguments to a variadic Callable.
5081
5082 This is needed in situations where e.g. variadic class object appears in
5083 runtime context. For example:
5084 class C(Generic[T, Unpack[Ts]]): ...
5085 x = C[int, str]()
5086
5087 We simply group the arguments that need to go into Ts variable into a TupleType,
5088 similar to how it is done in other places using split_with_prefix_and_suffix().
5089 """
5090 if t.is_type_obj():
5091 # Type arguments must map to class type variables, ignoring constructor vars.
5092 vars = t.type_object().defn.type_vars
5093 else:
5094 vars = list(t.variables)
5095 args = flatten_nested_tuples(args)
5096
5097 # TODO: this logic is duplicated with semanal_typeargs.
5098 for tv, arg in zip(t.variables, args):
5099 if isinstance(tv, ParamSpecType):
5100 if not isinstance(
5101 get_proper_type(arg), (Parameters, ParamSpecType, AnyType, UnboundType)
5102 ):
5103 self.chk.fail(
5104 "Can only replace ParamSpec with a parameter types list or"
5105 f" another ParamSpec, got {format_type(arg, self.chk.options)}",
5106 ctx,
5107 )
5108 return [AnyType(TypeOfAny.from_error)] * len(vars)
5109
5110 # TODO: in future we may want to support type application to variadic functions.
5111 if not vars or not t.is_type_obj() or t.type_object().fullname == "builtins.tuple":
5112 return list(args)
5113 info = t.type_object()
5114 # We reuse the logic from semanal phase to reduce code duplication.
5115 fake = Instance(info, args, line=ctx.line, column=ctx.column)
5116 # This code can be only called either from checking a type application, or from
5117 # checking a type alias (after the caller handles no_args aliases), so we know it
5118 # was initially an IndexExpr, and we allow empty tuple type arguments.
5119 if not validate_instance(fake, self.chk.fail, indexed=True):
5120 fix_instance(
5121 fake, self.chk.fail, self.chk.note, disallow_any=False, options=self.chk.options
5122 )
5123 args = list(fake.args)
5124
5125 if not any(isinstance(v, TypeVarTupleType) for v in vars):
5126 return args
5127
5128 prefix = next(i for (i, v) in enumerate(vars) if isinstance(v, TypeVarTupleType))
5129 suffix = len(vars) - prefix - 1
5130 tvt = vars[prefix]
5131 assert isinstance(tvt, TypeVarTupleType)
5132 start, middle, end = split_with_prefix_and_suffix(tuple(args), prefix, suffix)
5133 return list(start) + [TupleType(list(middle), tvt.tuple_fallback)] + list(end)
5134
5135 def apply_type_arguments_to_callable(
5136 self, tp: Type, args: Sequence[Type], ctx: Context
5137 ) -> Type:
5138 """Apply type arguments to a generic callable type coming from a type object.
5139
5140 This will first perform type arguments count checks, report the
5141 error as needed, and return the correct kind of Any. As a special
5142 case this returns Any for non-callable types, because if type object type
5143 is not callable, then an error should be already reported.
5144 """
5145 tp = get_proper_type(tp)
5146
5147 if isinstance(tp, CallableType):
5148 if tp.is_type_obj():
5149 # If we have a class object in runtime context, then the available type
5150 # variables are those of the class, we don't include additional variables
5151 # of the constructor. So that with
5152 # class C(Generic[T]):
5153 # def __init__(self, f: Callable[[S], T], x: S) -> None
5154 # C[int] is valid
5155 # C[int, str] is invalid (although C as a callable has 2 type variables)
5156 # Note: various logic below and in applytype.py relies on the fact that
5157 # class type variables appear *before* constructor variables.
5158 type_vars = tp.type_object().defn.type_vars
5159 else:
5160 type_vars = list(tp.variables)
5161 min_arg_count = sum(not v.has_default() for v in type_vars)
5162 has_type_var_tuple = any(isinstance(v, TypeVarTupleType) for v in type_vars)
5163 if (
5164 len(args) < min_arg_count or len(args) > len(type_vars)
5165 ) and not has_type_var_tuple:
5166 if tp.is_type_obj() and tp.type_object().fullname == "builtins.tuple":
5167 # e.g. expression tuple[X, Y]
5168 # - want the type of the expression i.e. a function with that as its return type
5169 # - tp is type of tuple (note it won't have params as we are only called
5170 # with generic callable type)
5171 # - tuple[X, Y]() takes a single arg that is a tuple containing an X and a Y
5172 return CallableType(
5173 [TupleType(list(args), self.chk.named_type("tuple"))],
5174 [ARG_POS],
5175 [None],
5176 TupleType(list(args), self.chk.named_type("tuple")),
5177 tp.fallback,
5178 name="tuple",
5179 definition=tp.definition,
5180 is_bound=tp.is_bound,
5181 )
5182 self.msg.incompatible_type_application(
5183 min_arg_count, len(type_vars), len(args), ctx
5184 )
5185 return AnyType(TypeOfAny.from_error)
5186 return self.apply_generic_arguments(tp, self.split_for_callable(tp, args, ctx), ctx)
5187 if isinstance(tp, Overloaded):
5188 for it in tp.items:
5189 if tp.is_type_obj():
5190 # Same as above.
5191 type_vars = tp.type_object().defn.type_vars
5192 else:
5193 type_vars = list(it.variables)
5194 min_arg_count = sum(not v.has_default() for v in type_vars)
5195 has_type_var_tuple = any(isinstance(v, TypeVarTupleType) for v in type_vars)
5196 if (
5197 len(args) < min_arg_count or len(args) > len(type_vars)
5198 ) and not has_type_var_tuple:
5199 self.msg.incompatible_type_application(
5200 min_arg_count, len(type_vars), len(args), ctx
5201 )
5202 return AnyType(TypeOfAny.from_error)
5203 return Overloaded(
5204 [
5205 self.apply_generic_arguments(it, self.split_for_callable(it, args, ctx), ctx)
5206 for it in tp.items
5207 ]
5208 )
5209 return AnyType(TypeOfAny.special_form)
5210
5211 def visit_list_expr(self, e: ListExpr) -> Type:
5212 """Type check a list expression [...]."""
5213 return self.check_lst_expr(e, "builtins.list", "<list>")
5214
5215 def visit_set_expr(self, e: SetExpr) -> Type:
5216 return self.check_lst_expr(e, "builtins.set", "<set>")
5217
5218 def fast_container_type(
5219 self, e: ListExpr | SetExpr | TupleExpr, container_fullname: str
5220 ) -> Type | None:
5221 """
5222 Fast path to determine the type of a list or set literal,
5223 based on the list of entries. This mostly impacts large
5224 module-level constant definitions.
5225
5226 Limitations:
5227
5228 - no active type context
5229 - at least one item
5230 - no star expressions
5231 - not after deferral
5232 - either exactly one distinct type inside,
5233 or the joined type of all entries is an Instance or Tuple type,
5234 """
5235 ctx = self.type_context[-1]
5236 if ctx or not e.items:
5237 return None
5238 if self.chk.current_node_deferred:
5239 # Guarantees that all items will be Any, we'll reject it anyway.
5240 return None
5241 values: list[Type] = []
5242 # Preserve join order while avoiding O(n) lookups at every iteration
5243 values_set: set[Type] = set()
5244 for item in e.items:
5245 if isinstance(item, StarExpr):
5246 # fallback to slow path
5247 return None
5248
5249 typ = self.accept(item)
5250 if typ not in values_set:
5251 values.append(typ)
5252 values_set.add(typ)
5253
5254 vt = self._first_or_join_fast_item(values)
5255 if vt is None:
5256 return None
5257 return self.chk.named_generic_type(container_fullname, [vt])
5258
5259 def _first_or_join_fast_item(self, items: list[Type]) -> Type | None:
5260 if len(items) == 1 and not self.chk.current_node_deferred:
5261 return items[0]
5262 typ = join.join_type_list(items)
5263 if not allow_fast_container_literal(typ):
5264 # TODO: This is overly strict, many other types can be joined safely here.
5265 # However, our join implementation isn't bug-free, and some joins may produce
5266 # undesired `Any`s or even more surprising results.
5267 return None
5268 return typ
5269
5270 def check_lst_expr(self, e: ListExpr | SetExpr | TupleExpr, fullname: str, tag: str) -> Type:
5271 # fast path
5272 t = self.fast_container_type(e, fullname)
5273 if t:
5274 return t
5275
5276 # Translate into type checking a generic function call.
5277 # Used for list and set expressions, as well as for tuples
5278 # containing star expressions that don't refer to a
5279 # Tuple. (Note: "lst" stands for list-set-tuple. :-)
5280 tv = TypeVarType(
5281 "T",
5282 "T",
5283 id=TypeVarId(-1, namespace="<lst>"),
5284 values=[],
5285 upper_bound=self.object_type(),
5286 default=AnyType(TypeOfAny.from_omitted_generics),
5287 )
5288 constructor = CallableType(
5289 [tv],
5290 [nodes.ARG_STAR],
5291 [None],
5292 self.chk.named_generic_type(fullname, [tv]),
5293 self.named_type("builtins.function"),
5294 name=tag,
5295 variables=[tv],
5296 )
5297 out = self.check_call(
5298 constructor,
5299 [(i.expr if isinstance(i, StarExpr) else i) for i in e.items],
5300 [(nodes.ARG_STAR if isinstance(i, StarExpr) else nodes.ARG_POS) for i in e.items],
5301 e,
5302 )[0]
5303 return remove_instance_last_known_values(out)
5304
5305 def tuple_context_matches(self, expr: TupleExpr, ctx: TupleType) -> bool:
5306 ctx_unpack_index = find_unpack_in_list(ctx.items)
5307 if ctx_unpack_index is None:
5308 # For fixed tuples accept everything that can possibly match, even if this
5309 # requires all star items to be empty.
5310 return len([e for e in expr.items if not isinstance(e, StarExpr)]) <= len(ctx.items)
5311 # For variadic context, the only easy case is when structure matches exactly.
5312 # TODO: try using tuple type context in more cases.
5313 if len([e for e in expr.items if isinstance(e, StarExpr)]) != 1:
5314 return False
5315 expr_star_index = next(i for i, lv in enumerate(expr.items) if isinstance(lv, StarExpr))
5316 return len(expr.items) == len(ctx.items) and ctx_unpack_index == expr_star_index
5317
5318 def visit_tuple_expr(self, e: TupleExpr) -> Type:
5319 """Type check a tuple expression."""
5320 # Try to determine type context for type inference.
5321 type_context = get_proper_type(self.type_context[-1])
5322 type_context_items = None
5323 if isinstance(type_context, UnionType):
5324 tuples_in_context = [
5325 t
5326 for t in get_proper_types(type_context.items)
5327 if (isinstance(t, TupleType) and self.tuple_context_matches(e, t))
5328 or is_named_instance(t, TUPLE_LIKE_INSTANCE_NAMES)
5329 ]
5330 if len(tuples_in_context) == 1:
5331 type_context = tuples_in_context[0]
5332 else:
5333 # There are either no relevant tuples in the Union, or there is
5334 # more than one. Either way, we can't decide on a context.
5335 pass
5336
5337 if isinstance(type_context, TupleType) and self.tuple_context_matches(e, type_context):
5338 type_context_items = type_context.items
5339 elif type_context and is_named_instance(type_context, TUPLE_LIKE_INSTANCE_NAMES):
5340 assert isinstance(type_context, Instance)
5341 if type_context.args:
5342 type_context_items = [type_context.args[0]] * len(e.items)
5343 # NOTE: it's possible for the context to have a different
5344 # number of items than e. In that case we use those context
5345 # items that match a position in e, and we'll worry about type
5346 # mismatches later.
5347
5348 unpack_in_context = False
5349 if type_context_items is not None:
5350 unpack_in_context = find_unpack_in_list(type_context_items) is not None
5351 seen_unpack_in_items = False
5352 allow_precise_tuples = (
5353 unpack_in_context or PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature
5354 )
5355
5356 # Infer item types. Give up if there's a star expression
5357 # that's not a Tuple.
5358 items: list[Type] = []
5359 j = 0 # Index into type_context_items; irrelevant if type_context_items is none
5360 for i in range(len(e.items)):
5361 item = e.items[i]
5362 if isinstance(item, StarExpr):
5363 # Special handling for star expressions.
5364 # TODO: If there's a context, and item.expr is a
5365 # TupleExpr, flatten it, so we can benefit from the
5366 # context? Counterargument: Why would anyone write
5367 # (1, *(2, 3)) instead of (1, 2, 3) except in a test?
5368 if unpack_in_context:
5369 # Note: this logic depends on full structure match in tuple_context_matches().
5370 assert type_context_items
5371 ctx_item = type_context_items[j]
5372 assert isinstance(ctx_item, UnpackType)
5373 ctx = ctx_item.type
5374 else:
5375 ctx = None
5376 tt = self.accept(item.expr, ctx)
5377 tt = get_proper_type(tt)
5378 if isinstance(tt, TupleType):
5379 if find_unpack_in_list(tt.items) is not None:
5380 if seen_unpack_in_items:
5381 # Multiple unpack items are not allowed in tuples,
5382 # fall back to instance type.
5383 return self.check_lst_expr(e, "builtins.tuple", "<tuple>")
5384 else:
5385 seen_unpack_in_items = True
5386 items.extend(tt.items)
5387 # Note: this logic depends on full structure match in tuple_context_matches().
5388 if unpack_in_context:
5389 j += 1
5390 else:
5391 # If there is an unpack in expressions, but not in context, this will
5392 # result in an error later, just do something predictable here.
5393 j += len(tt.items)
5394 else:
5395 if allow_precise_tuples and not seen_unpack_in_items:
5396 # Handle (x, *y, z), where y is e.g. tuple[Y, ...].
5397 if isinstance(tt, Instance) and self.chk.type_is_iterable(tt):
5398 item_type = self.chk.iterable_item_type(tt, e)
5399 mapped = self.chk.named_generic_type("builtins.tuple", [item_type])
5400 items.append(UnpackType(mapped))
5401 seen_unpack_in_items = True
5402 continue
5403 # A star expression that's not a Tuple.
5404 # Treat the whole thing as a variable-length tuple.
5405 return self.check_lst_expr(e, "builtins.tuple", "<tuple>")
5406 else:
5407 if not type_context_items or j >= len(type_context_items):
5408 tt = self.accept(item)
5409 else:
5410 tt = self.accept(item, type_context_items[j])
5411 j += 1
5412 items.append(tt)
5413 # This is a partial fallback item type. A precise type will be calculated on demand.
5414 fallback_item = AnyType(TypeOfAny.special_form)
5415 result: ProperType = TupleType(
5416 items, self.chk.named_generic_type("builtins.tuple", [fallback_item])
5417 )
5418 if seen_unpack_in_items:
5419 # Return already normalized tuple type just in case.
5420 result = expand_type(result, {})
5421 return result
5422
5423 def fast_dict_type(self, e: DictExpr) -> Type | None:
5424 """
5425 Fast path to determine the type of a dict literal,
5426 based on the list of entries. This mostly impacts large
5427 module-level constant definitions.
5428
5429 Limitations:
5430
5431 - no active type context
5432 - at least one item
5433 - only supported star expressions are other dict instances
5434 - either exactly one distinct type (keys and values separately) inside,
5435 or the joined type of all entries is an Instance or Tuple type
5436 """
5437 ctx = self.type_context[-1]
5438 if ctx or not e.items:
5439 return None
5440
5441 if self.chk.current_node_deferred:
5442 # Guarantees that all items will be Any, we'll reject it anyway.
5443 return None
5444
5445 keys: list[Type] = []
5446 values: list[Type] = []
5447 # Preserve join order while avoiding O(n) lookups at every iteration
5448 keys_set: set[Type] = set()
5449 values_set: set[Type] = set()
5450 stargs: tuple[Type, Type] | None = None
5451 for key, value in e.items:
5452 if key is None:
5453 st = get_proper_type(self.accept(value))
5454 if (
5455 isinstance(st, Instance)
5456 and st.type.fullname == "builtins.dict"
5457 and len(st.args) == 2
5458 ):
5459 stargs = (st.args[0], st.args[1])
5460 else:
5461 return None
5462 else:
5463 key_t = self.accept(key)
5464 if key_t not in keys_set:
5465 keys.append(key_t)
5466 keys_set.add(key_t)
5467 value_t = self.accept(value)
5468 if value_t not in values_set:
5469 values.append(value_t)
5470 values_set.add(value_t)
5471
5472 kt = self._first_or_join_fast_item(keys)
5473 if kt is None:
5474 return None
5475
5476 vt = self._first_or_join_fast_item(values)
5477 if vt is None:
5478 return None
5479
5480 if stargs and (stargs[0] != kt or stargs[1] != vt):
5481 return None
5482 return self.chk.named_generic_type("builtins.dict", [kt, vt])
5483
5484 def check_typeddict_literal_in_context(
5485 self, e: DictExpr, typeddict_context: TypedDictType
5486 ) -> Type:
5487 orig_ret_type = self.check_typeddict_call_with_dict(
5488 callee=typeddict_context, kwargs=e.items, context=e, orig_callee=None
5489 )
5490 ret_type = get_proper_type(orig_ret_type)
5491 if isinstance(ret_type, TypedDictType):
5492 return ret_type.copy_modified()
5493 return typeddict_context.copy_modified()
5494
5495 def visit_dict_expr(self, e: DictExpr) -> Type:
5496 """Type check a dict expression.
5497
5498 Translate it into a call to dict(), with provisions for **expr.
5499 """
5500 # if the dict literal doesn't match TypedDict, check_typeddict_call_with_dict reports
5501 # an error, but returns the TypedDict type that matches the literal it found
5502 # that would cause a second error when that TypedDict type is returned upstream
5503 # to avoid the second error, we always return TypedDict type that was requested
5504 typeddict_contexts, exhaustive = self.find_typeddict_context(self.type_context[-1], e)
5505 if typeddict_contexts:
5506 if len(typeddict_contexts) == 1 and exhaustive:
5507 return self.check_typeddict_literal_in_context(e, typeddict_contexts[0])
5508 # Multiple items union, check if at least one of them matches cleanly.
5509 for typeddict_context in typeddict_contexts:
5510 with self.msg.filter_errors() as err, self.chk.local_type_map as tmap:
5511 ret_type = self.check_typeddict_literal_in_context(e, typeddict_context)
5512 if err.has_new_errors():
5513 continue
5514 self.chk.store_types(tmap)
5515 return ret_type
5516 # No item matched without an error, so we can't unambiguously choose the item.
5517 if exhaustive:
5518 self.msg.typeddict_context_ambiguous(typeddict_contexts, e)
5519
5520 # fast path attempt
5521 dt = self.fast_dict_type(e)
5522 if dt:
5523 return dt
5524
5525 # Define type variables (used in constructors below).
5526 kt = TypeVarType(
5527 "KT",
5528 "KT",
5529 id=TypeVarId(-1, namespace="<dict>"),
5530 values=[],
5531 upper_bound=self.object_type(),
5532 default=AnyType(TypeOfAny.from_omitted_generics),
5533 )
5534 vt = TypeVarType(
5535 "VT",
5536 "VT",
5537 id=TypeVarId(-2, namespace="<dict>"),
5538 values=[],
5539 upper_bound=self.object_type(),
5540 default=AnyType(TypeOfAny.from_omitted_generics),
5541 )
5542
5543 # Collect function arguments, watching out for **expr.
5544 args: list[Expression] = []
5545 expected_types: list[Type] = []
5546 for key, value in e.items:
5547 if key is None:
5548 args.append(value)
5549 expected_types.append(
5550 self.chk.named_generic_type("_typeshed.SupportsKeysAndGetItem", [kt, vt])
5551 )
5552 else:
5553 tup = TupleExpr([key, value])
5554 if key.line >= 0:
5555 tup.line = key.line
5556 tup.column = key.column
5557 else:
5558 tup.line = value.line
5559 tup.column = value.column
5560 tup.end_line = value.end_line
5561 tup.end_column = value.end_column
5562 args.append(tup)
5563 expected_types.append(TupleType([kt, vt], self.named_type("builtins.tuple")))
5564
5565 # The callable type represents a function like this (except we adjust for **expr):
5566 # def <dict>(*v: Tuple[kt, vt]) -> Dict[kt, vt]: ...
5567 constructor = CallableType(
5568 expected_types,
5569 [nodes.ARG_POS] * len(expected_types),
5570 [None] * len(expected_types),
5571 self.chk.named_generic_type("builtins.dict", [kt, vt]),
5572 self.named_type("builtins.function"),
5573 name="<dict>",
5574 variables=[kt, vt],
5575 )
5576 return self.check_call(constructor, args, [nodes.ARG_POS] * len(args), e)[0]
5577
5578 def find_typeddict_context(
5579 self, context: Type | None, dict_expr: DictExpr
5580 ) -> tuple[list[TypedDictType], bool]:
5581 """Extract `TypedDict` members of the enclosing context.
5582
5583 Returns:
5584 a 2-tuple, (found_candidates, is_exhaustive)
5585 """
5586 context = get_proper_type(context)
5587 if isinstance(context, TypedDictType):
5588 return [context], True
5589 elif isinstance(context, UnionType):
5590 items = []
5591 exhaustive = True
5592 for item in context.items:
5593 item_contexts, item_exhaustive = self.find_typeddict_context(item, dict_expr)
5594 for item_context in item_contexts:
5595 if self.match_typeddict_call_with_dict(
5596 item_context, dict_expr.items, dict_expr
5597 ):
5598 items.append(item_context)
5599 exhaustive = exhaustive and item_exhaustive
5600 return items, exhaustive
5601 # No TypedDict type in context.
5602 return [], False
5603
5604 def visit_template_str_expr(self, e: TemplateStrExpr) -> Type:
5605 """Type check a template string expression (t-string).
5606
5607 Type-checks all interpolated expressions but the result is always
5608 string.templatelib.Template.
5609 """
5610 for item in e.items:
5611 if isinstance(item, tuple):
5612 value_expr, _source, _conversion, format_spec = item
5613 self.accept(value_expr)
5614 if format_spec is not None:
5615 self.accept(format_spec)
5616 sym = lookup_fully_qualified("string.templatelib.Template", self.chk.modules)
5617 if sym is not None and isinstance(sym.node, TypeInfo):
5618 return Instance(sym.node, [])
5619 return AnyType(TypeOfAny.from_error)
5620
5621 def visit_lambda_expr(self, e: LambdaExpr) -> Type:
5622 """Type check lambda expression."""
5623 old_in_lambda = self.in_lambda_expr
5624 self.in_lambda_expr = True
5625 self.chk.check_default_params(e, body_is_trivial=False)
5626 inferred_type, type_override = self.infer_lambda_type_using_context(e)
5627 if not inferred_type:
5628 self.chk.return_types.append(AnyType(TypeOfAny.special_form))
5629 # Type check everything in the body except for the final return
5630 # statement (it can contain tuple unpacking before return).
5631 with (
5632 self.chk.binder.frame_context(can_skip=True, fall_through=0),
5633 self.chk.scope.push_function(e),
5634 ):
5635 # If in empty context, reset argument types (from previous passes),
5636 # in the other branch argument types are set by check_func_def().
5637 for arg in e.arguments:
5638 arg.variable.type = None
5639 # Lambdas can have more than one element in body,
5640 # when we add "fictional" AssignmentStatement nodes, like in:
5641 # `lambda (a, b): a`
5642 for stmt in e.body.body[:-1]:
5643 stmt.accept(self.chk)
5644 # Only type check the return expression, not the return statement.
5645 # There's no useful type context.
5646 ret_type = self.accept(e.expr(), allow_none_return=True)
5647 fallback = self.named_type("builtins.function")
5648 self.chk.return_types.pop()
5649 self.in_lambda_expr = old_in_lambda
5650 return callable_type(e, fallback, ret_type)
5651 else:
5652 # Type context available.
5653 self.chk.return_types.append(inferred_type.ret_type)
5654 with self.chk.tscope.function_scope(e):
5655 self.chk.check_func_item(e, type_override=type_override)
5656 if not self.chk.has_type(e.expr()):
5657 # TODO: return expression must be accepted before exiting function scope.
5658 with self.chk.binder.frame_context(can_skip=True, fall_through=0):
5659 self.accept(e.expr(), allow_none_return=True)
5660 ret_type = self.chk.lookup_type(e.expr())
5661 self.chk.return_types.pop()
5662 self.in_lambda_expr = old_in_lambda
5663 return replace_callable_return_type(inferred_type, ret_type)
5664
5665 def infer_lambda_type_using_context(
5666 self, e: LambdaExpr
5667 ) -> tuple[CallableType | None, CallableType | None]:
5668 """Try to infer lambda expression type using context.
5669
5670 Return None if could not infer type.
5671 The second item in the return type is the type_override parameter for check_func_item.
5672 """
5673 # TODO also accept 'Any' context
5674 ctx = get_proper_type(self.type_context[-1])
5675
5676 if isinstance(ctx, UnionType):
5677 callables = [
5678 t for t in get_proper_types(ctx.relevant_items()) if isinstance(t, CallableType)
5679 ]
5680 if len(callables) == 1:
5681 ctx = callables[0]
5682
5683 if not ctx or not isinstance(ctx, CallableType):
5684 return None, None
5685
5686 # The context may have function type variables in it. We replace them
5687 # since these are the type variables we are ultimately trying to infer;
5688 # they must be considered as indeterminate. We use ErasedType since it
5689 # does not affect type inference results (it is for purposes like this
5690 # only).
5691 if not self.chk.options.old_type_inference:
5692 # With new type inference we can preserve argument types even if they
5693 # are generic, since new inference algorithm can handle constraints
5694 # like S <: T (we still erase return type since it's ultimately unknown).
5695 extra_vars = []
5696 for arg in ctx.arg_types:
5697 meta_vars = [tv for tv in get_all_type_vars(arg) if tv.id.is_meta_var()]
5698 extra_vars.extend([tv for tv in meta_vars if tv not in extra_vars])
5699 callable_ctx = ctx.copy_modified(
5700 ret_type=replace_meta_vars(ctx.ret_type, ErasedType()),
5701 variables=list(ctx.variables) + extra_vars,
5702 )
5703 else:
5704 erased_ctx = replace_meta_vars(ctx, ErasedType())
5705 assert isinstance(erased_ctx, ProperType) and isinstance(erased_ctx, CallableType)
5706 callable_ctx = erased_ctx
5707
5708 # The callable_ctx may have a fallback of builtins.type if the context
5709 # is a constructor -- but this fallback doesn't make sense for lambdas.
5710 callable_ctx = callable_ctx.copy_modified(fallback=self.named_type("builtins.function"))
5711
5712 if callable_ctx.type_guard is not None or callable_ctx.type_is is not None:
5713 # Lambda's return type cannot be treated as a `TypeGuard`,
5714 # because it is implicit. And `TypeGuard`s must be explicit.
5715 # See https://github.com/python/mypy/issues/9927
5716 return None, None
5717
5718 arg_kinds = [arg.kind for arg in e.arguments]
5719
5720 if callable_ctx.is_ellipsis_args or ctx.param_spec() is not None:
5721 # Fill in Any arguments to match the arguments of the lambda.
5722 callable_ctx = callable_ctx.copy_modified(
5723 is_ellipsis_args=False,
5724 arg_types=[AnyType(TypeOfAny.special_form)] * len(arg_kinds),
5725 arg_kinds=arg_kinds,
5726 arg_names=e.arg_names.copy(),
5727 )
5728
5729 if ARG_STAR in arg_kinds or ARG_STAR2 in arg_kinds:
5730 # TODO treat this case appropriately
5731 return callable_ctx, None
5732
5733 if callable_ctx.arg_kinds != arg_kinds:
5734 # Incompatible context; cannot use it to infer types.
5735 self.chk.fail(message_registry.CANNOT_INFER_LAMBDA_TYPE, e)
5736 return None, None
5737
5738 # Type of lambda must have correct argument names, to prevent false
5739 # negatives when lambdas appear in `ParamSpec` context.
5740 return callable_ctx.copy_modified(arg_names=e.arg_names), callable_ctx
5741
5742 def visit_super_expr(self, e: SuperExpr) -> Type:
5743 """Type check a super expression (non-lvalue)."""
5744
5745 # We have an expression like super(T, var).member
5746
5747 # First compute the types of T and var
5748 types = self._super_arg_types(e)
5749 if isinstance(types, tuple):
5750 type_type, instance_type = types
5751 else:
5752 return types
5753
5754 # Now get the MRO
5755 type_info = type_info_from_type(type_type)
5756 if type_info is None:
5757 self.chk.fail(message_registry.UNSUPPORTED_ARG_1_FOR_SUPER, e)
5758 return AnyType(TypeOfAny.from_error)
5759
5760 instance_info = type_info_from_type(instance_type)
5761 if instance_info is None:
5762 self.chk.fail(message_registry.UNSUPPORTED_ARG_2_FOR_SUPER, e)
5763 return AnyType(TypeOfAny.from_error)
5764
5765 mro = instance_info.mro
5766
5767 # The base is the first MRO entry *after* type_info that has a member
5768 # with the right name
5769 index = None
5770 if type_info in mro:
5771 index = mro.index(type_info)
5772 else:
5773 method = self.chk.scope.current_function()
5774 # Mypy explicitly allows supertype upper bounds (and no upper bound at all)
5775 # for annotating self-types. However, if such an annotation is used for
5776 # checking super() we will still get an error. So to be consistent, we also
5777 # allow such imprecise annotations for use with super(), where we fall back
5778 # to the current class MRO instead. This works only from inside a method.
5779 if method is not None and is_self_type_like(
5780 instance_type, is_classmethod=method.is_class
5781 ):
5782 if e.info and type_info in e.info.mro:
5783 mro = e.info.mro
5784 index = mro.index(type_info)
5785 if index is None:
5786 if (
5787 instance_info.is_protocol
5788 and instance_info != type_info
5789 and not type_info.is_protocol
5790 ):
5791 # A special case for mixins, in this case super() should point
5792 # directly to the host protocol, this is not safe, since the real MRO
5793 # is not known yet for mixin, but this feature is more like an escape hatch.
5794 index = -1
5795 else:
5796 self.chk.fail(message_registry.SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1, e)
5797 return AnyType(TypeOfAny.from_error)
5798
5799 if len(mro) == index + 1:
5800 self.chk.fail(message_registry.TARGET_CLASS_HAS_NO_BASE_CLASS, e)
5801 return AnyType(TypeOfAny.from_error)
5802
5803 for base in mro[index + 1 :]:
5804 if e.name in base.names or base == mro[-1]:
5805 if e.info and e.info.fallback_to_any and base == mro[-1]:
5806 # There's an undefined base class, and we're at the end of the
5807 # chain. That's not an error.
5808 return AnyType(TypeOfAny.special_form)
5809
5810 return analyze_member_access(
5811 name=e.name,
5812 typ=instance_type,
5813 is_lvalue=False,
5814 is_super=True,
5815 is_operator=False,
5816 original_type=instance_type,
5817 override_info=base,
5818 context=e,
5819 chk=self.chk,
5820 in_literal_context=self.is_literal_context(),
5821 )
5822
5823 assert False, "unreachable"
5824
5825 def _super_arg_types(self, e: SuperExpr) -> Type | tuple[Type, Type]:
5826 """
5827 Computes the types of the type and instance expressions in super(T, instance), or the
5828 implicit ones for zero-argument super() expressions. Returns a single type for the whole
5829 super expression when possible (for errors, anys), otherwise the pair of computed types.
5830 """
5831
5832 if not self.chk.in_checked_function():
5833 return AnyType(TypeOfAny.unannotated)
5834 elif len(e.call.args) == 0:
5835 if not e.info:
5836 # This has already been reported by the semantic analyzer.
5837 return AnyType(TypeOfAny.from_error)
5838 elif self.chk.scope.active_class():
5839 self.chk.fail(message_registry.SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED, e)
5840 return AnyType(TypeOfAny.from_error)
5841
5842 # Zero-argument super() is like super(<current class>, <self>)
5843 current_type = fill_typevars(e.info)
5844 type_type: ProperType = TypeType(current_type)
5845
5846 # Use the type of the self argument, in case it was annotated
5847 method = self.chk.scope.current_function()
5848 assert method is not None
5849 if method.arguments:
5850 instance_type: Type = method.arguments[0].variable.type or current_type
5851 else:
5852 self.chk.fail(message_registry.SUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED, e)
5853 return AnyType(TypeOfAny.from_error)
5854 elif ARG_STAR in e.call.arg_kinds:
5855 self.chk.fail(message_registry.SUPER_VARARGS_NOT_SUPPORTED, e)
5856 return AnyType(TypeOfAny.from_error)
5857 elif set(e.call.arg_kinds) != {ARG_POS}:
5858 self.chk.fail(message_registry.SUPER_POSITIONAL_ARGS_REQUIRED, e)
5859 return AnyType(TypeOfAny.from_error)
5860 elif len(e.call.args) == 1:
5861 self.chk.fail(message_registry.SUPER_WITH_SINGLE_ARG_NOT_SUPPORTED, e)
5862 return AnyType(TypeOfAny.from_error)
5863 elif len(e.call.args) == 2:
5864 type_type = get_proper_type(self.accept(e.call.args[0]))
5865 instance_type = self.accept(e.call.args[1])
5866 else:
5867 self.chk.fail(message_registry.TOO_MANY_ARGS_FOR_SUPER, e)
5868 return AnyType(TypeOfAny.from_error)
5869
5870 # Imprecisely assume that the type is the current class
5871 if isinstance(type_type, AnyType):
5872 if e.info:
5873 type_type = TypeType(fill_typevars(e.info))
5874 else:
5875 return AnyType(TypeOfAny.from_another_any, source_any=type_type)
5876 elif isinstance(type_type, TypeType):
5877 type_item = type_type.item
5878 if isinstance(type_item, AnyType):
5879 if e.info:
5880 type_type = TypeType(fill_typevars(e.info))
5881 else:
5882 return AnyType(TypeOfAny.from_another_any, source_any=type_item)
5883
5884 if not isinstance(type_type, TypeType) and not (
5885 isinstance(type_type, FunctionLike) and type_type.is_type_obj()
5886 ):
5887 self.msg.first_argument_for_super_must_be_type(type_type, e)
5888 return AnyType(TypeOfAny.from_error)
5889
5890 # Imprecisely assume that the instance is of the current class
5891 instance_type = get_proper_type(instance_type)
5892 if isinstance(instance_type, AnyType):
5893 if e.info:
5894 instance_type = fill_typevars(e.info)
5895 else:
5896 return AnyType(TypeOfAny.from_another_any, source_any=instance_type)
5897 elif isinstance(instance_type, TypeType):
5898 instance_item = instance_type.item
5899 if isinstance(instance_item, AnyType):
5900 if e.info:
5901 instance_type = TypeType(fill_typevars(e.info))
5902 else:
5903 return AnyType(TypeOfAny.from_another_any, source_any=instance_item)
5904
5905 return type_type, instance_type
5906
5907 def visit_slice_expr(self, e: SliceExpr) -> Type:
5908 type_args = []
5909 for index in [e.begin_index, e.end_index, e.stride]:
5910 if index:
5911 type_args.append(self.accept(index))
5912 else:
5913 type_args.append(NoneType())
5914 return self.chk.named_generic_type("builtins.slice", type_args)
5915
5916 def visit_list_comprehension(self, e: ListComprehension) -> Type:
5917 return self.check_generator_or_comprehension(
5918 e.generator, "builtins.list", "<list-comprehension>"
5919 )
5920
5921 def visit_set_comprehension(self, e: SetComprehension) -> Type:
5922 return self.check_generator_or_comprehension(
5923 e.generator, "builtins.set", "<set-comprehension>"
5924 )
5925
5926 def visit_generator_expr(self, e: GeneratorExpr) -> Type:
5927 # If any of the comprehensions use async for, the expression will return an async generator
5928 # object, or await is used anywhere but in the leftmost sequence.
5929 if (
5930 any(e.is_async)
5931 or has_await_expression(e.left_expr)
5932 or any(has_await_expression(sequence) for sequence in e.sequences[1:])
5933 or any(has_await_expression(cond) for condlist in e.condlists for cond in condlist)
5934 ):
5935 typ = "typing.AsyncGenerator"
5936 # received type is always None in async generator expressions
5937 additional_args: list[Type] = [NoneType()]
5938 else:
5939 typ = "typing.Generator"
5940 # received type and returned type are None
5941 additional_args = [NoneType(), NoneType()]
5942 return self.check_generator_or_comprehension(
5943 e, typ, "<generator>", additional_args=additional_args
5944 )
5945
5946 def check_generator_or_comprehension(
5947 self,
5948 gen: GeneratorExpr,
5949 type_name: str,
5950 id_for_messages: str,
5951 additional_args: list[Type] | None = None,
5952 ) -> Type:
5953 """Type check a generator expression or a list comprehension."""
5954 additional_args = additional_args or []
5955 with self.chk.binder.frame_context(can_skip=True, fall_through=0):
5956 self.check_for_comp(gen)
5957
5958 # Infer the type of the list comprehension by using a synthetic generic
5959 # callable type.
5960 tv = TypeVarType(
5961 "T",
5962 "T",
5963 id=TypeVarId(-1, namespace="<genexp>"),
5964 values=[],
5965 upper_bound=self.object_type(),
5966 default=AnyType(TypeOfAny.from_omitted_generics),
5967 )
5968 tv_list: list[Type] = [tv]
5969 constructor = CallableType(
5970 tv_list,
5971 [nodes.ARG_POS],
5972 [None],
5973 self.chk.named_generic_type(type_name, tv_list + additional_args),
5974 self.chk.named_type("builtins.function"),
5975 name=id_for_messages,
5976 variables=[tv],
5977 )
5978 return self.check_call(constructor, [gen.left_expr], [nodes.ARG_POS], gen)[0]
5979
5980 def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type:
5981 """Type check a dictionary comprehension."""
5982 with self.chk.binder.frame_context(can_skip=True, fall_through=0):
5983 self.check_for_comp(e)
5984
5985 # Infer the type of the list comprehension by using a synthetic generic
5986 # callable type.
5987 ktdef = TypeVarType(
5988 "KT",
5989 "KT",
5990 id=TypeVarId(-1, namespace="<dict>"),
5991 values=[],
5992 upper_bound=self.object_type(),
5993 default=AnyType(TypeOfAny.from_omitted_generics),
5994 )
5995 vtdef = TypeVarType(
5996 "VT",
5997 "VT",
5998 id=TypeVarId(-2, namespace="<dict>"),
5999 values=[],
6000 upper_bound=self.object_type(),
6001 default=AnyType(TypeOfAny.from_omitted_generics),
6002 )
6003 constructor = CallableType(
6004 [ktdef, vtdef],
6005 [nodes.ARG_POS, nodes.ARG_POS],
6006 [None, None],
6007 self.chk.named_generic_type("builtins.dict", [ktdef, vtdef]),
6008 self.chk.named_type("builtins.function"),
6009 name="<dictionary-comprehension>",
6010 variables=[ktdef, vtdef],
6011 )
6012 return self.check_call(
6013 constructor, [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e
6014 )[0]
6015
6016 def check_for_comp(self, e: GeneratorExpr | DictionaryComprehension) -> None:
6017 """Check the for_comp part of comprehensions. That is the part from 'for':
6018 ... for x in y if z
6019
6020 Note: This adds the type information derived from the condlists to the current binder.
6021 """
6022 for index, sequence, conditions, is_async in zip(
6023 e.indices, e.sequences, e.condlists, e.is_async
6024 ):
6025 if is_async:
6026 _, sequence_type = self.chk.analyze_async_iterable_item_type(sequence)
6027 else:
6028 _, sequence_type = self.chk.analyze_iterable_item_type(sequence)
6029 if (
6030 isinstance(get_proper_type(sequence_type), UninhabitedType)
6031 and isinstance(index, NameExpr)
6032 and index.name == "_"
6033 ):
6034 # To preserve backward compatibility, avoid inferring Never for "_"
6035 sequence_type = AnyType(TypeOfAny.special_form)
6036
6037 self.chk.analyze_index_variables(index, sequence_type, True, e)
6038 for condition in conditions:
6039 self.accept(condition)
6040
6041 # values are only part of the comprehension when all conditions are true
6042 true_map, false_map = self.chk.find_isinstance_check(condition)
6043 self.chk.push_type_map(true_map)
6044
6045 if codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes:
6046 if mypy.checker.is_unreachable_map(true_map):
6047 self.msg.redundant_condition_in_comprehension(False, condition)
6048 elif mypy.checker.is_unreachable_map(false_map):
6049 self.msg.redundant_condition_in_comprehension(True, condition)
6050
6051 def visit_conditional_expr(self, e: ConditionalExpr, allow_none_return: bool = False) -> Type:
6052 self.accept(e.cond)
6053 ctx: Type | None = self.type_context[-1]
6054
6055 # Gain type information from isinstance if it is there
6056 # but only for the current expression
6057 if_map, else_map = self.chk.find_isinstance_check(e.cond)
6058 if codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes:
6059 if mypy.checker.is_unreachable_map(if_map):
6060 self.msg.redundant_condition_in_if(False, e.cond)
6061 elif mypy.checker.is_unreachable_map(else_map):
6062 self.msg.redundant_condition_in_if(True, e.cond)
6063
6064 if ctx is None:
6065 # When no context is provided, compute each branch individually, and
6066 # use the union of the results as artificial context. Important for:
6067 # - testUnificationDict
6068 # - testConditionalExpressionWithEmpty
6069 ctx_if_type = self.analyze_cond_branch(
6070 if_map, e.if_expr, context=ctx, allow_none_return=allow_none_return
6071 )
6072 ctx_else_type = self.analyze_cond_branch(
6073 else_map, e.else_expr, context=ctx, allow_none_return=allow_none_return
6074 )
6075 if has_ambiguous_uninhabited_component(ctx_if_type):
6076 ctx = ctx_else_type
6077 elif has_ambiguous_uninhabited_component(ctx_else_type):
6078 ctx = ctx_if_type
6079 else:
6080 ctx = make_simplified_union([ctx_if_type, ctx_else_type])
6081
6082 if_type = self.analyze_cond_branch(
6083 if_map, e.if_expr, context=ctx, allow_none_return=allow_none_return
6084 )
6085 else_type = self.analyze_cond_branch(
6086 else_map, e.else_expr, context=ctx, allow_none_return=allow_none_return
6087 )
6088
6089 res: Type = make_simplified_union([if_type, else_type])
6090 if has_uninhabited_component(res) and not isinstance(
6091 get_proper_type(self.type_context[-1]), UnionType
6092 ):
6093 # In rare cases with empty collections join may give a better result.
6094 alternative = join.join_types(if_type, else_type)
6095 p_alt = get_proper_type(alternative)
6096 if not isinstance(p_alt, Instance) or p_alt.type.fullname != "builtins.object":
6097 res = alternative
6098 return res
6099
6100 def analyze_cond_branch(
6101 self,
6102 map: dict[Expression, Type],
6103 node: Expression,
6104 context: Type | None,
6105 allow_none_return: bool = False,
6106 suppress_unreachable_errors: bool = True,
6107 ) -> Type:
6108 with self.chk.binder.frame_context(can_skip=True, fall_through=0):
6109 if mypy.checker.is_unreachable_map(map):
6110 # We still need to type check node, in case we want to
6111 # process it for isinstance checks later. Since the branch was
6112 # determined to be unreachable, any errors should be suppressed.
6113 with self.msg.filter_errors(filter_errors=suppress_unreachable_errors):
6114 self.accept(node, type_context=context, allow_none_return=allow_none_return)
6115 return UninhabitedType()
6116 self.chk.push_type_map(map)
6117 return self.accept(node, type_context=context, allow_none_return=allow_none_return)
6118
6119 def _combined_context(self, ty: Type | None) -> Type | None:
6120 ctx_items = []
6121 if ty is not None:
6122 if has_any_type(ty):
6123 # HACK: Any should be contagious, `dict[str, Any] or <x>` should still
6124 # infer Any in x.
6125 return ty
6126 ctx_items.append(ty)
6127 if self.type_context and self.type_context[-1] is not None:
6128 ctx_items.append(self.type_context[-1])
6129 if ctx_items:
6130 return make_simplified_union(ctx_items)
6131 return None
6132
6133 #
6134 # Helpers
6135 #
6136
6137 def accept(
6138 self,
6139 node: Expression,
6140 type_context: Type | None = None,
6141 allow_none_return: bool = False,
6142 always_allow_any: bool = False,
6143 is_callee: bool = False,
6144 ) -> Type:
6145 """Type check a node in the given type context. If allow_none_return
6146 is True and this expression is a call, allow it to return None. This
6147 applies only to this expression and not any subexpressions.
6148 """
6149 if node in self.type_overrides:
6150 # This branch is very fast, there is no point timing it.
6151 return self.type_overrides[node]
6152 # We don't use context manager here to get most precise data (and avoid overhead).
6153 record_time = False
6154 if self.collect_line_checking_stats and not self.in_expression:
6155 t0 = time.perf_counter_ns()
6156 self.in_expression = True
6157 record_time = True
6158 self.type_context.append(type_context)
6159 old_is_callee = self.is_callee
6160 self.is_callee = is_callee
6161 try:
6162 p_type_context = get_proper_type(type_context)
6163 if allow_none_return and isinstance(node, CallExpr):
6164 typ = self.visit_call_expr(node, allow_none_return=True)
6165 elif allow_none_return and isinstance(node, YieldFromExpr):
6166 typ = self.visit_yield_from_expr(node, allow_none_return=True)
6167 elif allow_none_return and isinstance(node, ConditionalExpr):
6168 typ = self.visit_conditional_expr(node, allow_none_return=True)
6169 elif allow_none_return and isinstance(node, AwaitExpr):
6170 typ = self.visit_await_expr(node, allow_none_return=True)
6171
6172 elif (
6173 isinstance(p_type_context, TypeType)
6174 and p_type_context.is_type_form
6175 and (node_as_type := self.try_parse_as_type_expression(node)) is not None
6176 ):
6177 typ = TypeType.make_normalized(
6178 node_as_type,
6179 line=node_as_type.line,
6180 column=node_as_type.column,
6181 is_type_form=True,
6182 ) # r-value type, when interpreted as a type expression
6183 elif (
6184 isinstance(p_type_context, UnionType)
6185 and any(
6186 isinstance(p_item := get_proper_type(item), TypeType) and p_item.is_type_form
6187 for item in p_type_context.items
6188 )
6189 and (node_as_type := self.try_parse_as_type_expression(node)) is not None
6190 ):
6191 typ1 = TypeType.make_normalized(
6192 node_as_type,
6193 line=node_as_type.line,
6194 column=node_as_type.column,
6195 is_type_form=True,
6196 )
6197 if is_subtype(typ1, p_type_context):
6198 typ = typ1 # r-value type, when interpreted as a type expression
6199 else:
6200 typ2 = node.accept(self)
6201 typ = typ2 # r-value type, when interpreted as a value expression
6202 # Deeply nested generic calls can deteriorate performance dramatically.
6203 # Although in most cases caching makes little difference, in worst case
6204 # it avoids exponential complexity.
6205 # We cannot use cache inside lambdas, because they skip immediate type
6206 # context, and use enclosing one, see infer_lambda_type_using_context().
6207 # TODO: consider using cache for more expression kinds.
6208 elif (
6209 isinstance(node, (CallExpr, ListExpr, TupleExpr, DictExpr, OpExpr))
6210 and not (self.in_lambda_expr or self.chk.current_node_deferred)
6211 and not self.chk.options.disable_expression_cache
6212 ):
6213 if (node, type_context) in self.expr_cache:
6214 binder_version, typ, messages, type_map = self.expr_cache[(node, type_context)]
6215 if binder_version == self.chk.binder.version:
6216 self.chk.store_types(type_map)
6217 self.msg.add_errors(messages)
6218 else:
6219 typ = self.accept_maybe_cache(node, type_context=type_context)
6220 else:
6221 typ = self.accept_maybe_cache(node, type_context=type_context)
6222 else:
6223 typ = node.accept(self) # r-value type, when interpreted as a value expression
6224 except Exception as err:
6225 report_internal_error(
6226 err, self.chk.errors.file, node.line, self.chk.errors, self.chk.options
6227 )
6228 self.is_callee = old_is_callee
6229 self.type_context.pop()
6230 assert typ is not None
6231 self.chk.store_type(node, typ)
6232
6233 if (
6234 self.chk.options.disallow_any_expr
6235 and not always_allow_any
6236 and not self.chk.is_stub
6237 and self.chk.in_checked_function()
6238 and has_any_type(typ)
6239 and not self.chk.current_node_deferred
6240 ):
6241 self.msg.disallowed_any_type(typ, node)
6242
6243 if not self.chk.in_checked_function() or self.chk.current_node_deferred:
6244 result: Type = AnyType(TypeOfAny.unannotated)
6245 else:
6246 result = typ
6247 if record_time:
6248 self.per_line_checking_time_ns[node.line] += time.perf_counter_ns() - t0
6249 self.in_expression = False
6250 return result
6251
6252 def accept_maybe_cache(self, node: Expression, type_context: Type | None = None) -> Type:
6253 binder_version = self.chk.binder.version
6254 with self.msg.filter_errors(filter_errors=True, save_filtered_errors=True) as msg:
6255 with self.chk.local_type_map as type_map:
6256 typ = node.accept(self)
6257 messages = msg.filtered_errors()
6258 if binder_version == self.chk.binder.version and not self.chk.current_node_deferred:
6259 self.expr_cache[(node, type_context)] = (binder_version, typ, messages, type_map)
6260 self.chk.store_types(type_map)
6261 self.msg.add_errors(messages)
6262 return typ
6263
6264 def named_type(self, name: str) -> Instance:
6265 """Return an instance type with type given by the name and no type
6266 arguments. Alias for TypeChecker.named_type.
6267 """
6268 return self.chk.named_type(name)
6269
6270 def type_alias_type_type(self) -> Instance:
6271 """Returns a `typing.TypeAliasType` or `typing_extensions.TypeAliasType`."""
6272 if self.chk.options.python_version >= (3, 12):
6273 return self.named_type("typing.TypeAliasType")
6274 return self.named_type("typing_extensions.TypeAliasType")
6275
6276 def is_valid_var_arg(self, typ: Type) -> bool:
6277 """Is a type valid as a *args argument?"""
6278 typ = get_proper_type(typ)
6279 return isinstance(typ, (TupleType, AnyType, ParamSpecType, UnpackType)) or is_subtype(
6280 typ, self.chk.named_generic_type("typing.Iterable", [AnyType(TypeOfAny.special_form)])
6281 )
6282
6283 def is_valid_keyword_var_arg(self, typ: Type) -> bool:
6284 """Is a type valid as a **kwargs argument?"""
6285 typ = get_proper_type(typ)
6286 return (
6287 (
6288 # This is a little ad hoc, ideally we would have a map_instance_to_supertype
6289 # that worked for protocols
6290 isinstance(typ, Instance)
6291 and typ.type.fullname == "builtins.dict"
6292 and is_subtype(typ.args[0], self.named_type("builtins.str"))
6293 )
6294 or isinstance(typ, ParamSpecType)
6295 or is_subtype(
6296 typ,
6297 self.chk.named_generic_type(
6298 "_typeshed.SupportsKeysAndGetItem",
6299 [self.named_type("builtins.str"), AnyType(TypeOfAny.special_form)],
6300 ),
6301 )
6302 or is_subtype(
6303 typ,
6304 self.chk.named_generic_type(
6305 "_typeshed.SupportsKeysAndGetItem", [UninhabitedType(), UninhabitedType()]
6306 ),
6307 )
6308 )
6309
6310 def not_ready_callback(self, name: str, context: Context) -> None:
6311 """Called when we can't infer the type of a variable because it's not ready yet.
6312
6313 Either defer type checking of the enclosing function to the next
6314 pass or report an error.
6315 """
6316 self.chk.handle_cannot_determine_type(name, context)
6317
6318 def visit_yield_expr(self, e: YieldExpr) -> Type:
6319 return_type = self.chk.return_types[-1]
6320 expected_item_type = self.chk.get_generator_yield_type(return_type, False)
6321 if e.expr is None:
6322 if (
6323 not isinstance(get_proper_type(expected_item_type), (NoneType, AnyType))
6324 and self.chk.in_checked_function()
6325 ):
6326 self.chk.fail(message_registry.YIELD_VALUE_EXPECTED, e)
6327 else:
6328 actual_item_type = self.accept(e.expr, expected_item_type)
6329 self.chk.check_subtype(
6330 actual_item_type,
6331 expected_item_type,
6332 e,
6333 message_registry.INCOMPATIBLE_TYPES_IN_YIELD,
6334 "actual type",
6335 "expected type",
6336 )
6337 return self.chk.get_generator_receive_type(return_type, False)
6338
6339 def visit_await_expr(self, e: AwaitExpr, allow_none_return: bool = False) -> Type:
6340 expected_type = self.type_context[-1]
6341 if expected_type is not None:
6342 expected_type = self.chk.named_generic_type("typing.Awaitable", [expected_type])
6343 actual_type = get_proper_type(self.accept(e.expr, expected_type))
6344 if isinstance(actual_type, AnyType):
6345 return AnyType(TypeOfAny.from_another_any, source_any=actual_type)
6346 ret = self.check_awaitable_expr(
6347 actual_type, e, message_registry.INCOMPATIBLE_TYPES_IN_AWAIT
6348 )
6349 if not allow_none_return and isinstance(get_proper_type(ret), NoneType):
6350 self.chk.msg.does_not_return_value(None, e)
6351 return ret
6352
6353 def check_awaitable_expr(
6354 self, t: Type, ctx: Context, msg: str | ErrorMessage, ignore_binder: bool = False
6355 ) -> Type:
6356 """Check the argument to `await` and extract the type of value.
6357
6358 Also used by `async for` and `async with`.
6359 """
6360 if not self.chk.check_subtype(
6361 t, self.named_type("typing.Awaitable"), ctx, msg, "actual type", "expected type"
6362 ):
6363 return AnyType(TypeOfAny.special_form)
6364 else:
6365 generator = self.check_method_call_by_name("__await__", t, [], [], ctx)[0]
6366 ret_type = self.chk.get_generator_return_type(generator, False)
6367 ret_type = get_proper_type(ret_type)
6368 if (
6369 not ignore_binder
6370 and isinstance(ret_type, UninhabitedType)
6371 and not ret_type.ambiguous
6372 ):
6373 self.chk.binder.unreachable()
6374 return ret_type
6375
6376 def visit_yield_from_expr(self, e: YieldFromExpr, allow_none_return: bool = False) -> Type:
6377 # NOTE: Whether `yield from` accepts an `async def` decorated
6378 # with `@types.coroutine` (or `@asyncio.coroutine`) depends on
6379 # whether the generator containing the `yield from` is itself
6380 # thus decorated. But it accepts a generator regardless of
6381 # how it's decorated.
6382 return_type = self.chk.return_types[-1]
6383 # TODO: What should the context for the sub-expression be?
6384 # If the containing function has type Generator[X, Y, ...],
6385 # the context should be Generator[X, Y, T], where T is the
6386 # context of the 'yield from' itself (but it isn't known).
6387 subexpr_type = get_proper_type(self.accept(e.expr))
6388
6389 # Check that the expr is an instance of Iterable and get the type of the iterator produced
6390 # by __iter__.
6391 if isinstance(subexpr_type, AnyType):
6392 iter_type: Type = AnyType(TypeOfAny.from_another_any, source_any=subexpr_type)
6393 elif self.chk.type_is_iterable(subexpr_type):
6394 if is_async_def(subexpr_type) and not has_coroutine_decorator(return_type):
6395 self.chk.msg.yield_from_invalid_operand_type(subexpr_type, e)
6396
6397 any_type = AnyType(TypeOfAny.special_form)
6398 generic_generator_type = self.chk.named_generic_type(
6399 "typing.Generator", [any_type, any_type, any_type]
6400 )
6401 generic_generator_type.set_line(e)
6402 iter_type, _ = self.check_method_call_by_name(
6403 "__iter__", subexpr_type, [], [], context=generic_generator_type
6404 )
6405 else:
6406 if not (is_async_def(subexpr_type) and has_coroutine_decorator(return_type)):
6407 self.chk.msg.yield_from_invalid_operand_type(subexpr_type, e)
6408 iter_type = AnyType(TypeOfAny.from_error)
6409 else:
6410 iter_type = self.check_awaitable_expr(
6411 subexpr_type, e, message_registry.INCOMPATIBLE_TYPES_IN_YIELD_FROM
6412 )
6413
6414 # Check that the iterator's item type matches the type yielded by the Generator function
6415 # containing this `yield from` expression.
6416 expected_item_type = self.chk.get_generator_yield_type(return_type, False)
6417 actual_item_type = self.chk.get_generator_yield_type(iter_type, False)
6418
6419 self.chk.check_subtype(
6420 actual_item_type,
6421 expected_item_type,
6422 e,
6423 message_registry.INCOMPATIBLE_TYPES_IN_YIELD_FROM,
6424 "actual type",
6425 "expected type",
6426 )
6427
6428 # Determine the type of the entire yield from expression.
6429 iter_type = get_proper_type(iter_type)
6430 expr_type = self.chk.get_generator_return_type(iter_type, is_coroutine=False)
6431
6432 if not allow_none_return and isinstance(get_proper_type(expr_type), NoneType):
6433 self.chk.msg.does_not_return_value(None, e)
6434 return expr_type
6435
6436 def visit_temp_node(self, e: TempNode) -> Type:
6437 return e.type
6438
6439 def visit_type_var_expr(self, e: TypeVarExpr) -> Type:
6440 p_default = get_proper_type(e.default)
6441 if not (
6442 isinstance(p_default, AnyType)
6443 and p_default.type_of_any == TypeOfAny.from_omitted_generics
6444 ):
6445 if not is_subtype(p_default, e.upper_bound):
6446 self.chk.fail("TypeVar default must be a subtype of the bound type", e)
6447 if e.values and not any(is_same_type(p_default, value) for value in e.values):
6448 self.chk.fail("TypeVar default must be one of the constraint types", e)
6449 return AnyType(TypeOfAny.special_form)
6450
6451 def visit_paramspec_expr(self, e: ParamSpecExpr) -> Type:
6452 return AnyType(TypeOfAny.special_form)
6453
6454 def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> Type:
6455 return AnyType(TypeOfAny.special_form)
6456
6457 def visit_newtype_expr(self, e: NewTypeExpr) -> Type:
6458 return AnyType(TypeOfAny.special_form)
6459
6460 def visit_namedtuple_expr(self, e: NamedTupleExpr) -> Type:
6461 tuple_type = e.info.tuple_type
6462 if tuple_type:
6463 if self.chk.options.disallow_any_unimported and has_any_from_unimported_type(
6464 tuple_type
6465 ):
6466 self.msg.unimported_type_becomes_any("NamedTuple type", tuple_type, e)
6467 check_for_explicit_any(
6468 tuple_type, self.chk.options, self.chk.is_typeshed_stub, self.msg, context=e
6469 )
6470 return AnyType(TypeOfAny.special_form)
6471
6472 def visit_enum_call_expr(self, e: EnumCallExpr) -> Type:
6473 for name, value in zip(e.items, e.values):
6474 if value is not None:
6475 typ = self.accept(value)
6476 if not isinstance(get_proper_type(typ), AnyType):
6477 var = e.info.names[name].node
6478 if isinstance(var, Var):
6479 # Inline TypeChecker.set_inferred_type(),
6480 # without the lvalue. (This doesn't really do
6481 # much, since the value attribute is defined
6482 # to have type Any in the typeshed stub.)
6483 var.type = typ
6484 var.is_inferred = True
6485 return AnyType(TypeOfAny.special_form)
6486
6487 def visit_typeddict_expr(self, e: TypedDictExpr) -> Type:
6488 return AnyType(TypeOfAny.special_form)
6489
6490 def visit__promote_expr(self, e: PromoteExpr) -> Type:
6491 return e.type
6492
6493 def visit_star_expr(self, e: StarExpr) -> Type:
6494 # TODO: should this ever be called (see e.g. mypyc visitor)?
6495 return self.accept(e.expr)
6496
6497 def object_type(self) -> Instance:
6498 """Return instance type 'object'."""
6499 return self.named_type("builtins.object")
6500
6501 def bool_type(self) -> Instance:
6502 """Return instance type 'bool'."""
6503 return self.named_type("builtins.bool")
6504
6505 @overload
6506 def narrow_type_from_binder(self, expr: Expression, known_type: Type) -> Type: ...
6507
6508 @overload
6509 def narrow_type_from_binder(
6510 self, expr: Expression, known_type: Type, skip_non_overlapping: bool
6511 ) -> Type | None: ...
6512
6513 def narrow_type_from_binder(
6514 self, expr: Expression, known_type: Type, skip_non_overlapping: bool = False
6515 ) -> Type | None:
6516 """Narrow down a known type of expression using information in conditional type binder.
6517
6518 If 'skip_non_overlapping' is True, return None if the type and restriction are
6519 non-overlapping.
6520 """
6521 if literal(expr) >= LITERAL_TYPE:
6522 restriction = self.chk.binder.get(expr)
6523 # If the current node is deferred, some variables may get Any types that they
6524 # otherwise wouldn't have. We don't want to narrow down these since it may
6525 # produce invalid inferred Optional[Any] types, at least.
6526 if restriction and not (
6527 isinstance(get_proper_type(known_type), AnyType) and self.chk.current_node_deferred
6528 ):
6529 # Note: this call should match the one in narrow_declared_type().
6530 if skip_non_overlapping and not is_overlapping_types(known_type, restriction):
6531 return None
6532 narrowed = narrow_declared_type(known_type, restriction)
6533 if isinstance(get_proper_type(narrowed), UninhabitedType):
6534 # If we hit this case, it means that we can't reliably mark the code as
6535 # unreachable, but the resulting type can't be expressed in type system.
6536 # Falling back to restriction is more intuitive in most cases.
6537 return restriction
6538 return narrowed
6539 return known_type
6540
6541 def has_abstract_type_part(self, caller_type: ProperType, callee_type: ProperType) -> bool:
6542 # TODO: support other possible types here
6543 if isinstance(caller_type, TupleType) and isinstance(callee_type, TupleType):
6544 return any(
6545 self.has_abstract_type(get_proper_type(caller), get_proper_type(callee))
6546 for caller, callee in zip(caller_type.items, callee_type.items)
6547 )
6548 return self.has_abstract_type(caller_type, callee_type)
6549
6550 def has_abstract_type(self, caller_type: ProperType, callee_type: ProperType) -> bool:
6551 return (
6552 isinstance(caller_type, FunctionLike)
6553 and isinstance(callee_type, TypeType)
6554 and caller_type.is_type_obj()
6555 and (caller_type.type_object().is_abstract or caller_type.type_object().is_protocol)
6556 and isinstance(callee_type.item, Instance)
6557 and (callee_type.item.type.is_abstract or callee_type.item.type.is_protocol)
6558 and not self.chk.allow_abstract_call
6559 )
6560
6561 def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> Type | None:
6562 """Try to parse a value Expression as a type expression.
6563 If success then return the type that it spells.
6564 If fails then return None.
6565
6566 A value expression that is parsable as a type expression may be used
6567 where a TypeForm is expected to represent the spelled type.
6568
6569 Unlike SemanticAnalyzer.try_parse_as_type_expression()
6570 (used in the earlier SemanticAnalyzer pass), this function can only
6571 recognize type expressions which contain no string annotations."""
6572 if not isinstance(maybe_type_expr, MaybeTypeExpression):
6573 return None
6574
6575 # Check whether it has already been parsed as a type expression
6576 # by SemanticAnalyzer.try_parse_as_type_expression(),
6577 # perhaps containing a string annotation
6578 if (
6579 isinstance(maybe_type_expr, (StrExpr, IndexExpr, OpExpr))
6580 and maybe_type_expr.as_type != NotParsed.VALUE
6581 ):
6582 return maybe_type_expr.as_type
6583
6584 # If is potentially a type expression containing a string annotation,
6585 # don't try to parse it because there isn't enough information
6586 # available to the TypeChecker pass to resolve string annotations
6587 if has_str_expression(maybe_type_expr):
6588 self.chk.fail(
6589 "TypeForm containing a string annotation cannot be recognized here. "
6590 "Surround with TypeForm(...) to recognize.",
6591 maybe_type_expr,
6592 code=codes.MAYBE_UNRECOGNIZED_STR_TYPEFORM,
6593 )
6594 return None
6595
6596 # Collect symbols targeted by NameExprs and MemberExprs,
6597 # to be looked up by TypeAnalyser when binding the
6598 # UnboundTypes corresponding to those expressions.
6599 name_exprs, member_exprs = all_name_and_member_expressions(maybe_type_expr)
6600 sym_for_name = {e.name: SymbolTableNode(UNBOUND_IMPORTED, e.node) for e in name_exprs} | {
6601 e_name: SymbolTableNode(UNBOUND_IMPORTED, e.node)
6602 for e in member_exprs
6603 if (e_name := get_member_expr_fullname(e)) is not None
6604 }
6605
6606 chk_sem = mypy.checker.TypeCheckerAsSemanticAnalyzer(self.chk, sym_for_name)
6607 tpan = TypeAnalyser(
6608 chk_sem,
6609 # NOTE: Will never need to lookup type vars in this scope because
6610 # SemanticAnalyzer.try_parse_as_type_expression() will have
6611 # already recognized any type var referenced in a NameExpr.
6612 # String annotations (which may also reference type vars)
6613 # can't be resolved in the TypeChecker pass anyway.
6614 TypeVarLikeScope(), # empty scope
6615 self.plugin,
6616 self.chk.options,
6617 self.chk.tree,
6618 self.chk.is_typeshed_stub,
6619 )
6620
6621 try:
6622 typ1 = expr_to_unanalyzed_type(
6623 maybe_type_expr, self.chk.options, self.chk.is_typeshed_stub
6624 )
6625 typ2 = typ1.accept(tpan)
6626 if chk_sem.did_fail:
6627 return None
6628 return typ2
6629 except TypeTranslationError:
6630 return None
6631
6632
6633 def has_any_type(t: Type, ignore_in_type_obj: bool = False) -> bool:
6634 """Whether t contains an Any type"""
6635 return t.accept(HasAnyType(ignore_in_type_obj))
6636
6637
6638 class HasAnyType(types.BoolTypeQuery):
6639 def __init__(self, ignore_in_type_obj: bool) -> None:
6640 super().__init__(types.ANY_STRATEGY)
6641 self.ignore_in_type_obj = ignore_in_type_obj
6642
6643 def visit_any(self, t: AnyType) -> bool:
6644 return t.type_of_any != TypeOfAny.special_form # special forms are not real Any types
6645
6646 def visit_callable_type(self, t: CallableType) -> bool:
6647 if self.ignore_in_type_obj and t.is_type_obj():
6648 return False
6649 return super().visit_callable_type(t)
6650
6651 def visit_type_var(self, t: TypeVarType) -> bool:
6652 default = [t.default] if t.has_default() else []
6653 return self.query_types([t.upper_bound, *default] + t.values)
6654
6655 def visit_param_spec(self, t: ParamSpecType) -> bool:
6656 default = [t.default] if t.has_default() else []
6657 return self.query_types([t.upper_bound, *default, t.prefix])
6658
6659 def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:
6660 default = [t.default] if t.has_default() else []
6661 return self.query_types([t.upper_bound, *default])
6662
6663
6664 def has_coroutine_decorator(t: Type) -> bool:
6665 """Whether t came from a function decorated with `@coroutine`."""
6666 t = get_proper_type(t)
6667 return isinstance(t, Instance) and t.type.fullname == "typing.AwaitableGenerator"
6668
6669
6670 def is_async_def(t: Type) -> bool:
6671 """Whether t came from a function defined using `async def`."""
6672 # In check_func_def(), when we see a function decorated with
6673 # `@typing.coroutine` or `@async.coroutine`, we change the
6674 # return type to typing.AwaitableGenerator[...], so that its
6675 # type is compatible with either Generator or Awaitable.
6676 # But for the check here we need to know whether the original
6677 # function (before decoration) was an `async def`. The
6678 # AwaitableGenerator type conveniently preserves the original
6679 # type as its 4th parameter (3rd when using 0-origin indexing
6680 # :-), so that we can recover that information here.
6681 # (We really need to see whether the original, undecorated
6682 # function was an `async def`, which is orthogonal to its
6683 # decorations.)
6684 t = get_proper_type(t)
6685 if (
6686 isinstance(t, Instance)
6687 and t.type.fullname == "typing.AwaitableGenerator"
6688 and len(t.args) >= 4
6689 ):
6690 t = get_proper_type(t.args[3])
6691 return isinstance(t, Instance) and t.type.fullname == "typing.Coroutine"
6692
6693
6694 def is_non_empty_tuple(t: Type) -> bool:
6695 t = get_proper_type(t)
6696 return isinstance(t, TupleType) and bool(t.items)
6697
6698
6699 def is_duplicate_mapping(
6700 mapping: list[int], actual_types: list[Type], actual_kinds: list[ArgKind]
6701 ) -> bool:
6702 return (
6703 len(mapping) > 1
6704 # Multiple actuals can map to the same formal if they both come from
6705 # varargs (*args and **kwargs); in this case at runtime it is possible
6706 # that here are no duplicates. We need to allow this, as the convention
6707 # f(..., *args, **kwargs) is common enough.
6708 and not (
6709 len(mapping) == 2
6710 and actual_kinds[mapping[0]] == nodes.ARG_STAR
6711 and actual_kinds[mapping[1]] == nodes.ARG_STAR2
6712 )
6713 # Multiple actuals can map to the same formal if there are multiple
6714 # **kwargs which cannot be mapped with certainty (non-TypedDict
6715 # **kwargs).
6716 and not all(
6717 actual_kinds[m] == nodes.ARG_STAR2
6718 and not isinstance(get_proper_type(actual_types[m]), TypedDictType)
6719 for m in mapping
6720 )
6721 )
6722
6723
6724 def replace_callable_return_type(c: CallableType, new_ret_type: Type) -> CallableType:
6725 """Return a copy of a callable type with a different return type."""
6726 return c.copy_modified(ret_type=new_ret_type)
6727
6728
6729 class ArgInferSecondPassQuery(types.BoolTypeQuery):
6730 """Query whether an argument type should be inferred in the second pass.
6731
6732 The result is True if the type has a type variable in a callable return
6733 type anywhere. For example, the result for Callable[[], T] is True if t is
6734 a type variable.
6735 """
6736
6737 def __init__(self) -> None:
6738 super().__init__(types.ANY_STRATEGY)
6739
6740 def visit_callable_type(self, t: CallableType) -> bool:
6741 # TODO: we need to check only for type variables of original callable.
6742 return self.query_types(t.arg_types) or has_type_vars(t)
6743
6744
6745 def has_erased_component(t: Type | None) -> bool:
6746 return t is not None and t.accept(HasErasedComponentsQuery())
6747
6748
6749 class HasErasedComponentsQuery(types.BoolTypeQuery):
6750 """Visitor for querying whether a type has an erased component."""
6751
6752 def __init__(self) -> None:
6753 super().__init__(types.ANY_STRATEGY)
6754
6755 def visit_erased_type(self, t: ErasedType) -> bool:
6756 return True
6757
6758
6759 def has_uninhabited_component(t: Type | None) -> bool:
6760 return t is not None and t.accept(HasUninhabitedComponentsQuery())
6761
6762
6763 class HasUninhabitedComponentsQuery(types.BoolTypeQuery):
6764 """Visitor for querying whether a type has an UninhabitedType component."""
6765
6766 def __init__(self) -> None:
6767 super().__init__(types.ANY_STRATEGY)
6768
6769 def visit_uninhabited_type(self, t: UninhabitedType) -> bool:
6770 return True
6771
6772
6773 def has_ambiguous_uninhabited_component(t: Type | None) -> bool:
6774 return t is not None and t.accept(HasAmbiguousUninhabitedComponentsQuery())
6775
6776
6777 class HasAmbiguousUninhabitedComponentsQuery(types.BoolTypeQuery):
6778 """Visitor for querying whether a type has an ambiguous UninhabitedType component."""
6779
6780 def __init__(self) -> None:
6781 super().__init__(types.ANY_STRATEGY)
6782
6783 def visit_uninhabited_type(self, t: UninhabitedType) -> bool:
6784 return t.ambiguous
6785
6786
6787 def arg_approximate_similarity(actual: Type, formal: Type) -> bool:
6788 """Return if caller argument (actual) is roughly compatible with signature arg (formal).
6789
6790 This function is deliberately loose and will report two types are similar
6791 as long as their "shapes" are plausibly the same.
6792
6793 This is useful when we're doing error reporting: for example, if we're trying
6794 to select an overload alternative and there's no exact match, we can use
6795 this function to help us identify which alternative the user might have
6796 *meant* to match.
6797 """
6798 actual = get_proper_type(actual)
6799 formal = get_proper_type(formal)
6800
6801 # Erase typevars: we'll consider them all to have the same "shape".
6802 if isinstance(actual, TypeVarType):
6803 actual = erase_to_union_or_bound(actual)
6804 if isinstance(formal, TypeVarType):
6805 formal = erase_to_union_or_bound(formal)
6806
6807 # Callable or Type[...]-ish types
6808 def is_typetype_like(typ: ProperType) -> bool:
6809 return (
6810 isinstance(typ, TypeType)
6811 or (isinstance(typ, FunctionLike) and typ.is_type_obj())
6812 or (isinstance(typ, Instance) and typ.type.fullname == "builtins.type")
6813 )
6814
6815 if isinstance(formal, CallableType):
6816 if isinstance(actual, (CallableType, Overloaded, TypeType)):
6817 return True
6818 if is_typetype_like(actual) and is_typetype_like(formal):
6819 return True
6820
6821 # Unions
6822 if isinstance(actual, UnionType):
6823 return any(arg_approximate_similarity(item, formal) for item in actual.relevant_items())
6824 if isinstance(formal, UnionType):
6825 return any(arg_approximate_similarity(actual, item) for item in formal.relevant_items())
6826
6827 # TypedDicts
6828 if isinstance(actual, TypedDictType):
6829 if isinstance(formal, TypedDictType):
6830 return True
6831 return arg_approximate_similarity(actual.fallback, formal)
6832
6833 # Instances
6834 # For instances, we mostly defer to the existing is_subtype check.
6835 if isinstance(formal, Instance):
6836 if isinstance(actual, CallableType):
6837 actual = actual.fallback
6838 if isinstance(actual, Overloaded):
6839 actual = actual.items[0].fallback
6840 if isinstance(actual, TupleType):
6841 actual = tuple_fallback(actual)
6842 if isinstance(actual, Instance) and formal.type in actual.type.mro:
6843 # Try performing a quick check as an optimization
6844 return True
6845
6846 # Fall back to a standard subtype check for the remaining kinds of type.
6847 return is_subtype(erasetype.erase_type(actual), erasetype.erase_type(formal))
6848
6849
6850 def any_causes_overload_ambiguity(
6851 items: list[CallableType],
6852 return_types: list[Type],
6853 arg_types: list[Type],
6854 arg_kinds: list[ArgKind],
6855 arg_names: Sequence[str | None] | None,
6856 ) -> bool:
6857 """May an argument containing 'Any' cause ambiguous result type on call to overloaded function?
6858
6859 Note that this sometimes returns True even if there is no ambiguity, since a correct
6860 implementation would be complex (and the call would be imprecisely typed due to Any
6861 types anyway).
6862
6863 Args:
6864 items: Overload items matching the actual arguments
6865 arg_types: Actual argument types
6866 arg_kinds: Actual argument kinds
6867 arg_names: Actual argument names
6868 """
6869 if all_same_types(return_types):
6870 return False
6871
6872 actual_to_formal = [
6873 map_formals_to_actuals(
6874 arg_kinds, arg_names, item.arg_kinds, item.arg_names, lambda i: arg_types[i]
6875 )
6876 for item in items
6877 ]
6878
6879 for arg_idx, arg_type in enumerate(arg_types):
6880 # We ignore Anys in type object callables as ambiguity
6881 # creators, since that can lead to falsely claiming ambiguity
6882 # for overloads between Type and Callable.
6883 if has_any_type(arg_type, ignore_in_type_obj=True):
6884 matching_formals_unfiltered = [
6885 (item_idx, lookup[arg_idx])
6886 for item_idx, lookup in enumerate(actual_to_formal)
6887 if lookup[arg_idx]
6888 ]
6889
6890 matching_returns = []
6891 matching_formals = []
6892 for item_idx, formals in matching_formals_unfiltered:
6893 matched_callable = items[item_idx]
6894 matching_returns.append(matched_callable.ret_type)
6895
6896 # Note: if an actual maps to multiple formals of differing types within
6897 # a single callable, then we know at least one of those formals must be
6898 # a different type then the formal(s) in some other callable.
6899 # So it's safe to just append everything to the same list.
6900 for formal in formals:
6901 matching_formals.append(matched_callable.arg_types[formal])
6902 if not all_same_types(matching_formals) and not all_same_types(matching_returns):
6903 # Any maps to multiple different types, and the return types of these items differ.
6904 return True
6905 return False
6906
6907
6908 def all_same_types(types: list[Type]) -> bool:
6909 if not types:
6910 return True
6911 return all(is_same_type(t, types[0]) for t in types[1:])
6912
6913
6914 def merge_typevars_in_callables_by_name(
6915 callables: Sequence[CallableType],
6916 ) -> tuple[list[CallableType], list[TypeVarType]]:
6917 """Takes all the typevars present in the callables and 'combines' the ones with the same name.
6918
6919 For example, suppose we have two callables with signatures "f(x: T, y: S) -> T" and
6920 "f(x: List[Tuple[T, S]]) -> Tuple[T, S]". Both callables use typevars named "T" and
6921 "S", but we treat them as distinct, unrelated typevars. (E.g. they could both have
6922 distinct ids.)
6923
6924 If we pass in both callables into this function, it returns a list containing two
6925 new callables that are identical in signature, but use the same underlying TypeVarType
6926 for T and S.
6927
6928 This is useful if we want to take the output lists and "merge" them into one callable
6929 in some way -- for example, when unioning together overloads.
6930
6931 Returns both the new list of callables and a list of all distinct TypeVarType objects used.
6932 """
6933 output: list[CallableType] = []
6934 unique_typevars: dict[str, TypeVarType] = {}
6935 variables: list[TypeVarType] = []
6936
6937 for target in callables:
6938 if target.is_generic():
6939 target = freshen_function_type_vars(target)
6940
6941 rename = {} # Dict[TypeVarId, TypeVar]
6942 for tv in target.variables:
6943 name = tv.fullname
6944 if name not in unique_typevars:
6945 # TODO: support ParamSpecType and TypeVarTuple.
6946 if isinstance(tv, (ParamSpecType, TypeVarTupleType)):
6947 continue
6948 assert isinstance(tv, TypeVarType)
6949 unique_typevars[name] = tv
6950 variables.append(tv)
6951 rename[tv.id] = unique_typevars[name]
6952
6953 target = expand_type(target, rename)
6954 output.append(target)
6955
6956 return output, variables
6957
6958
6959 def try_getting_literal(typ: Type) -> ProperType:
6960 """If possible, get a more precise literal type for a given type."""
6961 typ = get_proper_type(typ)
6962 if isinstance(typ, Instance) and typ.last_known_value is not None:
6963 return typ.last_known_value
6964 return typ
6965
6966
6967 def is_expr_literal_type(node: Expression) -> bool:
6968 """Returns 'true' if the given node is a Literal"""
6969 if isinstance(node, IndexExpr):
6970 base = node.base
6971 return isinstance(base, RefExpr) and base.fullname in LITERAL_TYPE_NAMES
6972 if isinstance(node, NameExpr):
6973 underlying = node.node
6974 return isinstance(underlying, TypeAlias) and isinstance(
6975 get_proper_type(underlying.target), LiteralType
6976 )
6977 return False
6978
6979
6980 def has_bytes_component(typ: Type) -> bool:
6981 """Is this one of builtin byte types, or a union that contains it?"""
6982 typ = get_proper_type(typ)
6983 byte_types = {"builtins.bytes", "builtins.bytearray"}
6984 if isinstance(typ, UnionType):
6985 return any(has_bytes_component(t) for t in typ.items)
6986 if isinstance(typ, Instance) and typ.type.fullname in byte_types:
6987 return True
6988 return False
6989
6990
6991 def type_info_from_type(typ: Type) -> TypeInfo | None:
6992 """Gets the TypeInfo for a type, indirecting through things like type variables and tuples."""
6993 typ = get_proper_type(typ)
6994 if isinstance(typ, FunctionLike) and typ.is_type_obj():
6995 return typ.type_object()
6996 if isinstance(typ, TypeType):
6997 typ = typ.item
6998 if isinstance(typ, TypeVarType):
6999 typ = get_proper_type(typ.upper_bound)
7000 if isinstance(typ, TupleType):
7001 typ = tuple_fallback(typ)
7002 if isinstance(typ, Instance):
7003 return typ.type
7004
7005 # A complicated type. Too tricky, give up.
7006 # TODO: Do something more clever here.
7007 return None
7008
7009
7010 def is_operator_method(fullname: str | None) -> bool:
7011 if not fullname:
7012 return False
7013 short_name = fullname.split(".")[-1]
7014 return (
7015 short_name in operators.op_methods.values()
7016 or short_name in operators.reverse_op_methods.values()
7017 or short_name in operators.unary_op_methods.values()
7018 )
7019
7020
7021 def get_partial_instance_type(t: Type | None) -> PartialType | None:
7022 if t is None or not isinstance(t, PartialType) or t.type is None:
7023 return None
7024 return t
7025
7026
7027 def is_type_type_context(context: Type | None) -> bool:
7028 context = get_proper_type(context)
7029 if isinstance(context, TypeType):
7030 return True
7031 if isinstance(context, UnionType):
7032 return any(is_type_type_context(item) for item in context.items)
7033 return False