Debian Codegraph @

mypy/types.py

raw
1 """Classes for representing mypy types."""
2
3 from __future__ import annotations
4
5 import sys
6 from abc import abstractmethod
7 from collections.abc import Iterable, Sequence
8 from typing import (
9 Any,
10 ClassVar,
11 Final,
12 NamedTuple,
13 NewType,
14 TypeAlias as _TypeAlias,
15 TypeGuard,
16 TypeVar,
17 cast,
18 overload,
19 )
20 from typing_extensions import Self
21
22 from librt.internal import (
23 read_int as read_int_bare,
24 read_str as read_str_bare,
25 write_int as write_int_bare,
26 write_str as write_str_bare,
27 )
28
29 import mypy.nodes
30 from mypy.bogus_type import Bogus
31 from mypy.cache import (
32 DICT_STR_GEN,
33 END_TAG,
34 EXTRA_ATTRS,
35 LIST_GEN,
36 LITERAL_NONE,
37 ReadBuffer,
38 Tag,
39 WriteBuffer,
40 read_bool,
41 read_flags,
42 read_int,
43 read_int_list,
44 read_literal,
45 read_str,
46 read_str_list,
47 read_str_opt,
48 read_str_opt_list,
49 read_tag,
50 write_bool,
51 write_flags,
52 write_int,
53 write_int_list,
54 write_literal,
55 write_str,
56 write_str_list,
57 write_str_opt,
58 write_str_opt_list,
59 write_tag,
60 )
61 from mypy.nodes import ARG_KINDS, ARG_POS, ARG_STAR, ARG_STAR2, INVARIANT, ArgKind, SymbolNode
62 from mypy.options import Options
63 from mypy.state import state
64 from mypy.util import IdMapper
65
66 T = TypeVar("T")
67
68 JsonDict: _TypeAlias = dict[str, Any]
69
70 # The set of all valid expressions that can currently be contained
71 # inside of a Literal[...].
72 #
73 # Literals can contain bytes and enum-values: we special-case both of these
74 # and store the value as a string. We rely on the fallback type that's also
75 # stored with the Literal to determine how a string is being used.
76 #
77 # TODO: confirm that we're happy with representing enums (and the
78 # other types) in the manner described above.
79 #
80 # Note: if we change the set of types included below, we must also
81 # make sure to audit the following methods:
82 #
83 # 1. types.LiteralType's serialize and deserialize methods: this method
84 # needs to make sure it can convert the below types into JSON and back.
85 #
86 # 2. types.LiteralType's 'value_repr` method: this method is ultimately used
87 # by TypeStrVisitor's visit_literal_type to generate a reasonable
88 # repr-able output.
89 #
90 # 3. server.astdiff.SnapshotTypeVisitor's visit_literal_type_method: this
91 # method assumes that the following types supports equality checks and
92 # hashability.
93 #
94 # Note: Although "Literal[None]" is a valid type, we internally always convert
95 # such a type directly into "None". So, "None" is not a valid parameter of
96 # LiteralType and is omitted from this list.
97 #
98 # Note: Float values are only used internally. They are not accepted within
99 # Literal[...].
100 LiteralValue: _TypeAlias = int | str | bool | float
101
102
103 TUPLE_NAMES: Final = ("builtins.tuple", "typing.Tuple")
104 TYPE_NAMES: Final = ("builtins.type", "typing.Type")
105
106 TYPE_VAR_LIKE_NAMES: Final = (
107 "typing.TypeVar",
108 "typing_extensions.TypeVar",
109 "typing.ParamSpec",
110 "typing_extensions.ParamSpec",
111 "typing.TypeVarTuple",
112 "typing_extensions.TypeVarTuple",
113 )
114
115 TYPED_NAMEDTUPLE_NAMES: Final = ("typing.NamedTuple", "typing_extensions.NamedTuple")
116
117 # Supported names of TypedDict type constructors.
118 TPDICT_NAMES: Final = (
119 "typing.TypedDict",
120 "typing_extensions.TypedDict",
121 "mypy_extensions.TypedDict",
122 )
123
124 # Supported fallback instance type names for TypedDict types.
125 TPDICT_FB_NAMES: Final = (
126 "typing._TypedDict",
127 "typing_extensions._TypedDict",
128 "mypy_extensions._TypedDict",
129 )
130
131 # Supported names of Protocol base class.
132 PROTOCOL_NAMES: Final = ("typing.Protocol", "typing_extensions.Protocol")
133
134 # Supported TypeAlias names.
135 TYPE_ALIAS_NAMES: Final = ("typing.TypeAlias", "typing_extensions.TypeAlias")
136
137 # Supported Final type names.
138 FINAL_TYPE_NAMES: Final = ("typing.Final", "typing_extensions.Final")
139
140 # Supported @final decorator names.
141 FINAL_DECORATOR_NAMES: Final = ("typing.final", "typing_extensions.final")
142
143 # Supported @type_check_only names.
144 TYPE_CHECK_ONLY_NAMES: Final = ("typing.type_check_only", "typing_extensions.type_check_only")
145
146 # Supported Literal type names.
147 LITERAL_TYPE_NAMES: Final = ("typing.Literal", "typing_extensions.Literal")
148
149 # Supported Annotated type names.
150 ANNOTATED_TYPE_NAMES: Final = ("typing.Annotated", "typing_extensions.Annotated")
151
152 # Supported Concatenate type names.
153 CONCATENATE_TYPE_NAMES: Final = ("typing.Concatenate", "typing_extensions.Concatenate")
154
155 # Supported Unpack type names.
156 UNPACK_TYPE_NAMES: Final = ("typing.Unpack", "typing_extensions.Unpack")
157
158 # Supported @deprecated decorator names
159 DEPRECATED_TYPE_NAMES: Final = ("warnings.deprecated", "typing_extensions.deprecated")
160
161 # Supported @disjoint_base decorator names
162 DISJOINT_BASE_DECORATOR_NAMES: Final = ("typing.disjoint_base", "typing_extensions.disjoint_base")
163
164 # We use this constant in various places when checking `tuple` subtyping:
165 TUPLE_LIKE_INSTANCE_NAMES: Final = (
166 "builtins.tuple",
167 "typing.Iterable",
168 "typing.Container",
169 "typing.Sequence",
170 "typing.Reversible",
171 )
172
173 IMPORTED_REVEAL_TYPE_NAMES: Final = ("typing.reveal_type", "typing_extensions.reveal_type")
174 REVEAL_TYPE_NAMES: Final = ("builtins.reveal_type", *IMPORTED_REVEAL_TYPE_NAMES)
175
176 ASSERT_TYPE_NAMES: Final = ("typing.assert_type", "typing_extensions.assert_type")
177
178 OVERLOAD_NAMES: Final = ("typing.overload", "typing_extensions.overload")
179
180 NEVER_NAMES: Final = (
181 "typing.NoReturn",
182 "typing_extensions.NoReturn",
183 "mypy_extensions.NoReturn",
184 "typing.Never",
185 "typing_extensions.Never",
186 )
187
188 # Mypyc fixed-width native int types (compatible with builtins.int)
189 MYPYC_NATIVE_INT_NAMES: Final = (
190 "mypy_extensions.i64",
191 "mypy_extensions.i32",
192 "mypy_extensions.i16",
193 "mypy_extensions.u8",
194 )
195
196 DATACLASS_TRANSFORM_NAMES: Final = (
197 "typing.dataclass_transform",
198 "typing_extensions.dataclass_transform",
199 )
200 # Supported @override decorator names.
201 OVERRIDE_DECORATOR_NAMES: Final = ("typing.override", "typing_extensions.override")
202
203 ELLIPSIS_TYPE_NAMES: Final = ("builtins.ellipsis", "types.EllipsisType")
204
205 NOT_IMPLEMENTED_TYPE_NAMES: Final = ("builtins._NotImplementedType", "types.NotImplementedType")
206
207 # A placeholder used for Bogus[...] parameters
208 _dummy: Final[Any] = object()
209
210 # A placeholder for int parameters
211 _dummy_int: Final = -999999
212
213
214 class TypeOfAny:
215 """
216 This class describes different types of Any. Each 'Any' can be of only one type at a time.
217 """
218
219 __slots__ = ()
220
221 # Was this Any type inferred without a type annotation?
222 unannotated: Final = 1
223 # Does this Any come from an explicit type annotation?
224 explicit: Final = 2
225 # Does this come from an unfollowed import? See --disallow-any-unimported option
226 from_unimported_type: Final = 3
227 # Does this Any type come from omitted generics?
228 from_omitted_generics: Final = 4
229 # Does this Any come from an error?
230 from_error: Final = 5
231 # Is this a type that can't be represented in mypy's type system? For instance, type of
232 # call to NewType(...). Even though these types aren't real Anys, we treat them as such.
233 # Also used for variables named '_'.
234 special_form: Final = 6
235 # Does this Any come from interaction with another Any?
236 from_another_any: Final = 7
237 # Does this Any come from an implementation limitation/bug?
238 implementation_artifact: Final = 8
239 # Does this Any come from use in the suggestion engine? This is
240 # used to ignore Anys inserted by the suggestion engine when
241 # generating constraints.
242 suggestion_engine: Final = 9
243
244
245 def deserialize_type(data: JsonDict | str) -> Type:
246 if isinstance(data, str):
247 return Instance.deserialize(data)
248 classname = data[".class"]
249 method = deserialize_map.get(classname)
250 if method is not None:
251 return method(data)
252 raise NotImplementedError(f"unexpected .class {classname}")
253
254
255 class Type(mypy.nodes.Context):
256 """Abstract base class for all types."""
257
258 __slots__ = ("_can_be_true", "_can_be_false")
259 # 'can_be_true' and 'can_be_false' mean whether the value of the
260 # expression can be true or false in a boolean context. They are useful
261 # when inferring the type of logic expressions like `x and y`.
262 #
263 # For example:
264 # * the literal `False` can't be true while `True` can.
265 # * a value with type `bool` can be true or false.
266 # * `None` can't be true
267 # * ...
268
269 def __init__(self, line: int = -1, column: int = -1) -> None:
270 super().__init__(line, column)
271 # Value of these can be -1 (use the default, lazy init), 0 (false) or 1 (true)
272 self._can_be_true = -1
273 self._can_be_false = -1
274
275 @property
276 def can_be_true(self) -> bool:
277 if self._can_be_true == -1: # Lazy init helps mypyc
278 self._can_be_true = self.can_be_true_default()
279 return bool(self._can_be_true)
280
281 @can_be_true.setter
282 def can_be_true(self, v: bool) -> None:
283 self._can_be_true = v
284
285 @property
286 def can_be_false(self) -> bool:
287 if self._can_be_false == -1: # Lazy init helps mypyc
288 self._can_be_false = self.can_be_false_default()
289 return bool(self._can_be_false)
290
291 @can_be_false.setter
292 def can_be_false(self, v: bool) -> None:
293 self._can_be_false = v
294
295 def can_be_true_default(self) -> bool:
296 return True
297
298 def can_be_false_default(self) -> bool:
299 return True
300
301 def accept(self, visitor: TypeVisitor[T]) -> T:
302 raise RuntimeError("Not implemented", type(self))
303
304 def __repr__(self) -> str:
305 return self.accept(TypeStrVisitor(options=Options()))
306
307 def str_with_options(self, options: Options) -> str:
308 return self.accept(TypeStrVisitor(options=options))
309
310 def serialize(self) -> JsonDict | str:
311 raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance")
312
313 @classmethod
314 def deserialize(cls, data: JsonDict) -> Type:
315 raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance")
316
317 def write(self, data: WriteBuffer) -> None:
318 raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance")
319
320 @classmethod
321 def read(cls, data: ReadBuffer) -> Type:
322 raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance")
323
324
325 class TypeAliasType(Type):
326 """A type alias to another type.
327
328 To support recursive type aliases we don't immediately expand a type alias
329 during semantic analysis, but create an instance of this type that records the target alias
330 definition node (mypy.nodes.TypeAlias) and type arguments (for generic aliases).
331
332 This is very similar to how TypeInfo vs Instance interact, where a recursive class-based
333 structure like
334 class Node:
335 value: int
336 children: List[Node]
337 can be represented in a tree-like manner.
338 """
339
340 __slots__ = ("alias", "args", "type_ref")
341
342 def __init__(
343 self,
344 alias: mypy.nodes.TypeAlias | None,
345 args: list[Type],
346 line: int = -1,
347 column: int = -1,
348 ) -> None:
349 super().__init__(line, column)
350 self.alias = alias
351 self.args = args
352 self.type_ref: str | None = None
353
354 def _expand_once(self) -> Type:
355 """Expand to the target type exactly once.
356
357 This doesn't do full expansion, i.e. the result can contain another
358 (or even this same) type alias. Use this internal helper only when really needed,
359 its public wrapper mypy.types.get_proper_type() is preferred.
360 """
361 assert self.alias is not None
362 if self.alias.no_args:
363 # We know that no_args=True aliases like L = List must have an instance
364 # as their target.
365 assert isinstance(self.alias.target, Instance) # type: ignore[misc]
366 return self.alias.target.copy_modified(args=self.args)
367
368 # TODO: this logic duplicates the one in expand_type_by_instance().
369 if self.alias.tvar_tuple_index is None:
370 mapping: dict[TypeVarId, Type] = {
371 v.id: s for (v, s) in zip(self.alias.alias_tvars, self.args)
372 }
373 else:
374 prefix = self.alias.tvar_tuple_index
375 suffix = len(self.alias.alias_tvars) - self.alias.tvar_tuple_index - 1
376 start, middle, end = split_with_prefix_and_suffix(tuple(self.args), prefix, suffix)
377 tvar = self.alias.alias_tvars[prefix]
378 assert isinstance(tvar, TypeVarTupleType)
379 mapping = {tvar.id: TupleType(list(middle), tvar.tuple_fallback)}
380 for tvar, sub in zip(
381 self.alias.alias_tvars[:prefix] + self.alias.alias_tvars[prefix + 1 :], start + end
382 ):
383 mapping[tvar.id] = sub
384
385 return self.alias.target.accept(InstantiateAliasVisitor(mapping))
386
387 @property
388 def is_recursive(self) -> bool:
389 """Whether this type alias is recursive.
390
391 Note this doesn't check generic alias arguments, but only if this alias
392 *definition* is recursive. The property value thus can be cached on the
393 underlying TypeAlias node. If you want to include all nested types, use
394 has_recursive_types() function.
395 """
396 assert self.alias is not None, "Unfixed type alias"
397 is_recursive = self.alias._is_recursive
398 if is_recursive is None:
399 is_recursive = self.alias in self.alias.target.accept(CollectAliasesVisitor())
400 # We cache the value on the underlying TypeAlias node as an optimization,
401 # since the value is the same for all instances of the same alias.
402 self.alias._is_recursive = is_recursive
403 return is_recursive
404
405 def can_be_true_default(self) -> bool:
406 if self.alias is not None:
407 return self.alias.target.can_be_true
408 return super().can_be_true_default()
409
410 def can_be_false_default(self) -> bool:
411 if self.alias is not None:
412 return self.alias.target.can_be_false
413 return super().can_be_false_default()
414
415 def copy_modified(self, *, args: list[Type] | None = None) -> TypeAliasType:
416 return TypeAliasType(
417 self.alias, args if args is not None else self.args.copy(), self.line, self.column
418 )
419
420 def accept(self, visitor: TypeVisitor[T]) -> T:
421 return visitor.visit_type_alias_type(self)
422
423 def __hash__(self) -> int:
424 return hash((self.alias, tuple(self.args)))
425
426 def __eq__(self, other: object) -> bool:
427 # Note: never use this to determine subtype relationships, use is_subtype().
428 if not isinstance(other, TypeAliasType):
429 return NotImplemented
430 return self.alias == other.alias and self.args == other.args
431
432 def serialize(self) -> JsonDict:
433 assert self.alias is not None
434 data: JsonDict = {
435 ".class": "TypeAliasType",
436 "type_ref": self.alias.fullname,
437 "args": [arg.serialize() for arg in self.args],
438 }
439 return data
440
441 @classmethod
442 def deserialize(cls, data: JsonDict) -> TypeAliasType:
443 assert data[".class"] == "TypeAliasType"
444 args: list[Type] = []
445 if "args" in data:
446 args_list = data["args"]
447 assert isinstance(args_list, list)
448 args = [deserialize_type(arg) for arg in args_list]
449 alias = TypeAliasType(None, args)
450 alias.type_ref = data["type_ref"]
451 return alias
452
453 def write(self, data: WriteBuffer) -> None:
454 write_tag(data, TYPE_ALIAS_TYPE)
455 write_type_list(data, self.args)
456 assert self.alias is not None
457 write_str(data, self.alias.fullname)
458 write_tag(data, END_TAG)
459
460 @classmethod
461 def read(cls, data: ReadBuffer) -> TypeAliasType:
462 alias = TypeAliasType(None, read_type_list(data))
463 alias.type_ref = read_str(data)
464 assert read_tag(data) == END_TAG
465 return alias
466
467
468 class TypeGuardedType(Type):
469 """Only used by find_isinstance_check() etc."""
470
471 __slots__ = ("type_guard",)
472
473 def __init__(self, type_guard: Type) -> None:
474 super().__init__(line=type_guard.line, column=type_guard.column)
475 self.type_guard = type_guard
476
477 def __repr__(self) -> str:
478 return f"TypeGuard({self.type_guard})"
479
480 # This may hide some real bugs, but it is convenient for various "synthetic"
481 # visitors, similar to RequiredType and ReadOnlyType below.
482 def accept(self, visitor: TypeVisitor[T]) -> T:
483 return self.type_guard.accept(visitor)
484
485
486 class RequiredType(Type):
487 """Required[T] or NotRequired[T]. Only usable at top-level of a TypedDict definition."""
488
489 def __init__(self, item: Type, *, required: bool) -> None:
490 super().__init__(line=item.line, column=item.column)
491 self.item = item
492 self.required = required
493
494 def __repr__(self) -> str:
495 if self.required:
496 return f"Required[{self.item}]"
497 else:
498 return f"NotRequired[{self.item}]"
499
500 def accept(self, visitor: TypeVisitor[T]) -> T:
501 return self.item.accept(visitor)
502
503
504 class ReadOnlyType(Type):
505 """ReadOnly[T] Only usable at top-level of a TypedDict definition."""
506
507 def __init__(self, item: Type) -> None:
508 super().__init__(line=item.line, column=item.column)
509 self.item = item
510
511 def __repr__(self) -> str:
512 return f"ReadOnly[{self.item}]"
513
514 def accept(self, visitor: TypeVisitor[T]) -> T:
515 return self.item.accept(visitor)
516
517
518 class ProperType(Type):
519 """Not a type alias.
520
521 Every type except TypeAliasType must inherit from this type.
522 """
523
524 __slots__ = ()
525
526
527 class TypeVarId:
528 # A type variable is uniquely identified by its raw id and meta level.
529
530 # For plain variables (type parameters of generic classes and
531 # functions) raw ids are allocated by semantic analysis, using
532 # positive ids 1, 2, ... for generic class parameters and negative
533 # ids -1, ... for generic function type arguments. A special value 0
534 # is reserved for Self type variable (autogenerated). This convention
535 # is only used to keep type variable ids distinct when allocating
536 # them; the type checker makes no distinction between class and
537 # function type variables.
538
539 # Metavariables are allocated unique ids starting from 1.
540 raw_id: Final[int]
541
542 # Level of the variable in type inference. Currently either 0 for
543 # declared types, or 1 for type inference metavariables.
544 meta_level: int = 0
545
546 # Class variable used for allocating fresh ids for metavariables.
547 next_raw_id: ClassVar[int] = 1
548
549 # Fullname of class or function/method which declares this type
550 # variable (not the fullname of the TypeVar definition!), or ''
551 namespace: str
552
553 def __init__(self, raw_id: int, meta_level: int = 0, *, namespace: str = "") -> None:
554 self.raw_id = raw_id
555 self.meta_level = meta_level
556 self.namespace = namespace
557
558 @staticmethod
559 def new(meta_level: int) -> TypeVarId:
560 raw_id = TypeVarId.next_raw_id
561 TypeVarId.next_raw_id += 1
562 return TypeVarId(raw_id, meta_level)
563
564 def __repr__(self) -> str:
565 return self.raw_id.__repr__()
566
567 def __eq__(self, other: object) -> bool:
568 # Although this call is not expensive (like UnionType or TypedDictType),
569 # most of the time we get the same object here, so add a fast path.
570 if self is other:
571 return True
572 return (
573 isinstance(other, TypeVarId)
574 and self.raw_id == other.raw_id
575 and self.meta_level == other.meta_level
576 and self.namespace == other.namespace
577 )
578
579 def __ne__(self, other: object) -> bool:
580 return not (self == other)
581
582 def __hash__(self) -> int:
583 return self.raw_id ^ (self.meta_level << 8) ^ hash(self.namespace)
584
585 def is_meta_var(self) -> bool:
586 return self.meta_level > 0
587
588 def is_self(self) -> bool:
589 # This is a special value indicating typing.Self variable.
590 return self.raw_id == 0
591
592
593 class TypeVarLikeType(ProperType):
594 __slots__ = ("name", "fullname", "id", "upper_bound", "default")
595
596 name: str # Name (may be qualified)
597 fullname: str # Fully qualified name
598 id: TypeVarId
599 upper_bound: Type
600 default: Type
601
602 def __init__(
603 self,
604 name: str,
605 fullname: str,
606 id: TypeVarId,
607 upper_bound: Type,
608 default: Type,
609 line: int = -1,
610 column: int = -1,
611 ) -> None:
612 super().__init__(line, column)
613 self.name = name
614 self.fullname = fullname
615 self.id = id
616 self.upper_bound = upper_bound
617 self.default = default
618
619 def serialize(self) -> JsonDict:
620 raise NotImplementedError
621
622 @classmethod
623 def deserialize(cls, data: JsonDict) -> TypeVarLikeType:
624 raise NotImplementedError
625
626 def copy_modified(self, *, id: TypeVarId, **kwargs: Any) -> Self:
627 raise NotImplementedError
628
629 @classmethod
630 def new_unification_variable(cls, old: Self) -> Self:
631 new_id = TypeVarId.new(meta_level=1)
632 return old.copy_modified(id=new_id)
633
634 def has_default(self) -> bool:
635 t = get_proper_type(self.default)
636 return not (isinstance(t, AnyType) and t.type_of_any == TypeOfAny.from_omitted_generics)
637
638 def values_or_bound(self) -> ProperType:
639 if isinstance(self, TypeVarType) and self.values:
640 return UnionType(self.values)
641 return get_proper_type(self.upper_bound)
642
643
644 class TypeVarType(TypeVarLikeType):
645 """Type that refers to a type variable."""
646
647 __slots__ = ("values", "variance")
648
649 values: list[Type] # Value restriction, empty list if no restriction
650 variance: int
651
652 def __init__(
653 self,
654 name: str,
655 fullname: str,
656 id: TypeVarId,
657 values: list[Type],
658 upper_bound: Type,
659 default: Type,
660 variance: int = INVARIANT,
661 line: int = -1,
662 column: int = -1,
663 ) -> None:
664 super().__init__(name, fullname, id, upper_bound, default, line, column)
665 assert values is not None, "No restrictions must be represented by empty list"
666 self.values = values
667 self.variance = variance
668
669 def copy_modified(
670 self,
671 *,
672 values: Bogus[list[Type]] = _dummy,
673 upper_bound: Bogus[Type] = _dummy,
674 default: Bogus[Type] = _dummy,
675 id: Bogus[TypeVarId] = _dummy,
676 line: int = _dummy_int,
677 column: int = _dummy_int,
678 **kwargs: Any,
679 ) -> TypeVarType:
680 return TypeVarType(
681 name=self.name,
682 fullname=self.fullname,
683 id=self.id if id is _dummy else id,
684 values=self.values if values is _dummy else values,
685 upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound,
686 default=self.default if default is _dummy else default,
687 variance=self.variance,
688 line=self.line if line == _dummy_int else line,
689 column=self.column if column == _dummy_int else column,
690 )
691
692 def accept(self, visitor: TypeVisitor[T]) -> T:
693 return visitor.visit_type_var(self)
694
695 def __hash__(self) -> int:
696 return hash((self.id, self.upper_bound, tuple(self.values)))
697
698 def __eq__(self, other: object) -> bool:
699 if not isinstance(other, TypeVarType):
700 return NotImplemented
701 return (
702 self.id == other.id
703 and self.upper_bound == other.upper_bound
704 and self.values == other.values
705 and self.default == other.default
706 )
707
708 def serialize(self) -> JsonDict:
709 assert not self.id.is_meta_var()
710 return {
711 ".class": "TypeVarType",
712 "name": self.name,
713 "fullname": self.fullname,
714 "id": self.id.raw_id,
715 "namespace": self.id.namespace,
716 "values": [v.serialize() for v in self.values],
717 "upper_bound": self.upper_bound.serialize(),
718 "default": self.default.serialize(),
719 "variance": self.variance,
720 }
721
722 @classmethod
723 def deserialize(cls, data: JsonDict) -> TypeVarType:
724 assert data[".class"] == "TypeVarType"
725 return TypeVarType(
726 name=data["name"],
727 fullname=data["fullname"],
728 id=TypeVarId(data["id"], namespace=data["namespace"]),
729 values=[deserialize_type(v) for v in data["values"]],
730 upper_bound=deserialize_type(data["upper_bound"]),
731 default=deserialize_type(data["default"]),
732 variance=data["variance"],
733 )
734
735 def write(self, data: WriteBuffer) -> None:
736 write_tag(data, TYPE_VAR_TYPE)
737 write_str(data, self.name)
738 write_str(data, self.fullname)
739 write_int(data, self.id.raw_id)
740 write_str(data, self.id.namespace)
741 write_type_list(data, self.values)
742 self.upper_bound.write(data)
743 self.default.write(data)
744 write_int(data, self.variance)
745 write_tag(data, END_TAG)
746
747 @classmethod
748 def read(cls, data: ReadBuffer) -> TypeVarType:
749 ret = TypeVarType(
750 read_str(data),
751 read_str(data),
752 TypeVarId(read_int(data), namespace=read_str(data)),
753 read_type_list(data),
754 read_type(data),
755 read_type(data),
756 read_int(data),
757 )
758 assert read_tag(data) == END_TAG
759 return ret
760
761
762 class ParamSpecFlavor:
763 # Simple ParamSpec reference such as "P"
764 BARE: Final = 0
765 # P.args
766 ARGS: Final = 1
767 # P.kwargs
768 KWARGS: Final = 2
769
770
771 class ParamSpecType(TypeVarLikeType):
772 """Type that refers to a ParamSpec.
773
774 A ParamSpec is a type variable that represents the parameter
775 types, names and kinds of a callable (i.e., the signature without
776 the return type).
777
778 This can be one of these forms
779 * P (ParamSpecFlavor.BARE)
780 * P.args (ParamSpecFlavor.ARGS)
781 * P.kwargs (ParamSpecFLavor.KWARGS)
782
783 The upper_bound is really used as a fallback type -- it's shared
784 with TypeVarType for simplicity. It can't be specified by the user
785 and the value is directly derived from the flavor (currently
786 always just 'object').
787 """
788
789 __slots__ = ("flavor", "prefix")
790
791 flavor: int
792 prefix: Parameters
793
794 def __init__(
795 self,
796 name: str,
797 fullname: str,
798 id: TypeVarId,
799 flavor: int,
800 upper_bound: Type,
801 default: Type,
802 *,
803 line: int = -1,
804 column: int = -1,
805 prefix: Parameters | None = None,
806 ) -> None:
807 super().__init__(name, fullname, id, upper_bound, default, line=line, column=column)
808 self.flavor = flavor
809 self.prefix = prefix or Parameters([], [], [])
810
811 def with_flavor(self, flavor: int) -> ParamSpecType:
812 return ParamSpecType(
813 self.name,
814 self.fullname,
815 self.id,
816 flavor,
817 upper_bound=self.upper_bound,
818 default=self.default,
819 prefix=self.prefix,
820 )
821
822 def copy_modified(
823 self,
824 *,
825 id: Bogus[TypeVarId] = _dummy,
826 flavor: int = _dummy_int,
827 prefix: Bogus[Parameters] = _dummy,
828 default: Bogus[Type] = _dummy,
829 **kwargs: Any,
830 ) -> ParamSpecType:
831 return ParamSpecType(
832 self.name,
833 self.fullname,
834 id if id is not _dummy else self.id,
835 flavor if flavor != _dummy_int else self.flavor,
836 self.upper_bound,
837 default=default if default is not _dummy else self.default,
838 line=self.line,
839 column=self.column,
840 prefix=prefix if prefix is not _dummy else self.prefix,
841 )
842
843 def accept(self, visitor: TypeVisitor[T]) -> T:
844 return visitor.visit_param_spec(self)
845
846 def name_with_suffix(self) -> str:
847 n = self.name
848 if self.flavor == ParamSpecFlavor.ARGS:
849 return f"{n}.args"
850 elif self.flavor == ParamSpecFlavor.KWARGS:
851 return f"{n}.kwargs"
852 return n
853
854 def __hash__(self) -> int:
855 return hash((self.id, self.flavor, self.prefix))
856
857 def __eq__(self, other: object) -> bool:
858 if not isinstance(other, ParamSpecType):
859 return NotImplemented
860 # Upper bound can be ignored, since it's determined by flavor.
861 return (
862 self.id == other.id
863 and self.flavor == other.flavor
864 and self.prefix == other.prefix
865 and self.default == other.default
866 )
867
868 def serialize(self) -> JsonDict:
869 assert not self.id.is_meta_var()
870 return {
871 ".class": "ParamSpecType",
872 "name": self.name,
873 "fullname": self.fullname,
874 "id": self.id.raw_id,
875 "namespace": self.id.namespace,
876 "flavor": self.flavor,
877 "upper_bound": self.upper_bound.serialize(),
878 "default": self.default.serialize(),
879 "prefix": self.prefix.serialize(),
880 }
881
882 @classmethod
883 def deserialize(cls, data: JsonDict) -> ParamSpecType:
884 assert data[".class"] == "ParamSpecType"
885 return ParamSpecType(
886 data["name"],
887 data["fullname"],
888 TypeVarId(data["id"], namespace=data["namespace"]),
889 data["flavor"],
890 deserialize_type(data["upper_bound"]),
891 deserialize_type(data["default"]),
892 prefix=Parameters.deserialize(data["prefix"]),
893 )
894
895 def write(self, data: WriteBuffer) -> None:
896 write_tag(data, PARAM_SPEC_TYPE)
897 self.prefix.write(data)
898 write_str(data, self.name)
899 write_str(data, self.fullname)
900 write_int(data, self.id.raw_id)
901 write_str(data, self.id.namespace)
902 write_int(data, self.flavor)
903 self.upper_bound.write(data)
904 self.default.write(data)
905 write_tag(data, END_TAG)
906
907 @classmethod
908 def read(cls, data: ReadBuffer) -> ParamSpecType:
909 assert read_tag(data) == PARAMETERS
910 prefix = Parameters.read(data)
911 ret = ParamSpecType(
912 read_str(data),
913 read_str(data),
914 TypeVarId(read_int(data), namespace=read_str(data)),
915 read_int(data),
916 read_type(data),
917 read_type(data),
918 prefix=prefix,
919 )
920 assert read_tag(data) == END_TAG
921 return ret
922
923
924 class TypeVarTupleType(TypeVarLikeType):
925 """Type that refers to a TypeVarTuple.
926
927 See PEP646 for more information.
928 """
929
930 __slots__ = ("tuple_fallback", "min_len")
931
932 def __init__(
933 self,
934 name: str,
935 fullname: str,
936 id: TypeVarId,
937 upper_bound: Type,
938 tuple_fallback: Instance,
939 default: Type,
940 *,
941 line: int = -1,
942 column: int = -1,
943 min_len: int = 0,
944 ) -> None:
945 super().__init__(name, fullname, id, upper_bound, default, line=line, column=column)
946 self.tuple_fallback = tuple_fallback
947 # This value is not settable by a user. It is an internal-only thing to support
948 # len()-narrowing of variadic tuples.
949 self.min_len = min_len
950
951 def serialize(self) -> JsonDict:
952 assert not self.id.is_meta_var()
953 return {
954 ".class": "TypeVarTupleType",
955 "name": self.name,
956 "fullname": self.fullname,
957 "id": self.id.raw_id,
958 "namespace": self.id.namespace,
959 "upper_bound": self.upper_bound.serialize(),
960 "tuple_fallback": self.tuple_fallback.serialize(),
961 "default": self.default.serialize(),
962 "min_len": self.min_len,
963 }
964
965 @classmethod
966 def deserialize(cls, data: JsonDict) -> TypeVarTupleType:
967 assert data[".class"] == "TypeVarTupleType"
968 return TypeVarTupleType(
969 data["name"],
970 data["fullname"],
971 TypeVarId(data["id"], namespace=data["namespace"]),
972 deserialize_type(data["upper_bound"]),
973 Instance.deserialize(data["tuple_fallback"]),
974 deserialize_type(data["default"]),
975 min_len=data["min_len"],
976 )
977
978 def write(self, data: WriteBuffer) -> None:
979 write_tag(data, TYPE_VAR_TUPLE_TYPE)
980 self.tuple_fallback.write(data)
981 write_str(data, self.name)
982 write_str(data, self.fullname)
983 write_int(data, self.id.raw_id)
984 write_str(data, self.id.namespace)
985 self.upper_bound.write(data)
986 self.default.write(data)
987 write_int(data, self.min_len)
988 write_tag(data, END_TAG)
989
990 @classmethod
991 def read(cls, data: ReadBuffer) -> TypeVarTupleType:
992 assert read_tag(data) == INSTANCE
993 fallback = Instance.read(data)
994 ret = TypeVarTupleType(
995 read_str(data),
996 read_str(data),
997 TypeVarId(read_int(data), namespace=read_str(data)),
998 read_type(data),
999 fallback,
1000 read_type(data),
1001 min_len=read_int(data),
1002 )
1003 assert read_tag(data) == END_TAG
1004 return ret
1005
1006 def accept(self, visitor: TypeVisitor[T]) -> T:
1007 return visitor.visit_type_var_tuple(self)
1008
1009 def __hash__(self) -> int:
1010 return hash((self.id, self.min_len))
1011
1012 def __eq__(self, other: object) -> bool:
1013 if not isinstance(other, TypeVarTupleType):
1014 return NotImplemented
1015 return (
1016 self.id == other.id and self.min_len == other.min_len and self.default == other.default
1017 )
1018
1019 def copy_modified(
1020 self,
1021 *,
1022 id: Bogus[TypeVarId] = _dummy,
1023 upper_bound: Bogus[Type] = _dummy,
1024 default: Bogus[Type] = _dummy,
1025 min_len: Bogus[int] = _dummy,
1026 **kwargs: Any,
1027 ) -> TypeVarTupleType:
1028 return TypeVarTupleType(
1029 self.name,
1030 self.fullname,
1031 self.id if id is _dummy else id,
1032 self.upper_bound if upper_bound is _dummy else upper_bound,
1033 self.tuple_fallback,
1034 self.default if default is _dummy else default,
1035 line=self.line,
1036 column=self.column,
1037 min_len=self.min_len if min_len is _dummy else min_len,
1038 )
1039
1040
1041 class UnboundType(ProperType):
1042 """Instance type that has not been bound during semantic analysis."""
1043
1044 __slots__ = (
1045 "name",
1046 "args",
1047 "optional",
1048 "empty_tuple_index",
1049 "original_str_expr",
1050 "original_str_fallback",
1051 )
1052
1053 def __init__(
1054 self,
1055 name: str,
1056 args: Sequence[Type] | None = None,
1057 *,
1058 line: int = -1,
1059 column: int = -1,
1060 optional: bool = False,
1061 empty_tuple_index: bool = False,
1062 original_str_expr: str | None = None,
1063 original_str_fallback: str | None = None,
1064 ) -> None:
1065 super().__init__(line, column)
1066 if not args:
1067 args = []
1068 self.name = name
1069 self.args = tuple(args)
1070 # Should this type be wrapped in an Optional?
1071 self.optional = optional
1072 # Special case for X[()]
1073 self.empty_tuple_index = empty_tuple_index
1074 # If this UnboundType was originally defined as a str or bytes, keep track of
1075 # the original contents of that string-like thing. This way, if this UnboundExpr
1076 # ever shows up inside of a LiteralType, we can determine whether that
1077 # Literal[...] is valid or not. E.g. Literal[foo] is most likely invalid
1078 # (unless 'foo' is an alias for another literal or something) and
1079 # Literal["foo"] most likely is.
1080 #
1081 # We keep track of the entire string instead of just using a boolean flag
1082 # so we can distinguish between things like Literal["foo"] vs
1083 # Literal[" foo "].
1084 #
1085 # We also keep track of what the original base fallback type was supposed to be
1086 # so we don't have to try and recompute it later
1087 self.original_str_expr = original_str_expr
1088 self.original_str_fallback = original_str_fallback
1089
1090 def copy_modified(self, args: Bogus[Sequence[Type] | None] = _dummy) -> UnboundType:
1091 if args is _dummy:
1092 args = self.args
1093 return UnboundType(
1094 name=self.name,
1095 args=args,
1096 line=self.line,
1097 column=self.column,
1098 optional=self.optional,
1099 empty_tuple_index=self.empty_tuple_index,
1100 original_str_expr=self.original_str_expr,
1101 original_str_fallback=self.original_str_fallback,
1102 )
1103
1104 def accept(self, visitor: TypeVisitor[T]) -> T:
1105 return visitor.visit_unbound_type(self)
1106
1107 def __hash__(self) -> int:
1108 return hash((self.name, self.optional, tuple(self.args), self.original_str_expr))
1109
1110 def __eq__(self, other: object) -> bool:
1111 if not isinstance(other, UnboundType):
1112 return NotImplemented
1113 return (
1114 self.name == other.name
1115 and self.optional == other.optional
1116 and self.args == other.args
1117 and self.original_str_expr == other.original_str_expr
1118 and self.original_str_fallback == other.original_str_fallback
1119 )
1120
1121 def serialize(self) -> JsonDict:
1122 return {
1123 ".class": "UnboundType",
1124 "name": self.name,
1125 "args": [a.serialize() for a in self.args],
1126 "expr": self.original_str_expr,
1127 "expr_fallback": self.original_str_fallback,
1128 }
1129
1130 @classmethod
1131 def deserialize(cls, data: JsonDict) -> UnboundType:
1132 assert data[".class"] == "UnboundType"
1133 return UnboundType(
1134 data["name"],
1135 [deserialize_type(a) for a in data["args"]],
1136 original_str_expr=data["expr"],
1137 original_str_fallback=data["expr_fallback"],
1138 )
1139
1140 def write(self, data: WriteBuffer) -> None:
1141 write_tag(data, UNBOUND_TYPE)
1142 write_str(data, self.name)
1143 write_type_list(data, self.args)
1144 write_str_opt(data, self.original_str_expr)
1145 write_str_opt(data, self.original_str_fallback)
1146 write_tag(data, END_TAG)
1147
1148 @classmethod
1149 def read(cls, data: ReadBuffer) -> UnboundType:
1150 ret = UnboundType(
1151 read_str(data),
1152 read_type_list(data),
1153 original_str_expr=read_str_opt(data),
1154 original_str_fallback=read_str_opt(data),
1155 )
1156 assert read_tag(data) == END_TAG
1157 return ret
1158
1159
1160 class CallableArgument(ProperType):
1161 """Represents a Arg(type, 'name') inside a Callable's type list.
1162
1163 Note that this is a synthetic type for helping parse ASTs, not a real type.
1164 """
1165
1166 __slots__ = ("typ", "name", "constructor")
1167
1168 typ: Type
1169 name: str | None
1170 constructor: str | None
1171
1172 def __init__(
1173 self,
1174 typ: Type,
1175 name: str | None,
1176 constructor: str | None,
1177 line: int = -1,
1178 column: int = -1,
1179 ) -> None:
1180 super().__init__(line, column)
1181 self.typ = typ
1182 self.name = name
1183 self.constructor = constructor
1184
1185 def accept(self, visitor: TypeVisitor[T]) -> T:
1186 assert isinstance(visitor, SyntheticTypeVisitor)
1187 ret: T = visitor.visit_callable_argument(self)
1188 return ret
1189
1190 def serialize(self) -> JsonDict:
1191 assert False, "Synthetic types don't serialize"
1192
1193
1194 class TypeList(ProperType):
1195 """Information about argument types and names [...].
1196
1197 This is used for the arguments of a Callable type, i.e. for
1198 [arg, ...] in Callable[[arg, ...], ret]. This is not a real type
1199 but a syntactic AST construct. UnboundTypes can also have TypeList
1200 types before they are processed into Callable types.
1201 """
1202
1203 __slots__ = ("items",)
1204
1205 items: list[Type]
1206
1207 def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None:
1208 super().__init__(line, column)
1209 self.items = items
1210
1211 def accept(self, visitor: TypeVisitor[T]) -> T:
1212 assert isinstance(visitor, SyntheticTypeVisitor)
1213 ret: T = visitor.visit_type_list(self)
1214 return ret
1215
1216 def serialize(self) -> JsonDict:
1217 assert False, "Synthetic types don't serialize"
1218
1219 def __hash__(self) -> int:
1220 return hash(tuple(self.items))
1221
1222 def __eq__(self, other: object) -> bool:
1223 return isinstance(other, TypeList) and self.items == other.items
1224
1225
1226 class UnpackType(ProperType):
1227 """Type operator Unpack from PEP646. Can be either with Unpack[]
1228 or unpacking * syntax.
1229
1230 The inner type should be either a TypeVarTuple, or a variable length tuple.
1231 In an exceptional case of callable star argument it can be a fixed length tuple.
1232
1233 Note: the above restrictions are only guaranteed by normalizations after semantic
1234 analysis, if your code needs to handle UnpackType *during* semantic analysis, it is
1235 wild west, technically anything can be present in the wrapped type.
1236 """
1237
1238 __slots__ = ["type", "from_star_syntax"]
1239
1240 def __init__(
1241 self, typ: Type, line: int = -1, column: int = -1, from_star_syntax: bool = False
1242 ) -> None:
1243 super().__init__(line, column)
1244 self.type = typ
1245 self.from_star_syntax = from_star_syntax
1246
1247 def accept(self, visitor: TypeVisitor[T]) -> T:
1248 return visitor.visit_unpack_type(self)
1249
1250 def serialize(self) -> JsonDict:
1251 return {".class": "UnpackType", "type": self.type.serialize()}
1252
1253 def write(self, data: WriteBuffer) -> None:
1254 write_tag(data, UNPACK_TYPE)
1255 self.type.write(data)
1256 write_tag(data, END_TAG)
1257
1258 @classmethod
1259 def read(cls, data: ReadBuffer) -> UnpackType:
1260 ret = UnpackType(read_type(data))
1261 assert read_tag(data) == END_TAG
1262 return ret
1263
1264 @classmethod
1265 def deserialize(cls, data: JsonDict) -> UnpackType:
1266 assert data[".class"] == "UnpackType"
1267 typ = data["type"]
1268 return UnpackType(deserialize_type(typ))
1269
1270 def __hash__(self) -> int:
1271 return hash(self.type)
1272
1273 def __eq__(self, other: object) -> bool:
1274 return isinstance(other, UnpackType) and self.type == other.type
1275
1276
1277 class AnyType(ProperType):
1278 """The type 'Any'."""
1279
1280 __slots__ = ("type_of_any", "source_any", "missing_import_name")
1281
1282 def __init__(
1283 self,
1284 type_of_any: int,
1285 source_any: AnyType | None = None,
1286 missing_import_name: str | None = None,
1287 line: int = -1,
1288 column: int = -1,
1289 ) -> None:
1290 super().__init__(line, column)
1291 self.type_of_any = type_of_any
1292 # If this Any was created as a result of interacting with another 'Any', record the source
1293 # and use it in reports.
1294 self.source_any = source_any
1295 if source_any and source_any.source_any:
1296 self.source_any = source_any.source_any
1297
1298 if source_any is None:
1299 self.missing_import_name = missing_import_name
1300 else:
1301 self.missing_import_name = source_any.missing_import_name
1302
1303 # Only unimported type anys and anys from other anys should have an import name
1304 assert missing_import_name is None or type_of_any in (
1305 TypeOfAny.from_unimported_type,
1306 TypeOfAny.from_another_any,
1307 )
1308 # Only Anys that come from another Any can have source_any.
1309 assert type_of_any != TypeOfAny.from_another_any or source_any is not None
1310 # We should not have chains of Anys.
1311 assert not self.source_any or self.source_any.type_of_any != TypeOfAny.from_another_any
1312
1313 @property
1314 def is_from_error(self) -> bool:
1315 return self.type_of_any == TypeOfAny.from_error
1316
1317 def accept(self, visitor: TypeVisitor[T]) -> T:
1318 return visitor.visit_any(self)
1319
1320 def copy_modified(
1321 self,
1322 # Mark with Bogus because _dummy is just an object (with type Any)
1323 type_of_any: int = _dummy_int,
1324 original_any: Bogus[AnyType | None] = _dummy,
1325 missing_import_name: Bogus[str | None] = _dummy,
1326 ) -> AnyType:
1327 if type_of_any == _dummy_int:
1328 type_of_any = self.type_of_any
1329 if original_any is _dummy:
1330 original_any = self.source_any
1331 if missing_import_name is _dummy:
1332 missing_import_name = self.missing_import_name
1333 return AnyType(
1334 type_of_any=type_of_any,
1335 source_any=original_any,
1336 missing_import_name=missing_import_name,
1337 line=self.line,
1338 column=self.column,
1339 )
1340
1341 def __hash__(self) -> int:
1342 return hash(AnyType)
1343
1344 def __eq__(self, other: object) -> bool:
1345 return isinstance(other, AnyType)
1346
1347 def serialize(self) -> JsonDict:
1348 return {
1349 ".class": "AnyType",
1350 "type_of_any": self.type_of_any,
1351 "source_any": self.source_any.serialize() if self.source_any is not None else None,
1352 "missing_import_name": self.missing_import_name,
1353 }
1354
1355 @classmethod
1356 def deserialize(cls, data: JsonDict) -> AnyType:
1357 assert data[".class"] == "AnyType"
1358 source = data["source_any"]
1359 return AnyType(
1360 data["type_of_any"],
1361 AnyType.deserialize(source) if source is not None else None,
1362 data["missing_import_name"],
1363 )
1364
1365 def write(self, data: WriteBuffer) -> None:
1366 write_tag(data, ANY_TYPE)
1367 write_type_opt(data, self.source_any)
1368 write_int(data, self.type_of_any)
1369 write_str_opt(data, self.missing_import_name)
1370 write_tag(data, END_TAG)
1371
1372 @classmethod
1373 def read(cls, data: ReadBuffer) -> AnyType:
1374 tag = read_tag(data)
1375 if tag != LITERAL_NONE:
1376 assert tag == ANY_TYPE
1377 source_any = AnyType.read(data)
1378 else:
1379 source_any = None
1380 ret = AnyType(read_int(data), source_any, read_str_opt(data))
1381 assert read_tag(data) == END_TAG
1382 return ret
1383
1384
1385 class UninhabitedType(ProperType):
1386 """This type has no members.
1387
1388 This type is the bottom type.
1389 With strict Optional checking, it is the only common subtype between all
1390 other types, which allows `meet` to be well defined. Without strict
1391 Optional checking, NoneType fills this role.
1392
1393 In general, for any type T:
1394 join(UninhabitedType, T) = T
1395 meet(UninhabitedType, T) = UninhabitedType
1396 is_subtype(UninhabitedType, T) = True
1397 """
1398
1399 __slots__ = ("ambiguous",)
1400
1401 ambiguous: bool # Is this a result of inference for a variable without constraints?
1402
1403 def __init__(self, line: int = -1, column: int = -1, *, ambiguous: bool = False) -> None:
1404 super().__init__(line, column)
1405 self.ambiguous = ambiguous
1406
1407 def can_be_true_default(self) -> bool:
1408 return False
1409
1410 def can_be_false_default(self) -> bool:
1411 return False
1412
1413 def accept(self, visitor: TypeVisitor[T]) -> T:
1414 return visitor.visit_uninhabited_type(self)
1415
1416 def __hash__(self) -> int:
1417 return hash((UninhabitedType, self.ambiguous))
1418
1419 def __eq__(self, other: object) -> bool:
1420 return isinstance(other, UninhabitedType) and other.ambiguous == self.ambiguous
1421
1422 def serialize(self) -> JsonDict:
1423 return {".class": "UninhabitedType"}
1424
1425 @classmethod
1426 def deserialize(cls, data: JsonDict) -> UninhabitedType:
1427 assert data[".class"] == "UninhabitedType"
1428 return UninhabitedType()
1429
1430 def write(self, data: WriteBuffer) -> None:
1431 write_tag(data, UNINHABITED_TYPE)
1432 write_tag(data, END_TAG)
1433
1434 @classmethod
1435 def read(cls, data: ReadBuffer) -> UninhabitedType:
1436 assert read_tag(data) == END_TAG
1437 return UninhabitedType()
1438
1439
1440 class NoneType(ProperType):
1441 """The type of 'None'.
1442
1443 This type can be written by users as 'None'.
1444 """
1445
1446 __slots__ = ()
1447
1448 def __init__(self, line: int = -1, column: int = -1) -> None:
1449 super().__init__(line, column)
1450
1451 def can_be_true_default(self) -> bool:
1452 return False
1453
1454 def __hash__(self) -> int:
1455 return hash(NoneType)
1456
1457 def __eq__(self, other: object) -> bool:
1458 return isinstance(other, NoneType)
1459
1460 def accept(self, visitor: TypeVisitor[T]) -> T:
1461 return visitor.visit_none_type(self)
1462
1463 def serialize(self) -> JsonDict:
1464 return {".class": "NoneType"}
1465
1466 @classmethod
1467 def deserialize(cls, data: JsonDict) -> NoneType:
1468 assert data[".class"] == "NoneType"
1469 return NoneType()
1470
1471 def write(self, data: WriteBuffer) -> None:
1472 write_tag(data, NONE_TYPE)
1473 write_tag(data, END_TAG)
1474
1475 @classmethod
1476 def read(cls, data: ReadBuffer) -> NoneType:
1477 assert read_tag(data) == END_TAG
1478 return NoneType()
1479
1480
1481 # NoneType used to be called NoneTyp so to avoid needlessly breaking
1482 # external plugins we keep that alias here.
1483 NoneTyp = NoneType
1484
1485
1486 class ErasedType(ProperType):
1487 """Placeholder for an erased type.
1488
1489 This is used during type inference. This has the special property that
1490 it is ignored during type inference.
1491 """
1492
1493 __slots__ = ()
1494
1495 def accept(self, visitor: TypeVisitor[T]) -> T:
1496 return visitor.visit_erased_type(self)
1497
1498
1499 class DeletedType(ProperType):
1500 """Type of deleted variables.
1501
1502 These can be used as lvalues but not rvalues.
1503 """
1504
1505 __slots__ = ("source",)
1506
1507 source: str | None # May be None; name that generated this value
1508
1509 def __init__(self, source: str | None = None, line: int = -1, column: int = -1) -> None:
1510 super().__init__(line, column)
1511 self.source = source
1512
1513 def accept(self, visitor: TypeVisitor[T]) -> T:
1514 return visitor.visit_deleted_type(self)
1515
1516 def serialize(self) -> JsonDict:
1517 return {".class": "DeletedType", "source": self.source}
1518
1519 @classmethod
1520 def deserialize(cls, data: JsonDict) -> DeletedType:
1521 assert data[".class"] == "DeletedType"
1522 return DeletedType(data["source"])
1523
1524 def write(self, data: WriteBuffer) -> None:
1525 write_tag(data, DELETED_TYPE)
1526 write_str_opt(data, self.source)
1527 write_tag(data, END_TAG)
1528
1529 @classmethod
1530 def read(cls, data: ReadBuffer) -> DeletedType:
1531 ret = DeletedType(read_str_opt(data))
1532 assert read_tag(data) == END_TAG
1533 return ret
1534
1535
1536 # Fake TypeInfo to be used as a placeholder during Instance de-serialization.
1537 NOT_READY: Final = mypy.nodes.FakeInfo("De-serialization failure: TypeInfo not fixed")
1538
1539
1540 class ExtraAttrs:
1541 """Summary of module attributes and types.
1542
1543 This is used for instances of types.ModuleType, because they can have different
1544 attributes per instance, and for type narrowing with hasattr() checks.
1545 """
1546
1547 def __init__(
1548 self,
1549 attrs: dict[str, Type],
1550 immutable: set[str] | None = None,
1551 mod_name: str | None = None,
1552 ) -> None:
1553 self.attrs = attrs
1554 if immutable is None:
1555 immutable = set()
1556 self.immutable = immutable
1557 self.mod_name = mod_name
1558
1559 def __hash__(self) -> int:
1560 return hash((tuple(self.attrs.items()), tuple(sorted(self.immutable))))
1561
1562 def __eq__(self, other: object) -> bool:
1563 if not isinstance(other, ExtraAttrs):
1564 return NotImplemented
1565 return self.attrs == other.attrs and self.immutable == other.immutable
1566
1567 def copy(self) -> ExtraAttrs:
1568 return ExtraAttrs(self.attrs.copy(), self.immutable.copy(), self.mod_name)
1569
1570 def __repr__(self) -> str:
1571 return f"ExtraAttrs({self.attrs!r}, {self.immutable!r}, {self.mod_name!r})"
1572
1573 def serialize(self) -> JsonDict:
1574 return {
1575 ".class": "ExtraAttrs",
1576 "attrs": {k: v.serialize() for k, v in self.attrs.items()},
1577 "immutable": sorted(self.immutable),
1578 "mod_name": self.mod_name,
1579 }
1580
1581 @classmethod
1582 def deserialize(cls, data: JsonDict) -> ExtraAttrs:
1583 assert data[".class"] == "ExtraAttrs"
1584 return ExtraAttrs(
1585 {k: deserialize_type(v) for k, v in data["attrs"].items()},
1586 set(data["immutable"]),
1587 data["mod_name"],
1588 )
1589
1590 def write(self, data: WriteBuffer) -> None:
1591 write_tag(data, EXTRA_ATTRS)
1592 write_type_map(data, self.attrs)
1593 write_str_list(data, sorted(self.immutable))
1594 write_str_opt(data, self.mod_name)
1595 write_tag(data, END_TAG)
1596
1597 @classmethod
1598 def read(cls, data: ReadBuffer) -> ExtraAttrs:
1599 ret = ExtraAttrs(read_type_map(data), set(read_str_list(data)), read_str_opt(data))
1600 assert read_tag(data) == END_TAG
1601 return ret
1602
1603
1604 class Instance(ProperType):
1605 """An instance type of form C[T1, ..., Tn].
1606
1607 The list of type variables may be empty.
1608
1609 Several types have fallbacks to `Instance`, because in Python everything is an object
1610 and this concept is impossible to express without intersection types. We therefore use
1611 fallbacks for all "non-special" (like UninhabitedType, ErasedType etc) types.
1612 """
1613
1614 __slots__ = ("type", "args", "invalid", "type_ref", "last_known_value", "_hash", "extra_attrs")
1615
1616 def __init__(
1617 self,
1618 typ: mypy.nodes.TypeInfo,
1619 args: Sequence[Type],
1620 line: int = -1,
1621 column: int = -1,
1622 *,
1623 last_known_value: LiteralType | None = None,
1624 extra_attrs: ExtraAttrs | None = None,
1625 ) -> None:
1626 super().__init__(line, column)
1627 self.type = typ
1628 self.args = tuple(args)
1629 self.type_ref: str | None = None
1630
1631 # This field keeps track of the underlying Literal[...] value associated with
1632 # this instance, if one is known.
1633 #
1634 # This field is set whenever possible within expressions, but is erased upon
1635 # variable assignment (see erasetype.remove_instance_last_known_values) unless
1636 # the variable is declared to be final.
1637 #
1638 # For example, consider the following program:
1639 #
1640 # a = 1
1641 # b: Final[int] = 2
1642 # c: Final = 3
1643 # print(a + b + c + 4)
1644 #
1645 # The 'Instance' objects associated with the expressions '1', '2', '3', and '4' will
1646 # have last_known_values of type Literal[1], Literal[2], Literal[3], and Literal[4]
1647 # respectively. However, the Instance object assigned to 'a' and 'b' will have their
1648 # last_known_value erased: variable 'a' is mutable; variable 'b' was declared to be
1649 # specifically an int.
1650 #
1651 # Or more broadly, this field lets this Instance "remember" its original declaration
1652 # when applicable. We want this behavior because we want implicit Final declarations
1653 # to act pretty much identically with constants: we should be able to replace any
1654 # places where we use some Final variable with the original value and get the same
1655 # type-checking behavior. For example, we want this program:
1656 #
1657 # def expects_literal(x: Literal[3]) -> None: pass
1658 # var: Final = 3
1659 # expects_literal(var)
1660 #
1661 # ...to type-check in the exact same way as if we had written the program like this:
1662 #
1663 # def expects_literal(x: Literal[3]) -> None: pass
1664 # expects_literal(3)
1665 #
1666 # In order to make this work (especially with literal types), we need var's type
1667 # (an Instance) to remember the "original" value.
1668 #
1669 # Preserving this value within expressions is useful for similar reasons.
1670 #
1671 # Currently most of mypy will ignore this field and will continue to treat this type like
1672 # a regular Instance. We end up using this field only when we are explicitly within a
1673 # Literal context.
1674 self.last_known_value = last_known_value
1675
1676 # Cached hash value
1677 self._hash = -1
1678
1679 # Additional attributes defined per instance of this type. For example modules
1680 # have different attributes per instance of types.ModuleType.
1681 self.extra_attrs = extra_attrs
1682
1683 def accept(self, visitor: TypeVisitor[T]) -> T:
1684 return visitor.visit_instance(self)
1685
1686 def __hash__(self) -> int:
1687 if self._hash == -1:
1688 self._hash = hash((self.type, self.args, self.last_known_value, self.extra_attrs))
1689 return self._hash
1690
1691 def __eq__(self, other: object) -> bool:
1692 if not isinstance(other, Instance):
1693 return NotImplemented
1694 return (
1695 self.type == other.type
1696 and self.args == other.args
1697 and self.last_known_value == other.last_known_value
1698 and self.extra_attrs == other.extra_attrs
1699 )
1700
1701 def serialize(self) -> JsonDict | str:
1702 assert self.type is not None
1703 type_ref = self.type.fullname
1704 if not self.args and not self.last_known_value and not self.extra_attrs:
1705 return type_ref
1706 data: JsonDict = {
1707 ".class": "Instance",
1708 "type_ref": type_ref,
1709 "args": [arg.serialize() for arg in self.args],
1710 }
1711 if self.last_known_value is not None:
1712 data["last_known_value"] = self.last_known_value.serialize()
1713 data["extra_attrs"] = self.extra_attrs.serialize() if self.extra_attrs else None
1714 return data
1715
1716 @classmethod
1717 def deserialize(cls, data: JsonDict | str) -> Instance:
1718 if isinstance(data, str):
1719 inst = Instance(NOT_READY, [])
1720 inst.type_ref = data
1721 return inst
1722 assert data[".class"] == "Instance"
1723 args: list[Type] = []
1724 if "args" in data:
1725 args_list = data["args"]
1726 assert isinstance(args_list, list)
1727 args = [deserialize_type(arg) for arg in args_list]
1728 inst = Instance(NOT_READY, args)
1729 inst.type_ref = data["type_ref"] # Will be fixed up by fixup.py later.
1730 if "last_known_value" in data:
1731 inst.last_known_value = LiteralType.deserialize(data["last_known_value"])
1732 if data.get("extra_attrs") is not None:
1733 inst.extra_attrs = ExtraAttrs.deserialize(data["extra_attrs"])
1734 return inst
1735
1736 def write(self, data: WriteBuffer) -> None:
1737 write_tag(data, INSTANCE)
1738 if not self.args and not self.last_known_value and not self.extra_attrs:
1739 type_ref = self.type.fullname
1740 if type_ref == "builtins.str":
1741 write_tag(data, INSTANCE_STR)
1742 elif type_ref == "builtins.function":
1743 write_tag(data, INSTANCE_FUNCTION)
1744 elif type_ref == "builtins.int":
1745 write_tag(data, INSTANCE_INT)
1746 elif type_ref == "builtins.bool":
1747 write_tag(data, INSTANCE_BOOL)
1748 elif type_ref == "builtins.object":
1749 write_tag(data, INSTANCE_OBJECT)
1750 else:
1751 write_tag(data, INSTANCE_SIMPLE)
1752 write_str_bare(data, type_ref)
1753 return
1754 write_tag(data, INSTANCE_GENERIC)
1755 write_str(data, self.type.fullname)
1756 write_type_list(data, self.args)
1757 write_type_opt(data, self.last_known_value)
1758 if self.extra_attrs is None:
1759 write_tag(data, LITERAL_NONE)
1760 else:
1761 self.extra_attrs.write(data)
1762 write_tag(data, END_TAG)
1763
1764 @classmethod
1765 def read(cls, data: ReadBuffer) -> Instance:
1766 tag = read_tag(data)
1767 # This is quite verbose, but this is very hot code, so we are not
1768 # using dictionary lookups here.
1769 if tag == INSTANCE_STR:
1770 if instance_cache.str_type is None:
1771 instance_cache.str_type = Instance(NOT_READY, [])
1772 instance_cache.str_type.type_ref = "builtins.str"
1773 return instance_cache.str_type
1774 if tag == INSTANCE_FUNCTION:
1775 if instance_cache.function_type is None:
1776 instance_cache.function_type = Instance(NOT_READY, [])
1777 instance_cache.function_type.type_ref = "builtins.function"
1778 return instance_cache.function_type
1779 if tag == INSTANCE_INT:
1780 if instance_cache.int_type is None:
1781 instance_cache.int_type = Instance(NOT_READY, [])
1782 instance_cache.int_type.type_ref = "builtins.int"
1783 return instance_cache.int_type
1784 if tag == INSTANCE_BOOL:
1785 if instance_cache.bool_type is None:
1786 instance_cache.bool_type = Instance(NOT_READY, [])
1787 instance_cache.bool_type.type_ref = "builtins.bool"
1788 return instance_cache.bool_type
1789 if tag == INSTANCE_OBJECT:
1790 if instance_cache.object_type is None:
1791 instance_cache.object_type = Instance(NOT_READY, [])
1792 instance_cache.object_type.type_ref = "builtins.object"
1793 return instance_cache.object_type
1794 if tag == INSTANCE_SIMPLE:
1795 inst = Instance(NOT_READY, [])
1796 inst.type_ref = read_str_bare(data)
1797 return inst
1798 assert tag == INSTANCE_GENERIC
1799 type_ref = read_str(data)
1800 inst = Instance(NOT_READY, read_type_list(data))
1801 inst.type_ref = type_ref
1802 tag = read_tag(data)
1803 if tag != LITERAL_NONE:
1804 assert tag == LITERAL_TYPE
1805 inst.last_known_value = LiteralType.read(data)
1806 tag = read_tag(data)
1807 if tag != LITERAL_NONE:
1808 assert tag == EXTRA_ATTRS
1809 inst.extra_attrs = ExtraAttrs.read(data)
1810 assert read_tag(data) == END_TAG
1811 return inst
1812
1813 def copy_modified(
1814 self,
1815 *,
1816 args: Bogus[list[Type]] = _dummy,
1817 last_known_value: Bogus[LiteralType | None] = _dummy,
1818 ) -> Instance:
1819 new = Instance(
1820 typ=self.type,
1821 args=args if args is not _dummy else self.args,
1822 line=self.line,
1823 column=self.column,
1824 last_known_value=(
1825 last_known_value if last_known_value is not _dummy else self.last_known_value
1826 ),
1827 extra_attrs=self.extra_attrs,
1828 )
1829 new.can_be_true = self.can_be_true
1830 new.can_be_false = self.can_be_false
1831 return new
1832
1833 def copy_with_extra_attr(self, name: str, typ: Type) -> Instance:
1834 if self.extra_attrs:
1835 existing_attrs = self.extra_attrs.copy()
1836 else:
1837 existing_attrs = ExtraAttrs({}, set(), None)
1838 existing_attrs.attrs[name] = typ
1839 new = self.copy_modified()
1840 new.extra_attrs = existing_attrs
1841 return new
1842
1843
1844 class InstanceCache:
1845 def __init__(self) -> None:
1846 self.str_type: Instance | None = None
1847 self.function_type: Instance | None = None
1848 self.int_type: Instance | None = None
1849 self.bool_type: Instance | None = None
1850 self.object_type: Instance | None = None
1851
1852 def reset(self) -> None:
1853 self.str_type = None
1854 self.function_type = None
1855 self.int_type = None
1856 self.bool_type = None
1857 self.object_type = None
1858
1859
1860 instance_cache: Final = InstanceCache()
1861
1862
1863 class FunctionLike(ProperType):
1864 """Abstract base class for function types."""
1865
1866 __slots__ = ("fallback",)
1867
1868 fallback: Instance
1869
1870 def __init__(self, line: int = -1, column: int = -1) -> None:
1871 super().__init__(line, column)
1872 self._can_be_false = False
1873
1874 @abstractmethod
1875 def is_type_obj(self) -> bool:
1876 pass
1877
1878 @abstractmethod
1879 def type_object(self) -> mypy.nodes.TypeInfo:
1880 pass
1881
1882 @property
1883 @abstractmethod
1884 def items(self) -> list[CallableType]:
1885 pass
1886
1887 @abstractmethod
1888 def with_name(self, name: str) -> FunctionLike:
1889 pass
1890
1891 @abstractmethod
1892 def get_name(self) -> str | None:
1893 pass
1894
1895 def bound(self) -> bool:
1896 return bool(self.items) and self.items[0].is_bound
1897
1898
1899 class FormalArgument:
1900 def __init__(self, name: str | None, pos: int | None, typ: Type, required: bool) -> None:
1901 self.name = name
1902 self.pos = pos
1903 self.typ = typ
1904 self.required = required
1905
1906 def __eq__(self, other: object) -> bool:
1907 if not isinstance(other, FormalArgument):
1908 return NotImplemented
1909 return (
1910 self.name == other.name
1911 and self.pos == other.pos
1912 and self.typ == other.typ
1913 and self.required == other.required
1914 )
1915
1916 def __hash__(self) -> int:
1917 return hash((self.name, self.pos, self.typ, self.required))
1918
1919
1920 class Parameters(ProperType):
1921 """Type that represents the parameters to a function.
1922
1923 Used for ParamSpec analysis. Note that by convention we handle this
1924 type as a Callable without return type, not as a "tuple with names",
1925 so that it behaves contravariantly, in particular [x: int] <: [int].
1926 """
1927
1928 __slots__ = (
1929 "arg_types",
1930 "arg_kinds",
1931 "arg_names",
1932 "min_args",
1933 "is_ellipsis_args",
1934 # TODO: variables don't really belong here, but they are used to allow hacky support
1935 # for forall . Foo[[x: T], T] by capturing generic callable with ParamSpec, see #15909
1936 "variables",
1937 "imprecise_arg_kinds",
1938 )
1939
1940 def __init__(
1941 self,
1942 arg_types: Sequence[Type],
1943 arg_kinds: list[ArgKind],
1944 arg_names: Sequence[str | None],
1945 *,
1946 variables: Sequence[TypeVarLikeType] | None = None,
1947 is_ellipsis_args: bool = False,
1948 imprecise_arg_kinds: bool = False,
1949 line: int = -1,
1950 column: int = -1,
1951 ) -> None:
1952 super().__init__(line, column)
1953 self.arg_types = list(arg_types)
1954 self.arg_kinds = arg_kinds
1955 self.arg_names = list(arg_names)
1956 assert len(arg_types) == len(arg_kinds) == len(arg_names)
1957 assert not any(isinstance(t, Parameters) for t in arg_types)
1958 self.min_args = arg_kinds.count(ARG_POS)
1959 self.is_ellipsis_args = is_ellipsis_args
1960 self.variables = variables or []
1961 self.imprecise_arg_kinds = imprecise_arg_kinds
1962
1963 def copy_modified(
1964 self,
1965 arg_types: Bogus[Sequence[Type]] = _dummy,
1966 arg_kinds: Bogus[list[ArgKind]] = _dummy,
1967 arg_names: Bogus[Sequence[str | None]] = _dummy,
1968 *,
1969 variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,
1970 is_ellipsis_args: Bogus[bool] = _dummy,
1971 imprecise_arg_kinds: Bogus[bool] = _dummy,
1972 ) -> Parameters:
1973 return Parameters(
1974 arg_types=arg_types if arg_types is not _dummy else self.arg_types,
1975 arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,
1976 arg_names=arg_names if arg_names is not _dummy else self.arg_names,
1977 is_ellipsis_args=(
1978 is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args
1979 ),
1980 variables=variables if variables is not _dummy else self.variables,
1981 imprecise_arg_kinds=(
1982 imprecise_arg_kinds
1983 if imprecise_arg_kinds is not _dummy
1984 else self.imprecise_arg_kinds
1985 ),
1986 )
1987
1988 # TODO: here is a lot of code duplication with Callable type, fix this.
1989 def var_arg(self) -> FormalArgument | None:
1990 """The formal argument for *args."""
1991 for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
1992 if kind == ARG_STAR:
1993 return FormalArgument(None, position, type, False)
1994 return None
1995
1996 def kw_arg(self) -> FormalArgument | None:
1997 """The formal argument for **kwargs."""
1998 for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
1999 if kind == ARG_STAR2:
2000 return FormalArgument(None, position, type, False)
2001 return None
2002
2003 def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]:
2004 """Yields the formal arguments corresponding to this callable, ignoring *arg and **kwargs.
2005
2006 To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields,
2007 if they are not None.
2008
2009 If you really want to include star args in the yielded output, set the
2010 'include_star_args' parameter to 'True'."""
2011 args = []
2012 done_with_positional = False
2013 for i in range(len(self.arg_types)):
2014 kind = self.arg_kinds[i]
2015 if kind.is_named() or kind.is_star():
2016 done_with_positional = True
2017 if not include_star_args and kind.is_star():
2018 continue
2019
2020 required = kind.is_required()
2021 pos = None if done_with_positional else i
2022 arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required)
2023 args.append(arg)
2024 return args
2025
2026 def argument_by_name(self, name: str | None) -> FormalArgument | None:
2027 if name is None:
2028 return None
2029 seen_star = False
2030 for i, (arg_name, kind, typ) in enumerate(
2031 zip(self.arg_names, self.arg_kinds, self.arg_types)
2032 ):
2033 # No more positional arguments after these.
2034 if kind.is_named() or kind.is_star():
2035 seen_star = True
2036 if kind.is_star():
2037 continue
2038 if arg_name == name:
2039 position = None if seen_star else i
2040 return FormalArgument(name, position, typ, kind.is_required())
2041 return self.try_synthesizing_arg_from_kwarg(name)
2042
2043 def argument_by_position(self, position: int | None) -> FormalArgument | None:
2044 if position is None:
2045 return None
2046 if position >= len(self.arg_names):
2047 return self.try_synthesizing_arg_from_vararg(position)
2048 name, kind, typ = (
2049 self.arg_names[position],
2050 self.arg_kinds[position],
2051 self.arg_types[position],
2052 )
2053 if kind.is_positional():
2054 return FormalArgument(name, position, typ, kind == ARG_POS)
2055 else:
2056 return self.try_synthesizing_arg_from_vararg(position)
2057
2058 def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None:
2059 kw_arg = self.kw_arg()
2060 if kw_arg is not None:
2061 return FormalArgument(name, None, kw_arg.typ, False)
2062 else:
2063 return None
2064
2065 def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None:
2066 var_arg = self.var_arg()
2067 if var_arg is not None:
2068 return FormalArgument(None, position, var_arg.typ, False)
2069 else:
2070 return None
2071
2072 def accept(self, visitor: TypeVisitor[T]) -> T:
2073 return visitor.visit_parameters(self)
2074
2075 def serialize(self) -> JsonDict:
2076 return {
2077 ".class": "Parameters",
2078 "arg_types": [t.serialize() for t in self.arg_types],
2079 "arg_kinds": [int(x.value) for x in self.arg_kinds],
2080 "arg_names": self.arg_names,
2081 "variables": [tv.serialize() for tv in self.variables],
2082 "imprecise_arg_kinds": self.imprecise_arg_kinds,
2083 }
2084
2085 @classmethod
2086 def deserialize(cls, data: JsonDict) -> Parameters:
2087 assert data[".class"] == "Parameters"
2088 return Parameters(
2089 [deserialize_type(t) for t in data["arg_types"]],
2090 # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise,
2091 # we would spend ~20% of types deserialization time in Enum.__call__().
2092 [ARG_KINDS[x] for x in data["arg_kinds"]],
2093 data["arg_names"],
2094 variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]],
2095 imprecise_arg_kinds=data["imprecise_arg_kinds"],
2096 )
2097
2098 def write(self, data: WriteBuffer) -> None:
2099 write_tag(data, PARAMETERS)
2100 write_type_list(data, self.arg_types)
2101 write_int_list(data, [int(x.value) for x in self.arg_kinds])
2102 write_str_opt_list(data, self.arg_names)
2103 write_type_list(data, self.variables)
2104 write_bool(data, self.imprecise_arg_kinds)
2105 write_tag(data, END_TAG)
2106
2107 @classmethod
2108 def read(cls, data: ReadBuffer) -> Parameters:
2109 ret = Parameters(
2110 read_type_list(data),
2111 # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise,
2112 # we would spend ~20% of types deserialization time in Enum.__call__().
2113 [ARG_KINDS[ak] for ak in read_int_list(data)],
2114 read_str_opt_list(data),
2115 variables=read_type_var_likes(data),
2116 imprecise_arg_kinds=read_bool(data),
2117 )
2118 assert read_tag(data) == END_TAG
2119 return ret
2120
2121 def __hash__(self) -> int:
2122 return hash(
2123 (
2124 self.is_ellipsis_args,
2125 tuple(self.arg_types),
2126 tuple(self.arg_names),
2127 tuple(self.arg_kinds),
2128 )
2129 )
2130
2131 def __eq__(self, other: object) -> bool:
2132 if isinstance(other, Parameters):
2133 return (
2134 self.arg_types == other.arg_types
2135 and self.arg_names == other.arg_names
2136 and self.arg_kinds == other.arg_kinds
2137 and self.is_ellipsis_args == other.is_ellipsis_args
2138 )
2139 else:
2140 return NotImplemented
2141
2142
2143 CT = TypeVar("CT", bound="CallableType")
2144
2145
2146 class CallableType(FunctionLike):
2147 """Type of a non-overloaded callable object (such as function)."""
2148
2149 __slots__ = (
2150 "arg_types", # Types of function arguments
2151 "arg_kinds", # ARG_ constants
2152 "arg_names", # Argument names; None if not a keyword argument
2153 "ret_type", # Return value type
2154 "name", # Name (may be None; for error messages and plugins)
2155 "definition", # For error messages. May be None.
2156 "variables", # Type variables for a generic function
2157 "is_ellipsis_args", # Is this Callable[..., t] (with literal '...')?
2158 "implicit", # Was this type implicitly generated instead of explicitly
2159 # specified by the user?
2160 "special_sig", # Non-None for signatures that require special handling
2161 # (currently only values are 'dict' for a signature similar to
2162 # 'dict' and 'partial' for a `functools.partial` evaluation, and 'tuple')
2163 "from_type_type", # Was this callable generated by analyzing Type[...]
2164 # instantiation?
2165 "is_bound", # Is this a bound method?
2166 "type_guard", # T, if -> TypeGuard[T] (ret_type is bool in this case).
2167 "type_is", # T, if -> TypeIs[T] (ret_type is bool in this case).
2168 "from_concatenate", # whether this callable is from a concatenate object
2169 # (this is used for error messages)
2170 "imprecise_arg_kinds",
2171 "unpack_kwargs", # Was an Unpack[...] with **kwargs used to define this callable?
2172 "instance_type", # Real underlying type of a type object. This is different from
2173 # ret_type in case we have e.g. a custom __new__() return annotation.
2174 )
2175
2176 def __init__(
2177 self,
2178 # maybe this should be refactored to take a Parameters object
2179 arg_types: Sequence[Type],
2180 arg_kinds: list[ArgKind],
2181 arg_names: Sequence[str | None],
2182 ret_type: Type,
2183 fallback: Instance,
2184 name: str | None = None,
2185 definition: SymbolNode | None = None,
2186 variables: Sequence[TypeVarLikeType] | None = None,
2187 line: int = -1,
2188 column: int = -1,
2189 is_ellipsis_args: bool = False,
2190 implicit: bool = False,
2191 special_sig: str | None = None,
2192 from_type_type: bool = False,
2193 is_bound: bool = False,
2194 type_guard: Type | None = None,
2195 type_is: Type | None = None,
2196 from_concatenate: bool = False,
2197 imprecise_arg_kinds: bool = False,
2198 unpack_kwargs: bool = False,
2199 instance_type: ProperType | None = None,
2200 ) -> None:
2201 super().__init__(line, column)
2202 assert len(arg_types) == len(arg_kinds) == len(arg_names)
2203 self.arg_types = list(arg_types)
2204 for t in self.arg_types:
2205 if isinstance(t, ParamSpecType):
2206 assert not t.prefix.arg_types
2207 # TODO: should we assert that only ARG_STAR contain ParamSpecType?
2208 # See testParamSpecJoin, that relies on passing e.g `P.args` as plain argument.
2209 self.arg_kinds = arg_kinds
2210 self.arg_names = list(arg_names)
2211 self.ret_type = ret_type
2212 self.fallback = fallback
2213 assert not name or "<bound method" not in name
2214 self.name = name
2215 # The rules for what exactly is considered a definition:
2216 # * If it is a non-decorated function, FuncDef is the definition
2217 # * If it is a decorated function, enclosing Decorator is the definition
2218 self.definition = definition
2219 self.variables: tuple[TypeVarLikeType, ...]
2220 if variables is None:
2221 self.variables = ()
2222 else:
2223 self.variables = tuple(variables)
2224 self.is_ellipsis_args = is_ellipsis_args
2225 self.implicit = implicit
2226 self.special_sig = special_sig
2227 self.from_type_type = from_type_type
2228 self.from_concatenate = from_concatenate
2229 self.imprecise_arg_kinds = imprecise_arg_kinds
2230 self.is_bound = is_bound
2231 self.type_guard = type_guard
2232 self.type_is = type_is
2233 self.unpack_kwargs = unpack_kwargs
2234 self.instance_type = instance_type
2235
2236 def copy_modified(
2237 self: CT,
2238 arg_types: Bogus[Sequence[Type]] = _dummy,
2239 arg_kinds: Bogus[list[ArgKind]] = _dummy,
2240 arg_names: Bogus[Sequence[str | None]] = _dummy,
2241 ret_type: Bogus[Type] = _dummy,
2242 fallback: Bogus[Instance] = _dummy,
2243 name: Bogus[str | None] = _dummy,
2244 definition: Bogus[SymbolNode | None] = _dummy,
2245 variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,
2246 line: int = _dummy_int,
2247 column: int = _dummy_int,
2248 is_ellipsis_args: Bogus[bool] = _dummy,
2249 implicit: Bogus[bool] = _dummy,
2250 special_sig: Bogus[str | None] = _dummy,
2251 from_type_type: Bogus[bool] = _dummy,
2252 is_bound: Bogus[bool] = _dummy,
2253 type_guard: Bogus[Type | None] = _dummy,
2254 type_is: Bogus[Type | None] = _dummy,
2255 from_concatenate: Bogus[bool] = _dummy,
2256 imprecise_arg_kinds: Bogus[bool] = _dummy,
2257 unpack_kwargs: Bogus[bool] = _dummy,
2258 instance_type: Bogus[ProperType | None] = _dummy,
2259 ) -> CT:
2260 modified = CallableType(
2261 arg_types=arg_types if arg_types is not _dummy else self.arg_types,
2262 arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,
2263 arg_names=arg_names if arg_names is not _dummy else self.arg_names,
2264 ret_type=ret_type if ret_type is not _dummy else self.ret_type,
2265 fallback=fallback if fallback is not _dummy else self.fallback,
2266 name=name if name is not _dummy else self.name,
2267 definition=definition if definition is not _dummy else self.definition,
2268 variables=variables if variables is not _dummy else self.variables,
2269 line=line if line != _dummy_int else self.line,
2270 column=column if column != _dummy_int else self.column,
2271 is_ellipsis_args=(
2272 is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args
2273 ),
2274 implicit=implicit if implicit is not _dummy else self.implicit,
2275 special_sig=special_sig if special_sig is not _dummy else self.special_sig,
2276 from_type_type=from_type_type if from_type_type is not _dummy else self.from_type_type,
2277 is_bound=is_bound if is_bound is not _dummy else self.is_bound,
2278 type_guard=type_guard if type_guard is not _dummy else self.type_guard,
2279 type_is=type_is if type_is is not _dummy else self.type_is,
2280 from_concatenate=(
2281 from_concatenate if from_concatenate is not _dummy else self.from_concatenate
2282 ),
2283 imprecise_arg_kinds=(
2284 imprecise_arg_kinds
2285 if imprecise_arg_kinds is not _dummy
2286 else self.imprecise_arg_kinds
2287 ),
2288 unpack_kwargs=unpack_kwargs if unpack_kwargs is not _dummy else self.unpack_kwargs,
2289 instance_type=instance_type if instance_type is not _dummy else self.instance_type,
2290 )
2291 # Optimization: Only NewTypes are supported as subtypes since
2292 # the class is effectively final, so we can use a cast safely.
2293 return cast(CT, modified)
2294
2295 def var_arg(self) -> FormalArgument | None:
2296 """The formal argument for *args."""
2297 for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
2298 if kind == ARG_STAR:
2299 return FormalArgument(None, position, type, False)
2300 return None
2301
2302 def kw_arg(self) -> FormalArgument | None:
2303 """The formal argument for **kwargs."""
2304 for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):
2305 if kind == ARG_STAR2:
2306 return FormalArgument(None, position, type, False)
2307 return None
2308
2309 @property
2310 def min_args(self) -> int:
2311 return self.arg_kinds.count(ARG_POS)
2312
2313 @property
2314 def is_var_arg(self) -> bool:
2315 """Does this callable have a *args argument?"""
2316 return ARG_STAR in self.arg_kinds
2317
2318 @property
2319 def is_kw_arg(self) -> bool:
2320 """Does this callable have a **kwargs argument?"""
2321 return ARG_STAR2 in self.arg_kinds
2322
2323 def is_type_obj(self) -> bool:
2324 return self.fallback.type.is_metaclass() and not isinstance(
2325 get_proper_type(self.ret_type), UninhabitedType
2326 )
2327
2328 def get_instance_type(self, *, force_fallback: bool = False) -> ProperType:
2329 """Get underlying type of a type object.
2330
2331 By default, this will return a precise self-type, essentially whatever is
2332 returned by fill_typevars(). Most notably this is a TupleType for named tuples.
2333 If an Instance fallback is required, use force_fallback=True.
2334 """
2335 assert self.is_type_obj()
2336 if self.instance_type is not None:
2337 ret = self.instance_type
2338 else:
2339 # Fall back to historic behavior in case instance_type is not set. This
2340 # will avoid crashes on type objects generated by plugins, and on (unknown)
2341 # corner cases where is_type_obj() may "accidentally" return True.
2342 ret = get_proper_type(self.ret_type)
2343 if not force_fallback:
2344 return ret
2345 if isinstance(ret, TypeVarType):
2346 ret = get_proper_type(ret.upper_bound)
2347 if isinstance(ret, TupleType):
2348 ret = ret.partial_fallback
2349 if isinstance(ret, TypedDictType):
2350 ret = ret.fallback
2351 if isinstance(ret, LiteralType):
2352 ret = ret.fallback
2353 return ret
2354
2355 def type_object(self) -> mypy.nodes.TypeInfo:
2356 instance_type = self.get_instance_type(force_fallback=True)
2357 assert isinstance(instance_type, Instance)
2358 return instance_type.type
2359
2360 def accept(self, visitor: TypeVisitor[T]) -> T:
2361 return visitor.visit_callable_type(self)
2362
2363 def with_name(self, name: str) -> CallableType:
2364 """Return a copy of this type with the specified name."""
2365 return self.copy_modified(name=name)
2366
2367 def get_name(self) -> str | None:
2368 return self.name
2369
2370 def max_possible_positional_args(self) -> int:
2371 """Returns maximum number of positional arguments this method could possibly accept.
2372
2373 This takes into account *arg and **kwargs but excludes keyword-only args."""
2374 if self.is_var_arg or self.is_kw_arg:
2375 return sys.maxsize
2376 return sum(kind.is_positional() for kind in self.arg_kinds)
2377
2378 def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]:
2379 """Return a list of the formal arguments of this callable, ignoring *arg and **kwargs.
2380
2381 To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields,
2382 if they are not None.
2383
2384 If you really want to include star args in the yielded output, set the
2385 'include_star_args' parameter to 'True'."""
2386 args = []
2387 done_with_positional = False
2388 for i in range(len(self.arg_types)):
2389 kind = self.arg_kinds[i]
2390 if kind.is_named() or kind.is_star():
2391 done_with_positional = True
2392 if not include_star_args and kind.is_star():
2393 continue
2394
2395 required = kind.is_required()
2396 pos = None if done_with_positional else i
2397 arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required)
2398 args.append(arg)
2399 return args
2400
2401 def argument_by_name(self, name: str | None) -> FormalArgument | None:
2402 if name is None:
2403 return None
2404 seen_star = False
2405 for i, (arg_name, kind, typ) in enumerate(
2406 zip(self.arg_names, self.arg_kinds, self.arg_types)
2407 ):
2408 # No more positional arguments after these.
2409 if kind.is_named() or kind.is_star():
2410 seen_star = True
2411 if kind.is_star():
2412 continue
2413 if arg_name == name:
2414 position = None if seen_star else i
2415 return FormalArgument(name, position, typ, kind.is_required())
2416 return self.try_synthesizing_arg_from_kwarg(name)
2417
2418 def argument_by_position(self, position: int | None) -> FormalArgument | None:
2419 if position is None:
2420 return None
2421 if position >= len(self.arg_names):
2422 return self.try_synthesizing_arg_from_vararg(position)
2423 name, kind, typ = (
2424 self.arg_names[position],
2425 self.arg_kinds[position],
2426 self.arg_types[position],
2427 )
2428 if kind.is_positional():
2429 return FormalArgument(name, position, typ, kind == ARG_POS)
2430 else:
2431 return self.try_synthesizing_arg_from_vararg(position)
2432
2433 def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None:
2434 kw_arg = self.kw_arg()
2435 if kw_arg is not None:
2436 return FormalArgument(name, None, kw_arg.typ, False)
2437 else:
2438 return None
2439
2440 def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None:
2441 var_arg = self.var_arg()
2442 if var_arg is not None:
2443 return FormalArgument(None, position, var_arg.typ, False)
2444 else:
2445 return None
2446
2447 @property
2448 def items(self) -> list[CallableType]:
2449 return [self]
2450
2451 def is_generic(self) -> bool:
2452 return bool(self.variables)
2453
2454 def type_var_ids(self) -> list[TypeVarId]:
2455 a: list[TypeVarId] = []
2456 for tv in self.variables:
2457 a.append(tv.id)
2458 return a
2459
2460 def param_spec(self) -> ParamSpecType | None:
2461 """Return ParamSpec if callable can be called with one.
2462
2463 A Callable accepting ParamSpec P args (*args, **kwargs) must have the
2464 two final parameters like this: *args: P.args, **kwargs: P.kwargs.
2465 """
2466 if len(self.arg_types) < 2:
2467 return None
2468 if self.arg_kinds[-2] != ARG_STAR or self.arg_kinds[-1] != ARG_STAR2:
2469 return None
2470 arg_type = self.arg_types[-2]
2471 if not isinstance(arg_type, ParamSpecType):
2472 return None
2473
2474 # Prepend prefix for def f(prefix..., *args: P.args, **kwargs: P.kwargs) -> ...
2475 # TODO: confirm that all arg kinds are positional
2476 prefix = Parameters(self.arg_types[:-2], self.arg_kinds[:-2], self.arg_names[:-2])
2477 return arg_type.copy_modified(flavor=ParamSpecFlavor.BARE, prefix=prefix)
2478
2479 def normalize_trivial_unpack(self) -> None:
2480 # Normalize trivial unpack in var args as *args: *tuple[X, ...] -> *args: X in place.
2481 if self.is_var_arg:
2482 star_index = self.arg_kinds.index(ARG_STAR)
2483 star_type = self.arg_types[star_index]
2484 if isinstance(star_type, UnpackType):
2485 p_type = get_proper_type(star_type.type)
2486 if isinstance(p_type, Instance):
2487 assert p_type.type.fullname == "builtins.tuple"
2488 self.arg_types[star_index] = p_type.args[0]
2489
2490 def with_unpacked_kwargs(self) -> NormalizedCallableType:
2491 if not self.unpack_kwargs:
2492 return cast(NormalizedCallableType, self)
2493 last_type = get_proper_type(self.arg_types[-1])
2494 assert isinstance(last_type, TypedDictType)
2495 extra_kinds = [
2496 ArgKind.ARG_NAMED if name in last_type.required_keys else ArgKind.ARG_NAMED_OPT
2497 for name in last_type.items
2498 ]
2499 new_arg_kinds = self.arg_kinds[:-1] + extra_kinds
2500 new_arg_names = self.arg_names[:-1] + list(last_type.items)
2501 new_arg_types = self.arg_types[:-1] + list(last_type.items.values())
2502 return NormalizedCallableType(
2503 self.copy_modified(
2504 arg_kinds=new_arg_kinds,
2505 arg_names=new_arg_names,
2506 arg_types=new_arg_types,
2507 unpack_kwargs=False,
2508 )
2509 )
2510
2511 def with_normalized_var_args(self) -> Self:
2512 var_arg = self.var_arg()
2513 if not var_arg or not isinstance(var_arg.typ, UnpackType):
2514 return self
2515 unpacked = get_proper_type(var_arg.typ.type)
2516 if not isinstance(unpacked, TupleType):
2517 # Note that we don't normalize *args: *tuple[X, ...] -> *args: X,
2518 # this should be done once in semanal_typeargs.py for user-defined types,
2519 # and we ourselves rarely construct such type.
2520 return self
2521 unpack_index = find_unpack_in_list(unpacked.items)
2522 if unpack_index == 0 and len(unpacked.items) > 1:
2523 # Already normalized.
2524 return self
2525
2526 # Boilerplate:
2527 var_arg_index = self.arg_kinds.index(ARG_STAR)
2528 types_prefix = self.arg_types[:var_arg_index]
2529 kinds_prefix = self.arg_kinds[:var_arg_index]
2530 names_prefix = self.arg_names[:var_arg_index]
2531 types_suffix = self.arg_types[var_arg_index + 1 :]
2532 kinds_suffix = self.arg_kinds[var_arg_index + 1 :]
2533 names_suffix = self.arg_names[var_arg_index + 1 :]
2534 no_name: str | None = None # to silence mypy
2535
2536 # Now we have something non-trivial to do.
2537 if unpack_index is None:
2538 # Plain *Tuple[X, Y, Z] -> replace with ARG_POS completely
2539 types_middle = unpacked.items
2540 kinds_middle = [ARG_POS] * len(unpacked.items)
2541 names_middle = [no_name] * len(unpacked.items)
2542 else:
2543 # *Tuple[X, *Ts, Y, Z] or *Tuple[X, *tuple[T, ...], X, Z], here
2544 # we replace the prefix by ARG_POS (this is how some places expect
2545 # Callables to be represented)
2546 nested_unpack = unpacked.items[unpack_index]
2547 assert isinstance(nested_unpack, UnpackType)
2548 nested_unpacked = get_proper_type(nested_unpack.type)
2549 if unpack_index == len(unpacked.items) - 1:
2550 # Normalize also single item tuples like
2551 # *args: *Tuple[*tuple[X, ...]] -> *args: X
2552 # *args: *Tuple[*Ts] -> *args: *Ts
2553 # This may be not strictly necessary, but these are very verbose.
2554 if isinstance(nested_unpacked, Instance):
2555 assert nested_unpacked.type.fullname == "builtins.tuple"
2556 new_unpack = nested_unpacked.args[0]
2557 else:
2558 if not isinstance(nested_unpacked, TypeVarTupleType):
2559 # We found a non-normalized tuple type, this means this method
2560 # is called during semantic analysis (e.g. from get_proper_type())
2561 # there is no point in normalizing callables at this stage.
2562 return self
2563 new_unpack = nested_unpack
2564 else:
2565 new_unpack = UnpackType(
2566 unpacked.copy_modified(items=unpacked.items[unpack_index:])
2567 )
2568 types_middle = unpacked.items[:unpack_index] + [new_unpack]
2569 kinds_middle = [ARG_POS] * unpack_index + [ARG_STAR]
2570 names_middle = [no_name] * unpack_index + [self.arg_names[var_arg_index]]
2571 return self.copy_modified(
2572 arg_types=types_prefix + types_middle + types_suffix,
2573 arg_kinds=kinds_prefix + kinds_middle + kinds_suffix,
2574 arg_names=names_prefix + names_middle + names_suffix,
2575 )
2576
2577 def __hash__(self) -> int:
2578 return hash(
2579 (
2580 self.ret_type,
2581 self.is_ellipsis_args,
2582 self.name,
2583 tuple(self.arg_types),
2584 tuple(self.arg_names),
2585 tuple(self.arg_kinds),
2586 self.fallback,
2587 )
2588 )
2589
2590 def __eq__(self, other: object) -> bool:
2591 if isinstance(other, CallableType):
2592 return (
2593 self.ret_type == other.ret_type
2594 and self.arg_types == other.arg_types
2595 and self.arg_names == other.arg_names
2596 and self.arg_kinds == other.arg_kinds
2597 and self.name == other.name
2598 and self.is_ellipsis_args == other.is_ellipsis_args
2599 and self.type_guard == other.type_guard
2600 and self.type_is == other.type_is
2601 and self.fallback == other.fallback
2602 )
2603 else:
2604 return NotImplemented
2605
2606 def serialize(self) -> JsonDict:
2607 # TODO: As an optimization, leave out everything related to
2608 # generic functions for non-generic functions.
2609 return {
2610 ".class": "CallableType",
2611 "arg_types": [t.serialize() for t in self.arg_types],
2612 "arg_kinds": [int(x.value) for x in self.arg_kinds],
2613 "arg_names": self.arg_names,
2614 "ret_type": self.ret_type.serialize(),
2615 "fallback": self.fallback.serialize(),
2616 "name": self.name,
2617 # We don't serialize the definition (only used for error messages).
2618 "variables": [v.serialize() for v in self.variables],
2619 "is_ellipsis_args": self.is_ellipsis_args,
2620 "implicit": self.implicit,
2621 "is_bound": self.is_bound,
2622 "type_guard": self.type_guard.serialize() if self.type_guard is not None else None,
2623 "type_is": self.type_is.serialize() if self.type_is is not None else None,
2624 "from_concatenate": self.from_concatenate,
2625 "imprecise_arg_kinds": self.imprecise_arg_kinds,
2626 "unpack_kwargs": self.unpack_kwargs,
2627 "instance_type": (
2628 self.instance_type.serialize() if self.instance_type is not None else None
2629 ),
2630 }
2631
2632 @classmethod
2633 def deserialize(cls, data: JsonDict) -> CallableType:
2634 assert data[".class"] == "CallableType"
2635 # The .definition link is set in fixup.py.
2636 return CallableType(
2637 [deserialize_type(t) for t in data["arg_types"]],
2638 [ARG_KINDS[x] for x in data["arg_kinds"]],
2639 data["arg_names"],
2640 deserialize_type(data["ret_type"]),
2641 Instance.deserialize(data["fallback"]),
2642 name=data["name"],
2643 variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]],
2644 is_ellipsis_args=data["is_ellipsis_args"],
2645 implicit=data["implicit"],
2646 is_bound=data["is_bound"],
2647 type_guard=(
2648 deserialize_type(data["type_guard"]) if data["type_guard"] is not None else None
2649 ),
2650 type_is=deserialize_type(data["type_is"]) if data["type_is"] is not None else None,
2651 from_concatenate=data["from_concatenate"],
2652 imprecise_arg_kinds=data["imprecise_arg_kinds"],
2653 unpack_kwargs=data["unpack_kwargs"],
2654 instance_type=(
2655 cast(ProperType, deserialize_type(data["instance_type"]))
2656 if data["instance_type"] is not None
2657 else None
2658 ),
2659 )
2660
2661 def write(self, data: WriteBuffer) -> None:
2662 write_tag(data, CALLABLE_TYPE)
2663 self.fallback.write(data)
2664 write_type_opt(data, self.instance_type)
2665 write_flags(
2666 data,
2667 [
2668 self.is_ellipsis_args,
2669 self.implicit,
2670 self.is_bound,
2671 self.from_concatenate,
2672 self.imprecise_arg_kinds,
2673 self.unpack_kwargs,
2674 ],
2675 )
2676 write_type_list(data, self.arg_types)
2677 write_int_list(data, [int(x.value) for x in self.arg_kinds])
2678 write_str_opt_list(data, self.arg_names)
2679 self.ret_type.write(data)
2680 write_str_opt(data, self.name)
2681 write_type_list(data, self.variables)
2682 write_type_opt(data, self.type_guard)
2683 write_type_opt(data, self.type_is)
2684 write_tag(data, END_TAG)
2685
2686 @classmethod
2687 def read(cls, data: ReadBuffer) -> CallableType:
2688 assert read_tag(data) == INSTANCE
2689 fallback = Instance.read(data)
2690 instance_type = read_type_opt(data)
2691 assert instance_type is None or isinstance(instance_type, ProperType)
2692 (
2693 is_ellipsis_args,
2694 implicit,
2695 is_bound,
2696 from_concatenate,
2697 imprecise_arg_kinds,
2698 unpack_kwargs,
2699 ) = read_flags(data, num_flags=6)
2700 ret = CallableType(
2701 read_type_list(data),
2702 [ARG_KINDS[ak] for ak in read_int_list(data)],
2703 read_str_opt_list(data),
2704 read_type(data),
2705 fallback,
2706 name=read_str_opt(data),
2707 variables=read_type_var_likes(data),
2708 is_ellipsis_args=is_ellipsis_args,
2709 implicit=implicit,
2710 is_bound=is_bound,
2711 type_guard=read_type_opt(data),
2712 type_is=read_type_opt(data),
2713 from_concatenate=from_concatenate,
2714 imprecise_arg_kinds=imprecise_arg_kinds,
2715 unpack_kwargs=unpack_kwargs,
2716 instance_type=instance_type,
2717 )
2718 assert read_tag(data) == END_TAG
2719 return ret
2720
2721
2722 # This is a little safety net to prevent reckless special-casing of callables
2723 # that can potentially break Unpack[...] with **kwargs.
2724 # TODO: use this in more places in checkexpr.py etc?
2725 NormalizedCallableType = NewType("NormalizedCallableType", CallableType)
2726
2727
2728 class Overloaded(FunctionLike):
2729 """Overloaded function type T1, ... Tn, where each Ti is CallableType.
2730
2731 The variant to call is chosen based on static argument
2732 types. Overloaded function types can only be defined in stub
2733 files, and thus there is no explicit runtime dispatch
2734 implementation.
2735 """
2736
2737 __slots__ = ("_items",)
2738
2739 _items: list[CallableType] # Must not be empty
2740
2741 def __init__(self, items: list[CallableType]) -> None:
2742 super().__init__(items[0].line, items[0].column)
2743 self._items = items
2744 self.fallback = items[0].fallback
2745
2746 @property
2747 def items(self) -> list[CallableType]:
2748 return self._items
2749
2750 def name(self) -> str | None:
2751 return self.get_name()
2752
2753 def is_type_obj(self) -> bool:
2754 # All the items must have the same type object status, so it's
2755 # sufficient to query only (any) one of them.
2756 return self._items[0].is_type_obj()
2757
2758 def type_object(self) -> mypy.nodes.TypeInfo:
2759 # All the items must have the same type object, so it's sufficient to
2760 # query only (any) one of them.
2761 return self._items[0].type_object()
2762
2763 def with_name(self, name: str) -> Overloaded:
2764 ni: list[CallableType] = []
2765 for it in self._items:
2766 ni.append(it.with_name(name))
2767 return Overloaded(ni)
2768
2769 def get_name(self) -> str | None:
2770 return self._items[0].name
2771
2772 def with_unpacked_kwargs(self) -> Overloaded:
2773 if any(i.unpack_kwargs for i in self.items):
2774 return Overloaded([i.with_unpacked_kwargs() for i in self.items])
2775 return self
2776
2777 def accept(self, visitor: TypeVisitor[T]) -> T:
2778 return visitor.visit_overloaded(self)
2779
2780 def __hash__(self) -> int:
2781 return hash(tuple(self.items))
2782
2783 def __eq__(self, other: object) -> bool:
2784 if not isinstance(other, Overloaded):
2785 return NotImplemented
2786 return self.items == other.items
2787
2788 def serialize(self) -> JsonDict:
2789 return {".class": "Overloaded", "items": [t.serialize() for t in self.items]}
2790
2791 @classmethod
2792 def deserialize(cls, data: JsonDict) -> Overloaded:
2793 assert data[".class"] == "Overloaded"
2794 return Overloaded([CallableType.deserialize(t) for t in data["items"]])
2795
2796 def write(self, data: WriteBuffer) -> None:
2797 write_tag(data, OVERLOADED)
2798 write_type_list(data, self.items)
2799 write_tag(data, END_TAG)
2800
2801 @classmethod
2802 def read(cls, data: ReadBuffer) -> Overloaded:
2803 items = []
2804 assert read_tag(data) == LIST_GEN
2805 for _ in range(read_int_bare(data)):
2806 assert read_tag(data) == CALLABLE_TYPE
2807 items.append(CallableType.read(data))
2808 assert read_tag(data) == END_TAG
2809 return Overloaded(items)
2810
2811
2812 class TupleType(ProperType):
2813 """The tuple type Tuple[T1, ..., Tn] (at least one type argument).
2814
2815 Instance variables:
2816 items: Tuple item types
2817 partial_fallback: The (imprecise) underlying instance type that is used
2818 for non-tuple methods. This is generally builtins.tuple[Any, ...] for
2819 regular tuples, but it's different for named tuples and classes with
2820 a tuple base class. Use mypy.typeops.tuple_fallback to calculate the
2821 precise fallback type derived from item types.
2822 implicit: If True, derived from a tuple expression (t,....) instead of Tuple[t, ...]
2823 """
2824
2825 __slots__ = ("items", "partial_fallback", "implicit")
2826
2827 items: list[Type]
2828 partial_fallback: Instance
2829 implicit: bool
2830
2831 def __init__(
2832 self,
2833 items: list[Type],
2834 fallback: Instance,
2835 line: int = -1,
2836 column: int = -1,
2837 implicit: bool = False,
2838 ) -> None:
2839 super().__init__(line, column)
2840 self.partial_fallback = fallback
2841 self.items = items
2842 self.implicit = implicit
2843
2844 def can_be_true_default(self) -> bool:
2845 if self.can_be_any_bool():
2846 # Corner case: it is a `NamedTuple` with `__bool__` method defined.
2847 # It can be anything: both `True` and `False`.
2848 return True
2849 return self.length() > 0
2850
2851 def can_be_false_default(self) -> bool:
2852 if self.can_be_any_bool():
2853 # Corner case: it is a `NamedTuple` with `__bool__` method defined.
2854 # It can be anything: both `True` and `False`.
2855 return True
2856 if self.length() == 0:
2857 return True
2858 if self.length() > 1:
2859 return False
2860 # Special case tuple[*Ts] may or may not be false.
2861 item = self.items[0]
2862 if not isinstance(item, UnpackType):
2863 return False
2864 if not isinstance(item.type, TypeVarTupleType):
2865 # Non-normalized tuple[int, ...] can be false.
2866 return True
2867 return item.type.min_len == 0
2868
2869 def can_be_any_bool(self) -> bool:
2870 return bool(
2871 self.partial_fallback.type
2872 and self.partial_fallback.type.fullname != "builtins.tuple"
2873 and self.partial_fallback.type.names.get("__bool__")
2874 )
2875
2876 def length(self) -> int:
2877 return len(self.items)
2878
2879 def accept(self, visitor: TypeVisitor[T]) -> T:
2880 return visitor.visit_tuple_type(self)
2881
2882 def __hash__(self) -> int:
2883 return hash((tuple(self.items), self.partial_fallback))
2884
2885 def __eq__(self, other: object) -> bool:
2886 if not isinstance(other, TupleType):
2887 return NotImplemented
2888 return self.items == other.items and self.partial_fallback == other.partial_fallback
2889
2890 def serialize(self) -> JsonDict:
2891 return {
2892 ".class": "TupleType",
2893 "items": [t.serialize() for t in self.items],
2894 "partial_fallback": self.partial_fallback.serialize(),
2895 "implicit": self.implicit,
2896 }
2897
2898 @classmethod
2899 def deserialize(cls, data: JsonDict) -> TupleType:
2900 assert data[".class"] == "TupleType"
2901 return TupleType(
2902 [deserialize_type(t) for t in data["items"]],
2903 Instance.deserialize(data["partial_fallback"]),
2904 implicit=data["implicit"],
2905 )
2906
2907 def write(self, data: WriteBuffer) -> None:
2908 write_tag(data, TUPLE_TYPE)
2909 self.partial_fallback.write(data)
2910 write_type_list(data, self.items)
2911 write_bool(data, self.implicit)
2912 write_tag(data, END_TAG)
2913
2914 @classmethod
2915 def read(cls, data: ReadBuffer) -> TupleType:
2916 assert read_tag(data) == INSTANCE
2917 fallback = Instance.read(data)
2918 ret = TupleType(read_type_list(data), fallback, implicit=read_bool(data))
2919 assert read_tag(data) == END_TAG
2920 return ret
2921
2922 def copy_modified(
2923 self, *, fallback: Instance | None = None, items: list[Type] | None = None
2924 ) -> TupleType:
2925 if fallback is None:
2926 fallback = self.partial_fallback
2927 if items is None:
2928 items = self.items
2929 return TupleType(items, fallback, self.line, self.column)
2930
2931 def slice(
2932 self, begin: int | None, end: int | None, stride: int | None, *, fallback: Instance | None
2933 ) -> TupleType | None:
2934 if fallback is None:
2935 fallback = self.partial_fallback
2936
2937 if stride == 0:
2938 return None
2939
2940 if any(isinstance(t, UnpackType) for t in self.items):
2941 total = len(self.items)
2942 unpack_index = find_unpack_in_list(self.items)
2943 assert unpack_index is not None
2944 if begin is None and end is None:
2945 # We special-case this to support reversing variadic tuples.
2946 # General support for slicing is tricky, so we handle only simple cases.
2947 if stride == -1:
2948 slice_items = self.items[::-1]
2949 elif stride is None or stride == 1:
2950 slice_items = self.items
2951 else:
2952 return None
2953 elif (begin is None or unpack_index >= begin >= 0) and (
2954 end is not None and unpack_index >= end >= 0
2955 ):
2956 # Start and end are in the prefix, everything works in this case.
2957 slice_items = self.items[begin:end:stride]
2958 elif (begin is not None and unpack_index - total < begin < 0) and (
2959 end is None or unpack_index - total < end < 0
2960 ):
2961 # Start and end are in the suffix, everything works in this case.
2962 slice_items = self.items[begin:end:stride]
2963 elif (begin is None or unpack_index >= begin >= 0) and (
2964 end is None or unpack_index - total < end < 0
2965 ):
2966 # Start in the prefix, end in the suffix, we can support only trivial strides.
2967 if stride is None or stride == 1:
2968 slice_items = self.items[begin:end:stride]
2969 else:
2970 return None
2971 elif (begin is not None and unpack_index - total < begin < 0) and (
2972 end is not None and unpack_index >= end >= 0
2973 ):
2974 # Start in the suffix, end in the prefix, we can support only trivial strides.
2975 if stride is None or stride == -1:
2976 slice_items = self.items[begin:end:stride]
2977 else:
2978 return None
2979 else:
2980 # TODO: there some additional cases we can support for homogeneous variadic
2981 # items, we can "eat away" finite number of items.
2982 return None
2983 else:
2984 slice_items = self.items[begin:end:stride]
2985 return TupleType(slice_items, fallback, self.line, self.column, self.implicit)
2986
2987
2988 class TypedDictItem(NamedTuple):
2989 """Type, mutability and requiredness of an item in a TypedDict.
2990
2991 If typ is `None`, the item comes from a missing item in an open TypedDict, and
2992 the type should be treated as if it were a `builtins.object`. (Missing items in
2993 closed TypedDicts will have an uninhabited type.)
2994
2995 TODO: pass a `builtins.object` instead of None when TypedDictType gains a
2996 proper extra_items field.
2997 """
2998
2999 typ: Type | None
3000 required: bool
3001 readonly: bool
3002
3003 @property
3004 def mutable(self) -> bool:
3005 return not self.readonly
3006
3007
3008 class TypedDictType(ProperType):
3009 """Type of TypedDict object {'k1': v1, ..., 'kn': vn}.
3010
3011 A TypedDict object is a dictionary with specific string (literal) keys. Each
3012 key has a value with a distinct type that depends on the key. TypedDict objects
3013 are normal dict objects at runtime.
3014
3015 A TypedDictType can be either named or anonymous. If it's anonymous, its
3016 fallback will be typing_extensions._TypedDict (Instance). _TypedDict is a subclass
3017 of Mapping[str, object] and defines all non-mapping dict methods that TypedDict
3018 supports. Some dict methods are unsafe and not supported. _TypedDict isn't defined
3019 at runtime.
3020
3021 If a TypedDict is named, its fallback will be an Instance of the named type
3022 (ex: "Point") whose TypeInfo has a typeddict_type that is anonymous. This
3023 is similar to how named tuples work.
3024
3025 TODO: The fallback structure is perhaps overly complicated.
3026 """
3027
3028 __slots__ = (
3029 "items",
3030 "required_keys",
3031 "readonly_keys",
3032 "is_closed",
3033 "fallback",
3034 "extra_items_from",
3035 "to_be_mutated",
3036 )
3037
3038 items: dict[str, Type] # item_name -> item_type
3039 required_keys: set[str]
3040 readonly_keys: set[str]
3041 fallback: Instance
3042
3043 extra_items_from: list[ProperType] # only used during semantic analysis
3044 to_be_mutated: bool # only used in a plugin for `.update`, `|=`, etc
3045
3046 def __init__(
3047 self,
3048 items: dict[str, Type],
3049 required_keys: set[str],
3050 readonly_keys: set[str],
3051 fallback: Instance,
3052 line: int = -1,
3053 column: int = -1,
3054 *,
3055 is_closed: bool = False,
3056 ) -> None:
3057 super().__init__(line, column)
3058 self.items = items
3059 self.required_keys = required_keys
3060 self.readonly_keys = readonly_keys
3061 self.is_closed = is_closed
3062 self.fallback = fallback
3063 self.can_be_true = len(self.items) > 0
3064 self.can_be_false = len(self.required_keys) == 0
3065 self.extra_items_from = []
3066 self.to_be_mutated = False
3067
3068 def accept(self, visitor: TypeVisitor[T]) -> T:
3069 return visitor.visit_typeddict_type(self)
3070
3071 def __hash__(self) -> int:
3072 return hash(
3073 (
3074 frozenset(self.items.items()),
3075 self.fallback,
3076 frozenset(self.required_keys),
3077 frozenset(self.readonly_keys),
3078 self.is_closed,
3079 )
3080 )
3081
3082 def __eq__(self, other: object) -> bool:
3083 if not isinstance(other, TypedDictType):
3084 return NotImplemented
3085 if self is other:
3086 return True
3087 return (
3088 frozenset(self.items.keys()) == frozenset(other.items.keys())
3089 and all(
3090 left_item_type == right_item_type
3091 for (_, left_item_type, right_item_type) in self.zip(other)
3092 )
3093 and self.fallback == other.fallback
3094 and self.required_keys == other.required_keys
3095 and self.readonly_keys == other.readonly_keys
3096 and self.is_closed == other.is_closed
3097 )
3098
3099 def serialize(self) -> JsonDict:
3100 return {
3101 ".class": "TypedDictType",
3102 "items": [[n, t.serialize()] for (n, t) in self.items.items()],
3103 "required_keys": sorted(self.required_keys),
3104 "readonly_keys": sorted(self.readonly_keys),
3105 "fallback": self.fallback.serialize(),
3106 "is_closed": self.is_closed,
3107 }
3108
3109 @classmethod
3110 def deserialize(cls, data: JsonDict) -> TypedDictType:
3111 assert data[".class"] == "TypedDictType"
3112 return TypedDictType(
3113 {n: deserialize_type(t) for (n, t) in data["items"]},
3114 set(data["required_keys"]),
3115 set(data["readonly_keys"]),
3116 Instance.deserialize(data["fallback"]),
3117 is_closed=bool(data["is_closed"]),
3118 )
3119
3120 def write(self, data: WriteBuffer) -> None:
3121 write_tag(data, TYPED_DICT_TYPE)
3122 self.fallback.write(data)
3123 write_type_map(data, self.items)
3124 write_str_list(data, sorted(self.required_keys))
3125 write_str_list(data, sorted(self.readonly_keys))
3126 write_bool(data, self.is_closed)
3127 write_tag(data, END_TAG)
3128
3129 @classmethod
3130 def read(cls, data: ReadBuffer) -> TypedDictType:
3131 assert read_tag(data) == INSTANCE
3132 fallback = Instance.read(data)
3133 ret = TypedDictType(
3134 read_type_map(data),
3135 set(read_str_list(data)),
3136 set(read_str_list(data)),
3137 fallback,
3138 is_closed=read_bool(data),
3139 )
3140 assert read_tag(data) == END_TAG
3141 return ret
3142
3143 @property
3144 def is_final(self) -> bool:
3145 return self.fallback.type.is_final
3146
3147 def is_anonymous(self) -> bool:
3148 return self.fallback.type.fullname in TPDICT_FB_NAMES
3149
3150 def create_anonymous_fallback(self) -> Instance:
3151 if self.is_anonymous():
3152 return self.fallback
3153 assert self.fallback.type.typeddict_type is not None
3154 return self.fallback.type.typeddict_type.create_anonymous_fallback()
3155
3156 def copy_modified(
3157 self,
3158 *,
3159 fallback: Instance | None = None,
3160 item_types: list[Type] | None = None,
3161 item_names: list[str] | None = None,
3162 required_keys: set[str] | None = None,
3163 readonly_keys: set[str] | None = None,
3164 is_closed: bool | None = None,
3165 ) -> TypedDictType:
3166 if fallback is None:
3167 fallback = self.fallback
3168 if item_types is None:
3169 items = self.items
3170 else:
3171 items = dict(zip(self.items, item_types))
3172 if required_keys is None:
3173 required_keys = self.required_keys
3174 if readonly_keys is None:
3175 readonly_keys = self.readonly_keys
3176 if is_closed is None:
3177 is_closed = self.is_closed
3178 if item_names is not None:
3179 items = {k: v for (k, v) in items.items() if k in item_names}
3180 required_keys &= set(item_names)
3181 return TypedDictType(
3182 items,
3183 required_keys,
3184 readonly_keys,
3185 fallback,
3186 self.line,
3187 self.column,
3188 is_closed=is_closed,
3189 )
3190
3191 def zip(self, right: TypedDictType) -> Iterable[tuple[str, Type, Type]]:
3192 left = self
3193 for item_name, left_item_type in left.items.items():
3194 right_item_type = right.items.get(item_name)
3195 if right_item_type is not None:
3196 yield (item_name, left_item_type, right_item_type)
3197
3198 def item(self, item_name: str) -> TypedDictItem:
3199 item_type = self.items.get(item_name)
3200 if item_type is not None:
3201 is_required = item_name in self.required_keys
3202 is_readonly = item_name in self.readonly_keys
3203 elif self.is_closed:
3204 item_type = UninhabitedType()
3205 is_required = False
3206 is_readonly = False
3207 else:
3208 is_required = False
3209 is_readonly = True
3210 return TypedDictItem(item_type, is_required, is_readonly)
3211
3212 def zipall(self, right: TypedDictType) -> Iterable[tuple[str, TypedDictItem, TypedDictItem]]:
3213 left = self
3214 for item_name in left.items:
3215 yield (item_name, left.item(item_name), right.item(item_name))
3216 for item_name in right.items:
3217 if item_name in left.items:
3218 continue
3219 yield (item_name, left.item(item_name), right.item(item_name))
3220
3221
3222 class RawExpressionType(ProperType):
3223 """A synthetic type representing some arbitrary expression that does not cleanly
3224 translate into a type.
3225
3226 This synthetic type is only used at the beginning stages of semantic analysis
3227 and should be completely removing during the process for mapping UnboundTypes to
3228 actual types: we either turn it into a LiteralType or an AnyType.
3229
3230 For example, suppose `Foo[1]` is initially represented as the following:
3231
3232 UnboundType(
3233 name='Foo',
3234 args=[
3235 RawExpressionType(value=1, base_type_name='builtins.int'),
3236 ],
3237 )
3238
3239 As we perform semantic analysis, this type will transform into one of two
3240 possible forms.
3241
3242 If 'Foo' was an alias for 'Literal' all along, this type is transformed into:
3243
3244 LiteralType(value=1, fallback=int_instance_here)
3245
3246 Alternatively, if 'Foo' is an unrelated class, we report an error and instead
3247 produce something like this:
3248
3249 Instance(type=typeinfo_for_foo, args=[AnyType(TypeOfAny.from_error))
3250
3251 If the "note" field is not None, the provided note will be reported alongside the
3252 error at this point.
3253
3254 Note: if "literal_value" is None, that means this object is representing some
3255 expression that cannot possibly be a parameter of Literal[...]. For example,
3256 "Foo[3j]" would be represented as:
3257
3258 UnboundType(
3259 name='Foo',
3260 args=[
3261 RawExpressionType(value=None, base_type_name='builtins.complex'),
3262 ],
3263 )
3264 """
3265
3266 __slots__ = ("literal_value", "base_type_name", "note")
3267
3268 def __init__(
3269 self,
3270 literal_value: LiteralValue | None,
3271 base_type_name: str,
3272 line: int = -1,
3273 column: int = -1,
3274 note: str | None = None,
3275 ) -> None:
3276 super().__init__(line, column)
3277 self.literal_value = literal_value
3278 self.base_type_name = base_type_name
3279 self.note = note
3280
3281 def simple_name(self) -> str:
3282 return self.base_type_name.replace("builtins.", "")
3283
3284 def accept(self, visitor: TypeVisitor[T]) -> T:
3285 assert isinstance(visitor, SyntheticTypeVisitor)
3286 ret: T = visitor.visit_raw_expression_type(self)
3287 return ret
3288
3289 def serialize(self) -> JsonDict:
3290 assert False, "Synthetic types don't serialize"
3291
3292 def __hash__(self) -> int:
3293 return hash((self.literal_value, self.base_type_name))
3294
3295 def __eq__(self, other: object) -> bool:
3296 if isinstance(other, RawExpressionType):
3297 return (
3298 self.base_type_name == other.base_type_name
3299 and self.literal_value == other.literal_value
3300 )
3301 else:
3302 return NotImplemented
3303
3304
3305 class LiteralType(ProperType):
3306 """The type of a Literal instance. Literal[Value]
3307
3308 A Literal always consists of:
3309
3310 1. A native Python object corresponding to the contained inner value
3311 2. A fallback for this Literal. The fallback also corresponds to the
3312 parent type this Literal subtypes.
3313
3314 For example, 'Literal[42]' is represented as
3315 'LiteralType(value=42, fallback=instance_of_int)'
3316
3317 As another example, `Literal[Color.RED]` (where Color is an enum) is
3318 represented as `LiteralType(value="RED", fallback=instance_of_color)'.
3319 """
3320
3321 __slots__ = ("value", "fallback", "_hash")
3322
3323 def __init__(
3324 self, value: LiteralValue, fallback: Instance, line: int = -1, column: int = -1
3325 ) -> None:
3326 super().__init__(line, column)
3327 self.value = value
3328 self.fallback = fallback
3329
3330 # NOTE: Enum types are always truthy by default, but this can be changed
3331 # in subclasses, so we need to get the truthyness from the Enum
3332 # type rather than base it on the value (which is a non-empty
3333 # string for enums, so always truthy)
3334 # TODO: We should consider moving this branch to the `can_be_true`
3335 # `can_be_false` properties instead, so the truthyness only
3336 # needs to be determined once per set of Enum literals.
3337 # However, the same can be said for `TypeAliasType` in some
3338 # cases and we only set the default based on the type it is
3339 # aliasing. So if we decide to change this, we may want to
3340 # change that as well. perf_compare output was inconclusive
3341 # but slightly favored this version, probably because we have
3342 # almost no test cases where we would redundantly compute
3343 # `can_be_false`/`can_be_true`.
3344 def can_be_false_default(self) -> bool:
3345 if self.fallback.type.is_enum:
3346 return self.fallback.can_be_false
3347 return not self.value
3348
3349 def can_be_true_default(self) -> bool:
3350 if self.fallback.type.is_enum:
3351 return self.fallback.can_be_true
3352 return bool(self.value)
3353
3354 def accept(self, visitor: TypeVisitor[T]) -> T:
3355 return visitor.visit_literal_type(self)
3356
3357 def __hash__(self) -> int:
3358 # Intentionally a subset of __eq__ for perf
3359 return hash(self.value)
3360
3361 def __eq__(self, other: object) -> bool:
3362 if isinstance(other, LiteralType):
3363 return self.value == other.value and self.fallback == other.fallback
3364 else:
3365 return NotImplemented
3366
3367 def is_enum_literal(self) -> bool:
3368 return self.fallback.type.is_enum
3369
3370 def value_repr(self) -> str:
3371 """Returns the string representation of the underlying type.
3372
3373 This function is almost equivalent to running `repr(self.value)`,
3374 except it includes some additional logic to correctly handle cases
3375 where the value is a string, byte string, a unicode string, or an enum.
3376 """
3377 raw = repr(self.value)
3378 fallback_name = self.fallback.type.fullname
3379
3380 # If this is backed by an enum,
3381 if self.is_enum_literal():
3382 return f"{fallback_name}.{self.value}"
3383
3384 if fallback_name == "builtins.bytes":
3385 # Note: 'builtins.bytes' only appears in Python 3, so we want to
3386 # explicitly prefix with a "b"
3387 return "b" + raw
3388 else:
3389 # 'builtins.str' could mean either depending on context, but either way
3390 # we don't prefix: it's the "native" string. And of course, if value is
3391 # some other type, we just return that string repr directly.
3392 return raw
3393
3394 def serialize(self) -> JsonDict | str:
3395 return {
3396 ".class": "LiteralType",
3397 "value": self.value,
3398 "fallback": self.fallback.serialize(),
3399 }
3400
3401 @classmethod
3402 def deserialize(cls, data: JsonDict) -> LiteralType:
3403 assert data[".class"] == "LiteralType"
3404 return LiteralType(value=data["value"], fallback=Instance.deserialize(data["fallback"]))
3405
3406 def write(self, data: WriteBuffer) -> None:
3407 write_tag(data, LITERAL_TYPE)
3408 self.fallback.write(data)
3409 write_literal(data, self.value)
3410 write_tag(data, END_TAG)
3411
3412 @classmethod
3413 def read(cls, data: ReadBuffer) -> LiteralType:
3414 assert read_tag(data) == INSTANCE
3415 fallback = Instance.read(data)
3416 tag = read_tag(data)
3417 ret = LiteralType(read_literal(data, tag), fallback)
3418 assert read_tag(data) == END_TAG
3419 return ret
3420
3421
3422 class UnionType(ProperType):
3423 """The union type Union[T1, ..., Tn] (at least one type argument)."""
3424
3425 __slots__ = (
3426 "items",
3427 "is_evaluated",
3428 "uses_pep604_syntax",
3429 "original_str_expr",
3430 "original_str_fallback",
3431 )
3432
3433 def __init__(
3434 self,
3435 items: Sequence[Type],
3436 line: int = -1,
3437 column: int = -1,
3438 *,
3439 is_evaluated: bool = True,
3440 uses_pep604_syntax: bool = False,
3441 ) -> None:
3442 super().__init__(line, column)
3443 # We must keep this false to avoid crashes during semantic analysis.
3444 # TODO: maybe switch this to True during type-checking pass?
3445 self.items = flatten_nested_unions(items, handle_type_alias_type=False)
3446 # is_evaluated should be set to false for type comments and string literals
3447 self.is_evaluated = is_evaluated
3448 # uses_pep604_syntax is True if Union uses OR syntax (X | Y)
3449 self.uses_pep604_syntax = uses_pep604_syntax
3450 # The meaning of these two is the same as for UnboundType. A UnionType can be
3451 # return by type parser from a string "A|B", and we need to be able to fall back
3452 # to plain string, when such a string appears inside a Literal[...].
3453 self.original_str_expr: str | None = None
3454 self.original_str_fallback: str | None = None
3455
3456 def can_be_true_default(self) -> bool:
3457 return any(item.can_be_true for item in self.items)
3458
3459 def can_be_false_default(self) -> bool:
3460 return any(item.can_be_false for item in self.items)
3461
3462 def __hash__(self) -> int:
3463 return hash(frozenset(self.items))
3464
3465 def __eq__(self, other: object) -> bool:
3466 if not isinstance(other, UnionType):
3467 return NotImplemented
3468 if self is other:
3469 return True
3470 return frozenset(self.items) == frozenset(other.items)
3471
3472 @overload
3473 @staticmethod
3474 def make_union(
3475 items: Sequence[ProperType], line: int = -1, column: int = -1
3476 ) -> ProperType: ...
3477
3478 @overload
3479 @staticmethod
3480 def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type: ...
3481
3482 @staticmethod
3483 def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type:
3484 if len(items) > 1:
3485 return UnionType(items, line, column)
3486 elif len(items) == 1:
3487 return items[0]
3488 else:
3489 return UninhabitedType()
3490
3491 def length(self) -> int:
3492 return len(self.items)
3493
3494 def accept(self, visitor: TypeVisitor[T]) -> T:
3495 return visitor.visit_union_type(self)
3496
3497 def relevant_items(self) -> list[Type]:
3498 """Removes NoneTypes from Unions when strict Optional checking is off."""
3499 if state.strict_optional:
3500 return self.items
3501 else:
3502 return [i for i in self.items if not isinstance(get_proper_type(i), NoneType)]
3503
3504 def serialize(self) -> JsonDict:
3505 return {
3506 ".class": "UnionType",
3507 "items": [t.serialize() for t in self.items],
3508 "uses_pep604_syntax": self.uses_pep604_syntax,
3509 }
3510
3511 @classmethod
3512 def deserialize(cls, data: JsonDict) -> UnionType:
3513 assert data[".class"] == "UnionType"
3514 return UnionType(
3515 [deserialize_type(t) for t in data["items"]],
3516 uses_pep604_syntax=data["uses_pep604_syntax"],
3517 )
3518
3519 def write(self, data: WriteBuffer) -> None:
3520 write_tag(data, UNION_TYPE)
3521 write_type_list(data, self.items)
3522 write_bool(data, self.uses_pep604_syntax)
3523 write_tag(data, END_TAG)
3524
3525 @classmethod
3526 def read(cls, data: ReadBuffer) -> UnionType:
3527 ret = UnionType(read_type_list(data), uses_pep604_syntax=read_bool(data))
3528 assert read_tag(data) == END_TAG
3529 return ret
3530
3531
3532 class PartialType(ProperType):
3533 """Type such as List[?] where type arguments are unknown, or partial None type.
3534
3535 These are used for inferring types in multiphase initialization such as this:
3536
3537 x = [] # x gets a partial type List[?], as item type is unknown
3538 x.append(1) # partial type gets replaced with normal type List[int]
3539
3540 Or with None:
3541
3542 x = None # x gets a partial type None
3543 if c:
3544 x = 1 # Infer actual type int for x
3545 """
3546
3547 __slots__ = ("type", "var", "value_type")
3548
3549 # None for the 'None' partial type; otherwise a generic class
3550 type: mypy.nodes.TypeInfo | None
3551 var: mypy.nodes.Var
3552 # For partial defaultdict[K, V], the type V (K is unknown). If V is generic,
3553 # the type argument is Any and will be replaced later.
3554 value_type: Instance | None
3555
3556 def __init__(
3557 self,
3558 type: mypy.nodes.TypeInfo | None,
3559 var: mypy.nodes.Var,
3560 value_type: Instance | None = None,
3561 ) -> None:
3562 super().__init__()
3563 self.type = type
3564 self.var = var
3565 self.value_type = value_type
3566
3567 def accept(self, visitor: TypeVisitor[T]) -> T:
3568 return visitor.visit_partial_type(self)
3569
3570
3571 class EllipsisType(ProperType):
3572 """The type ... (ellipsis).
3573
3574 This is not a real type but a syntactic AST construct, used in Callable[..., T], for example.
3575
3576 A semantically analyzed type will never have ellipsis types.
3577 """
3578
3579 __slots__ = ()
3580
3581 def accept(self, visitor: TypeVisitor[T]) -> T:
3582 assert isinstance(visitor, SyntheticTypeVisitor)
3583 ret: T = visitor.visit_ellipsis_type(self)
3584 return ret
3585
3586 def serialize(self) -> JsonDict:
3587 assert False, "Synthetic types don't serialize"
3588
3589
3590 class TypeType(ProperType):
3591 """For types like Type[User] or TypeForm[User | None].
3592
3593 Type[C] annotates variables that are class objects, constrained by
3594 the type argument. See PEP 484 for more details.
3595
3596 TypeForm[T] annotates variables that hold the result of evaluating
3597 a type expression. See PEP 747 for more details.
3598
3599 We may encounter expressions whose values are specific classes;
3600 those are represented as callables (possibly overloaded)
3601 corresponding to the class's constructor's signature and returning
3602 an instance of that class. The difference with Type[C] is that
3603 those callables always represent the exact class given as the
3604 return type; Type[C] represents any class that's a subclass of C,
3605 and C may also be a type variable or a union (or Any).
3606
3607 Many questions around subtype relationships between Type[C1] and
3608 def(...) -> C2 are answered by looking at the subtype
3609 relationships between C1 and C2, since Type[] is considered
3610 covariant.
3611
3612 There's an unsolved problem with constructor signatures (also
3613 unsolved in PEP 484): calling a variable whose type is Type[C]
3614 assumes the constructor signature for C, even though a subclass of
3615 C might completely change the constructor signature. For now we
3616 just assume that users of Type[C] are careful not to do that (in
3617 the future we might detect when they are violating that
3618 assumption).
3619 """
3620
3621 __slots__ = ("item", "is_type_form")
3622
3623 # This can't be everything, but it can be a class reference,
3624 # a generic class instance, a union, Any, a type variable...
3625 item: ProperType
3626
3627 # If True then this TypeType represents a TypeForm[T].
3628 # If False then this TypeType represents a Type[C].
3629 is_type_form: bool
3630
3631 def __init__(
3632 self,
3633 item: Bogus[Instance | AnyType | TypeVarType | TupleType | NoneType | CallableType],
3634 *,
3635 line: int = -1,
3636 column: int = -1,
3637 is_type_form: bool = False,
3638 ) -> None:
3639 """To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of
3640 type UnionType must be handled through make_normalized static method.
3641 """
3642 super().__init__(line, column)
3643 self.item = item
3644 self.is_type_form = is_type_form
3645
3646 @staticmethod
3647 def make_normalized(
3648 item: Type, *, line: int = -1, column: int = -1, is_type_form: bool = False
3649 ) -> ProperType:
3650 item = get_proper_type(item)
3651 if is_type_form:
3652 # Don't convert TypeForm[X | Y] to (TypeForm[X] | TypeForm[Y])
3653 pass
3654 else:
3655 if isinstance(item, UnionType):
3656 return UnionType.make_union(
3657 [TypeType.make_normalized(union_item) for union_item in item.items],
3658 line=line,
3659 column=column,
3660 )
3661 return TypeType(item, line=line, column=column, is_type_form=is_type_form) # type: ignore[arg-type]
3662
3663 def accept(self, visitor: TypeVisitor[T]) -> T:
3664 return visitor.visit_type_type(self)
3665
3666 def __hash__(self) -> int:
3667 return hash(self.item)
3668
3669 def __eq__(self, other: object) -> bool:
3670 if not isinstance(other, TypeType):
3671 return NotImplemented
3672 return self.item == other.item and self.is_type_form == other.is_type_form
3673
3674 def serialize(self) -> JsonDict:
3675 return {
3676 ".class": "TypeType",
3677 "item": self.item.serialize(),
3678 "is_type_form": self.is_type_form,
3679 }
3680
3681 @classmethod
3682 def deserialize(cls, data: JsonDict) -> Type:
3683 assert data[".class"] == "TypeType"
3684 return TypeType.make_normalized(
3685 deserialize_type(data["item"]), is_type_form=data["is_type_form"]
3686 )
3687
3688 def write(self, data: WriteBuffer) -> None:
3689 write_tag(data, TYPE_TYPE)
3690 self.item.write(data)
3691 write_bool(data, self.is_type_form)
3692 write_tag(data, END_TAG)
3693
3694 @classmethod
3695 def read(cls, data: ReadBuffer) -> Type:
3696 ret = TypeType.make_normalized(read_type(data), is_type_form=read_bool(data))
3697 assert read_tag(data) == END_TAG
3698 return ret
3699
3700
3701 class PlaceholderType(ProperType):
3702 """Temporary, yet-unknown type during semantic analysis.
3703
3704 This is needed when there's a reference to a type before the real symbol
3705 table entry of the target type is available (specifically, we use a
3706 temporary PlaceholderNode symbol node). Consider this example:
3707
3708 class str(Sequence[str]): ...
3709
3710 We use a PlaceholderType for the 'str' in 'Sequence[str]' since we can't create
3711 a TypeInfo for 'str' until all base classes have been resolved. We'll soon
3712 perform another analysis iteration which replaces the base class with a complete
3713 type without any placeholders. After semantic analysis, no placeholder types must
3714 exist.
3715 """
3716
3717 __slots__ = ("fullname", "args")
3718
3719 def __init__(self, fullname: str | None, args: list[Type], line: int) -> None:
3720 super().__init__(line)
3721 self.fullname = fullname # Must be a valid full name of an actual node (or None).
3722 self.args = args
3723
3724 def accept(self, visitor: TypeVisitor[T]) -> T:
3725 assert isinstance(visitor, SyntheticTypeVisitor)
3726 ret: T = visitor.visit_placeholder_type(self)
3727 return ret
3728
3729 def __hash__(self) -> int:
3730 return hash((self.fullname, tuple(self.args)))
3731
3732 def __eq__(self, other: object) -> bool:
3733 if not isinstance(other, PlaceholderType):
3734 return NotImplemented
3735 return self.fullname == other.fullname and self.args == other.args
3736
3737 def serialize(self) -> str:
3738 # We should never get here since all placeholders should be replaced
3739 # during semantic analysis.
3740 assert False, f"Internal error: unresolved placeholder type {self.fullname}"
3741
3742
3743 @overload
3744 def get_proper_type(typ: None) -> None: ...
3745
3746
3747 @overload
3748 def get_proper_type(typ: Type) -> ProperType: ...
3749
3750
3751 def get_proper_type(typ: Type | None) -> ProperType | None:
3752 """Get the expansion of a type alias type.
3753
3754 If the type is already a proper type, this is a no-op. Use this function
3755 wherever a decision is made on a call like e.g. 'if isinstance(typ, UnionType): ...',
3756 because 'typ' in this case may be an alias to union. Note: if after making the decision
3757 on the isinstance() call you pass on the original type (and not one of its components)
3758 it is recommended to *always* pass on the unexpanded alias.
3759 """
3760 if typ is None:
3761 return None
3762 # TODO: this is an ugly hack, remove.
3763 if isinstance(typ, TypeGuardedType):
3764 typ = typ.type_guard
3765 while isinstance(typ, TypeAliasType):
3766 typ = typ._expand_once()
3767 # TODO: store the name of original type alias on this type, so we can show it in errors.
3768 return cast(ProperType, typ)
3769
3770
3771 @overload
3772 def get_proper_types(types: list[Type] | tuple[Type, ...]) -> list[ProperType]: ...
3773
3774
3775 @overload
3776 def get_proper_types(
3777 types: list[Type | None] | tuple[Type | None, ...],
3778 ) -> list[ProperType | None]: ...
3779
3780
3781 def get_proper_types(
3782 types: list[Type] | list[Type | None] | tuple[Type | None, ...],
3783 ) -> list[ProperType] | list[ProperType | None]:
3784 if isinstance(types, list):
3785 typelist = types
3786 # Optimize for the common case so that we don't need to allocate anything
3787 if not any(isinstance(t, (TypeAliasType, TypeGuardedType)) for t in typelist):
3788 return cast("list[ProperType]", typelist)
3789 return [get_proper_type(t) for t in typelist]
3790 else:
3791 return [get_proper_type(t) for t in types]
3792
3793
3794 # We split off the type visitor base classes to another module
3795 # to make it easier to gradually get modules working with mypyc.
3796 # Import them here, after the types are defined.
3797 # This is intended as a re-export also.
3798 from mypy.type_visitor import (
3799 ALL_STRATEGY as ALL_STRATEGY,
3800 ANY_STRATEGY as ANY_STRATEGY,
3801 BoolTypeQuery as BoolTypeQuery,
3802 SyntheticTypeVisitor as SyntheticTypeVisitor,
3803 TypeQuery as TypeQuery,
3804 TypeTranslator as TypeTranslator,
3805 TypeVisitor as TypeVisitor,
3806 )
3807
3808
3809 class TypeStrVisitor(SyntheticTypeVisitor[str]):
3810 """Visitor for pretty-printing types into strings.
3811
3812 This is mostly for debugging/testing.
3813
3814 Do not preserve original formatting.
3815
3816 Notes:
3817 - Represent unbound types as Foo? or Foo?[...].
3818 - Represent the NoneType type as None.
3819 - Represent Union[x, y] as x | y
3820 """
3821
3822 def __init__(self, id_mapper: IdMapper | None = None, *, options: Options) -> None:
3823 self.id_mapper = id_mapper
3824 self.options = options
3825 self.dotted_aliases: set[TypeAliasType] | None = None
3826
3827 def visit_unbound_type(self, t: UnboundType, /) -> str:
3828 s = t.name + "?"
3829 if t.args:
3830 s += f"[{self.list_str(t.args)}]"
3831 return s
3832
3833 def visit_type_list(self, t: TypeList, /) -> str:
3834 return f"<TypeList {self.list_str(t.items)}>"
3835
3836 def visit_callable_argument(self, t: CallableArgument, /) -> str:
3837 typ = t.typ.accept(self)
3838 if t.name is None:
3839 return f"{t.constructor}({typ})"
3840 else:
3841 return f"{t.constructor}({typ}, {t.name})"
3842
3843 def visit_any(self, t: AnyType, /) -> str:
3844 return "Any"
3845
3846 def visit_none_type(self, t: NoneType, /) -> str:
3847 return "None"
3848
3849 def visit_uninhabited_type(self, t: UninhabitedType, /) -> str:
3850 return "Never"
3851
3852 def visit_erased_type(self, t: ErasedType, /) -> str:
3853 return "<Erased>"
3854
3855 def visit_deleted_type(self, t: DeletedType, /) -> str:
3856 if t.source is None:
3857 return "<Deleted>"
3858 else:
3859 return f"<Deleted '{t.source}'>"
3860
3861 def visit_instance(self, t: Instance, /) -> str:
3862 fullname = t.type.fullname
3863 if not self.options.reveal_verbose_types and fullname.startswith("builtins."):
3864 fullname = t.type.name
3865 if t.last_known_value and not t.args:
3866 # Instances with a literal fallback should never be generic. If they are,
3867 # something went wrong so we fall back to showing the full Instance repr.
3868 s = f"{t.last_known_value.accept(self)}?"
3869
3870 else:
3871 s = fullname or t.type.name or "<???>"
3872
3873 if t.args:
3874 if t.type.fullname == "builtins.tuple":
3875 assert len(t.args) == 1
3876 s += f"[{self.list_str(t.args)}, ...]"
3877 else:
3878 s += f"[{self.list_str(t.args)}]"
3879 elif t.type.has_type_var_tuple_type and len(t.type.type_vars) == 1:
3880 s += "[()]"
3881 if self.id_mapper:
3882 s += f"<{self.id_mapper.id(t.type)}>"
3883 return s
3884
3885 def visit_type_var(self, t: TypeVarType, /) -> str:
3886 if not self.options.reveal_verbose_types:
3887 s = t.name
3888 else:
3889 s = f"{t.name}`{t.id}"
3890 if self.id_mapper and t.upper_bound:
3891 s += f"(upper_bound={t.upper_bound.accept(self)})"
3892 if t.has_default() and self.options.reveal_verbose_types:
3893 s += f" = {t.default.accept(self)}"
3894 # TODO: disambiguate type variables with same name using namespace.
3895 # We should reuse find_type_overlaps() and scoped_type_var_name().
3896 return s
3897
3898 def visit_param_spec(self, t: ParamSpecType, /) -> str:
3899 # prefixes are displayed as Concatenate
3900 s = ""
3901 if t.prefix.arg_types:
3902 s += f"[{self.list_str(t.prefix.arg_types)}, **"
3903 if not self.options.reveal_verbose_types:
3904 s += t.name_with_suffix()
3905 else:
3906 s += f"{t.name_with_suffix()}`{t.id}"
3907 if t.prefix.arg_types:
3908 s += "]"
3909 if t.has_default() and self.options.reveal_verbose_types:
3910 s += f" = {t.default.accept(self)}"
3911 return s
3912
3913 def visit_parameters(self, t: Parameters, /) -> str:
3914 # This is copied from visit_callable -- is there a way to decrease duplication?
3915 if t.is_ellipsis_args:
3916 return "..."
3917
3918 s = ""
3919 bare_asterisk = False
3920 for i in range(len(t.arg_types)):
3921 if s != "":
3922 s += ", "
3923 if t.arg_kinds[i].is_named() and not bare_asterisk:
3924 s += "*, "
3925 bare_asterisk = True
3926 if t.arg_kinds[i] == ARG_STAR:
3927 s += "*"
3928 if t.arg_kinds[i] == ARG_STAR2:
3929 s += "**"
3930 name = t.arg_names[i]
3931 if name:
3932 s += f"{name}: "
3933 r = t.arg_types[i].accept(self)
3934
3935 s += r
3936
3937 if t.arg_kinds[i].is_optional():
3938 s += " ="
3939
3940 return f"[{s}]"
3941
3942 def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> str:
3943 if not self.options.reveal_verbose_types:
3944 s = t.name
3945 else:
3946 s = f"{t.name}`{t.id}"
3947 if t.has_default() and self.options.reveal_verbose_types:
3948 s += f" = {t.default.accept(self)}"
3949 return s
3950
3951 def visit_callable_type(self, t: CallableType, /) -> str:
3952 param_spec = t.param_spec()
3953 if param_spec is not None:
3954 num_skip = 2
3955 else:
3956 num_skip = 0
3957
3958 s = ""
3959 asterisk = False
3960 for i in range(len(t.arg_types) - num_skip):
3961 if s != "":
3962 s += ", "
3963 if t.arg_kinds[i].is_named() and not asterisk:
3964 s += "*, "
3965 asterisk = True
3966 if t.arg_kinds[i] == ARG_STAR:
3967 s += "*"
3968 asterisk = True
3969 if t.arg_kinds[i] == ARG_STAR2:
3970 s += "**"
3971 name = t.arg_names[i]
3972 if not name and not self.options.reveal_verbose_types:
3973 # Avoid ambiguous (and weird) formatting for anonymous args/kwargs.
3974 if t.arg_kinds[i] == ARG_STAR and isinstance(t.arg_types[i], UnpackType):
3975 name = "args"
3976 elif t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs:
3977 name = "kwargs"
3978 if name:
3979 s += name + ": "
3980 type_str = t.arg_types[i].accept(self)
3981 if t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs:
3982 if not self.options.reveal_verbose_types:
3983 type_str = f"**{type_str}"
3984 else:
3985 type_str = f"Unpack[{type_str}]"
3986 s += type_str
3987 if t.arg_kinds[i].is_optional():
3988 s += " ="
3989
3990 if param_spec is not None:
3991 n = param_spec.name
3992 if s:
3993 s += ", "
3994 s += f"*{n}.args, **{n}.kwargs"
3995 if param_spec.has_default():
3996 s += f" = {param_spec.default.accept(self)}"
3997
3998 s = f"({s})"
3999
4000 if not isinstance(get_proper_type(t.ret_type), NoneType):
4001 if t.type_guard is not None:
4002 s += f" -> TypeGuard[{t.type_guard.accept(self)}]"
4003 elif t.type_is is not None:
4004 s += f" -> TypeIs[{t.type_is.accept(self)}]"
4005 else:
4006 s += f" -> {t.ret_type.accept(self)}"
4007
4008 if t.variables:
4009 vs = []
4010 for var in t.variables:
4011 if isinstance(var, TypeVarType):
4012 if var.values:
4013 vals = f"({', '.join(val.accept(self) for val in var.values)})"
4014 vs.append(f"{var.name} in {vals}")
4015 elif not is_named_instance(var.upper_bound, "builtins.object"):
4016 vs.append(
4017 f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
4018 )
4019 else:
4020 vs.append(
4021 f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
4022 )
4023 else:
4024 # For other TypeVarLikeTypes, use the name and default
4025 vs.append(
4026 f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}"
4027 )
4028 s = f"[{', '.join(vs)}] {s}"
4029
4030 return f"def {s}"
4031
4032 def visit_overloaded(self, t: Overloaded, /) -> str:
4033 a = []
4034 for i in t.items:
4035 a.append(i.accept(self))
4036 return f"Overload({', '.join(a)})"
4037
4038 def visit_tuple_type(self, t: TupleType, /) -> str:
4039 s = self.list_str(t.items) or "()"
4040 if t.partial_fallback and t.partial_fallback.type:
4041 fallback_name = t.partial_fallback.type.fullname
4042 if fallback_name != "builtins.tuple":
4043 return f"tuple[{s}, fallback={t.partial_fallback.accept(self)}]"
4044 return f"tuple[{s}]"
4045
4046 def visit_typeddict_type(self, t: TypedDictType, /) -> str:
4047 def item_str(name: str, typ: str) -> str:
4048 modifier = ""
4049 if name not in t.required_keys:
4050 modifier += "?"
4051 if name in t.readonly_keys:
4052 modifier += "="
4053 return f"{name!r}{modifier}: {typ}"
4054
4055 s = (
4056 "{"
4057 + ", ".join(item_str(name, typ.accept(self)) for name, typ in t.items.items())
4058 + "}"
4059 )
4060 if t.is_closed:
4061 s += ", closed=True"
4062 prefix = ""
4063 if t.fallback and t.fallback.type:
4064 if t.fallback.type.fullname not in TPDICT_FB_NAMES:
4065 if not self.options.reveal_verbose_types:
4066 prefix = t.fallback.type.fullname + ", "
4067 else:
4068 prefix = repr(t.fallback.type.fullname) + ", "
4069 return f"TypedDict({prefix}{s})"
4070
4071 def visit_raw_expression_type(self, t: RawExpressionType, /) -> str:
4072 # For bytes literals, the value is already escaped, just add quotes and b prefix
4073 if t.base_type_name == "builtins.bytes":
4074 # The value is already escaped (e.g., "foo" or "hello\\nworld")
4075 # Just add quotes and b prefix
4076 return f"b'{t.literal_value}'"
4077 return repr(t.literal_value)
4078
4079 def visit_literal_type(self, t: LiteralType, /) -> str:
4080 return f"Literal[{t.value_repr()}]"
4081
4082 def visit_union_type(self, t: UnionType, /) -> str:
4083 return self.list_str(t.items, use_or_syntax=True)
4084
4085 def visit_partial_type(self, t: PartialType, /) -> str:
4086 if t.type is None:
4087 return "<partial None>"
4088 else:
4089 return "<partial {}[{}]>".format(t.type.name, ", ".join(["?"] * len(t.type.type_vars)))
4090
4091 def visit_ellipsis_type(self, t: EllipsisType, /) -> str:
4092 return "..."
4093
4094 def visit_type_type(self, t: TypeType, /) -> str:
4095 if t.is_type_form:
4096 type_name = "TypeForm"
4097 else:
4098 type_name = "type"
4099 return f"{type_name}[{t.item.accept(self)}]"
4100
4101 def visit_placeholder_type(self, t: PlaceholderType, /) -> str:
4102 return f"<placeholder {t.fullname}>"
4103
4104 def visit_type_alias_type(self, t: TypeAliasType, /) -> str:
4105 if t.alias is None:
4106 return "<alias (unfixed)>"
4107 if not t.is_recursive:
4108 return get_proper_type(t).accept(self)
4109 if self.dotted_aliases is None:
4110 self.dotted_aliases = set()
4111 elif t in self.dotted_aliases:
4112 return "..."
4113 self.dotted_aliases.add(t)
4114 type_str = get_proper_type(t).accept(self)
4115 self.dotted_aliases.discard(t)
4116 return type_str
4117
4118 def visit_unpack_type(self, t: UnpackType, /) -> str:
4119 if not self.options.reveal_verbose_types:
4120 return f"*{t.type.accept(self)}"
4121 return f"Unpack[{t.type.accept(self)}]"
4122
4123 def list_str(self, a: Iterable[Type], *, use_or_syntax: bool = False) -> str:
4124 """Convert items of an array to strings (pretty-print types)
4125 and join the results with commas.
4126 """
4127 res = []
4128 for t in a:
4129 s = t.accept(self)
4130 if use_or_syntax and isinstance(get_proper_type(t), CallableType):
4131 res.append(f"({s})")
4132 else:
4133 res.append(s)
4134 sep = ", " if not use_or_syntax else " | "
4135 return sep.join(res)
4136
4137
4138 class TrivialSyntheticTypeTranslator(TypeTranslator, SyntheticTypeVisitor[Type]):
4139 """A base class for type translators that need to be run during semantic analysis."""
4140
4141 def visit_placeholder_type(self, t: PlaceholderType, /) -> Type:
4142 return t
4143
4144 def visit_callable_argument(self, t: CallableArgument, /) -> Type:
4145 return t
4146
4147 def visit_ellipsis_type(self, t: EllipsisType, /) -> Type:
4148 return t
4149
4150 def visit_raw_expression_type(self, t: RawExpressionType, /) -> Type:
4151 return t
4152
4153 def visit_type_list(self, t: TypeList, /) -> Type:
4154 return t
4155
4156
4157 class CollectAliasesVisitor(TypeQuery[list[mypy.nodes.TypeAlias]]):
4158 def __init__(self) -> None:
4159 super().__init__()
4160 self.seen_alias_nodes: set[mypy.nodes.TypeAlias] = set()
4161
4162 def strategy(self, items: list[list[mypy.nodes.TypeAlias]]) -> list[mypy.nodes.TypeAlias]:
4163 out = []
4164 for item in items:
4165 out.extend(item)
4166 return out
4167
4168 def visit_type_alias_type(self, t: TypeAliasType, /) -> list[mypy.nodes.TypeAlias]:
4169 assert t.alias is not None
4170 if t.alias not in self.seen_alias_nodes:
4171 self.seen_alias_nodes.add(t.alias)
4172 res = [t.alias] + t.alias.target.accept(self)
4173 else:
4174 res = []
4175 for arg in t.args:
4176 res.extend(arg.accept(self))
4177 return res
4178
4179
4180 def is_named_instance(t: Type, fullnames: str | tuple[str, ...]) -> TypeGuard[Instance]:
4181 if not isinstance(fullnames, tuple):
4182 fullnames = (fullnames,)
4183
4184 t = get_proper_type(t)
4185 return isinstance(t, Instance) and t.type.fullname in fullnames
4186
4187
4188 class HasTypeVars(BoolTypeQuery):
4189 """Visitor for querying whether a type has a type variable component."""
4190
4191 def __init__(self) -> None:
4192 super().__init__(ANY_STRATEGY)
4193 self.skip_alias_target = True
4194
4195 def visit_type_var(self, t: TypeVarType) -> bool:
4196 return True
4197
4198 def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:
4199 return True
4200
4201 def visit_param_spec(self, t: ParamSpecType) -> bool:
4202 return True
4203
4204
4205 def has_type_vars(typ: Type) -> bool:
4206 """Check if a type contains any type variables (recursively)."""
4207 return typ.accept(HasTypeVars())
4208
4209
4210 class HasRecursiveType(BoolTypeQuery):
4211 def __init__(self) -> None:
4212 super().__init__(ANY_STRATEGY)
4213
4214 def visit_type_alias_type(self, t: TypeAliasType) -> bool:
4215 return t.is_recursive or self.query_types(t.args)
4216
4217
4218 # Use singleton since this is hot (note: call reset() before using)
4219 _has_recursive_type: Final = HasRecursiveType()
4220
4221
4222 def has_recursive_types(typ: Type) -> bool:
4223 """Check if a type contains any recursive aliases (recursively)."""
4224 _has_recursive_type.reset()
4225 return typ.accept(_has_recursive_type)
4226
4227
4228 def split_with_prefix_and_suffix(
4229 types: tuple[Type, ...], prefix: int, suffix: int
4230 ) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]:
4231 if len(types) <= prefix + suffix:
4232 types = extend_args_for_prefix_and_suffix(types, prefix, suffix)
4233 if suffix:
4234 return types[:prefix], types[prefix:-suffix], types[-suffix:]
4235 else:
4236 return types[:prefix], types[prefix:], ()
4237
4238
4239 def extend_args_for_prefix_and_suffix(
4240 types: tuple[Type, ...], prefix: int, suffix: int
4241 ) -> tuple[Type, ...]:
4242 """Extend list of types by eating out from variadic tuple to satisfy prefix and suffix."""
4243 idx = None
4244 item = None
4245 for i, t in enumerate(types):
4246 if isinstance(t, UnpackType):
4247 p_type = get_proper_type(t.type)
4248 if isinstance(p_type, Instance) and p_type.type.fullname == "builtins.tuple":
4249 item = p_type.args[0]
4250 idx = i
4251 break
4252
4253 if idx is None:
4254 return types
4255 assert item is not None
4256 if idx < prefix:
4257 start = (item,) * (prefix - idx)
4258 else:
4259 start = ()
4260 if len(types) - idx - 1 < suffix:
4261 end = (item,) * (suffix - len(types) + idx + 1)
4262 else:
4263 end = ()
4264 return types[:idx] + start + (types[idx],) + end + types[idx + 1 :]
4265
4266
4267 def flatten_nested_unions(
4268 types: Sequence[Type], *, handle_type_alias_type: bool = True, handle_recursive: bool = True
4269 ) -> list[Type]:
4270 """Flatten nested unions in a type list."""
4271 if not isinstance(types, list):
4272 typelist = list(types)
4273 else:
4274 typelist = cast("list[Type]", types)
4275
4276 # Fast path: most of the time there is nothing to flatten
4277 if not any(isinstance(t, (TypeAliasType, UnionType)) for t in typelist): # type: ignore[misc]
4278 return typelist
4279
4280 flat_items: list[Type] = []
4281 for t in typelist:
4282 if handle_type_alias_type and isinstance(t, TypeAliasType):
4283 if not handle_recursive and t.is_recursive:
4284 tp: Type = t
4285 else:
4286 tp = get_proper_type(t)
4287 else:
4288 tp = t
4289 if isinstance(tp, ProperType) and isinstance(tp, UnionType):
4290 flat_items.extend(
4291 flatten_nested_unions(
4292 tp.items,
4293 handle_type_alias_type=handle_type_alias_type,
4294 handle_recursive=handle_recursive,
4295 )
4296 )
4297 else:
4298 # Must preserve original aliases when possible.
4299 flat_items.append(t)
4300 return flat_items
4301
4302
4303 def find_unpack_in_list(items: Sequence[Type]) -> int | None:
4304 unpack_index: int | None = None
4305 for i, item in enumerate(items):
4306 if isinstance(item, UnpackType):
4307 # We cannot fail here, so we must check this in an earlier
4308 # semanal phase.
4309 # Funky code here avoids mypyc narrowing the type of unpack_index.
4310 old_index = unpack_index
4311 assert old_index is None
4312 # Don't return so that we can also sanity-check there is only one.
4313 unpack_index = i
4314 return unpack_index
4315
4316
4317 def flatten_nested_tuples(types: Iterable[Type], handle_recursive: bool = True) -> list[Type]:
4318 """Recursively flatten TupleTypes nested with Unpack.
4319
4320 For example this will transform
4321 Tuple[A, Unpack[Tuple[B, Unpack[Tuple[C, D]]]]]
4322 into
4323 Tuple[A, B, C, D]
4324 """
4325 res = []
4326 for typ in types:
4327 if not isinstance(typ, UnpackType):
4328 res.append(typ)
4329 continue
4330 p_type = get_proper_type(typ.type)
4331 if (
4332 not isinstance(p_type, TupleType)
4333 or not handle_recursive
4334 and isinstance(typ.type, TypeAliasType)
4335 and typ.type.is_recursive
4336 ):
4337 res.append(typ)
4338 continue
4339 if isinstance(typ.type, TypeAliasType):
4340 items = []
4341 for item in p_type.items:
4342 if (
4343 isinstance(item, ProperType)
4344 and isinstance(item, Instance)
4345 or isinstance(item, TypeAliasType)
4346 ):
4347 if len(item.args) == 0:
4348 item = item.copy_modified()
4349 item.set_line(typ)
4350 items.append(item)
4351 else:
4352 items = p_type.items
4353 res.extend(flatten_nested_tuples(items))
4354 return res
4355
4356
4357 def is_literal_type(typ: ProperType, fallback_fullname: str, value: LiteralValue) -> bool:
4358 """Check if this type is a LiteralType with the given fallback type and value."""
4359 if isinstance(typ, Instance) and typ.last_known_value:
4360 typ = typ.last_known_value
4361 return (
4362 isinstance(typ, LiteralType)
4363 and typ.fallback.type.fullname == fallback_fullname
4364 and typ.value == value
4365 )
4366
4367
4368 def is_unannotated_any(t: Type) -> bool:
4369 """Check if type represents an implicit (unannotated) Any.
4370
4371 This is used to check for functions with unspecified/not fully specified types.
4372 """
4373 if not isinstance(t, ProperType):
4374 return False
4375 return isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated
4376
4377
4378 names: Final = globals().copy()
4379 names.pop("NOT_READY", None)
4380 deserialize_map: Final = {
4381 key: obj.deserialize
4382 for key, obj in names.items()
4383 if isinstance(obj, type) and issubclass(obj, Type) and obj is not Type
4384 }
4385
4386
4387 def callable_with_ellipsis(any_type: AnyType, ret_type: Type, fallback: Instance) -> CallableType:
4388 """Construct type Callable[..., ret_type]."""
4389 return CallableType(
4390 [any_type, any_type],
4391 [ARG_STAR, ARG_STAR2],
4392 [None, None],
4393 ret_type=ret_type,
4394 fallback=fallback,
4395 is_ellipsis_args=True,
4396 )
4397
4398
4399 def remove_dups(types: list[T]) -> list[T]:
4400 if len(types) <= 1:
4401 return types
4402 # Get unique elements in order of appearance
4403 all_types: set[T] = set()
4404 new_types: list[T] = []
4405 for t in types:
4406 if t not in all_types:
4407 new_types.append(t)
4408 all_types.add(t)
4409 return new_types
4410
4411
4412 def type_vars_as_args(type_vars: Sequence[TypeVarLikeType]) -> tuple[Type, ...]:
4413 """Represent type variables as they would appear in a type argument list."""
4414 args: list[Type] = []
4415 for tv in type_vars:
4416 if isinstance(tv, TypeVarTupleType):
4417 args.append(UnpackType(tv))
4418 else:
4419 args.append(tv)
4420 return tuple(args)
4421
4422
4423 # See docstring for mypy/cache.py for reserved tag ranges.
4424 # Instance-related tags.
4425 INSTANCE: Final[Tag] = 80
4426 INSTANCE_SIMPLE: Final[Tag] = 81
4427 INSTANCE_GENERIC: Final[Tag] = 82
4428 INSTANCE_STR: Final[Tag] = 83
4429 INSTANCE_FUNCTION: Final[Tag] = 84
4430 INSTANCE_INT: Final[Tag] = 85
4431 INSTANCE_BOOL: Final[Tag] = 86
4432 INSTANCE_OBJECT: Final[Tag] = 87
4433
4434 # Other type tags.
4435 TYPE_ALIAS_TYPE: Final[Tag] = 100
4436 TYPE_VAR_TYPE: Final[Tag] = 101
4437 PARAM_SPEC_TYPE: Final[Tag] = 102
4438 TYPE_VAR_TUPLE_TYPE: Final[Tag] = 103
4439 UNBOUND_TYPE: Final[Tag] = 104
4440 UNPACK_TYPE: Final[Tag] = 105
4441 ANY_TYPE: Final[Tag] = 106
4442 UNINHABITED_TYPE: Final[Tag] = 107
4443 NONE_TYPE: Final[Tag] = 108
4444 DELETED_TYPE: Final[Tag] = 109
4445 CALLABLE_TYPE: Final[Tag] = 110
4446 OVERLOADED: Final[Tag] = 111
4447 TUPLE_TYPE: Final[Tag] = 112
4448 TYPED_DICT_TYPE: Final[Tag] = 113
4449 LITERAL_TYPE: Final[Tag] = 114
4450 UNION_TYPE: Final[Tag] = 115
4451 TYPE_TYPE: Final[Tag] = 116
4452 PARAMETERS: Final[Tag] = 117
4453 LIST_TYPE: Final[Tag] = 118 # Only valid in serialized ASTs
4454 ELLIPSIS_TYPE: Final[Tag] = 119 # Only valid in serialized ASTs
4455 RAW_EXPRESSION_TYPE: Final[Tag] = 120 # Only valid in serialized ASTs
4456 CALL_TYPE: Final[Tag] = 121 # Only valid in serialized ASTs
4457
4458
4459 def read_type(data: ReadBuffer, tag: Tag | None = None) -> Type:
4460 if tag is None:
4461 tag = read_tag(data)
4462 # The branches here are ordered manually by type "popularity".
4463 if tag == INSTANCE:
4464 return Instance.read(data)
4465 if tag == ANY_TYPE:
4466 return AnyType.read(data)
4467 if tag == TYPE_VAR_TYPE:
4468 return TypeVarType.read(data)
4469 if tag == CALLABLE_TYPE:
4470 return CallableType.read(data)
4471 if tag == NONE_TYPE:
4472 return NoneType.read(data)
4473 if tag == UNION_TYPE:
4474 return UnionType.read(data)
4475 if tag == LITERAL_TYPE:
4476 return LiteralType.read(data)
4477 if tag == TYPE_ALIAS_TYPE:
4478 return TypeAliasType.read(data)
4479 if tag == TUPLE_TYPE:
4480 return TupleType.read(data)
4481 if tag == TYPED_DICT_TYPE:
4482 return TypedDictType.read(data)
4483 if tag == TYPE_TYPE:
4484 return TypeType.read(data)
4485 if tag == OVERLOADED:
4486 return Overloaded.read(data)
4487 if tag == PARAM_SPEC_TYPE:
4488 return ParamSpecType.read(data)
4489 if tag == TYPE_VAR_TUPLE_TYPE:
4490 return TypeVarTupleType.read(data)
4491 if tag == UNPACK_TYPE:
4492 return UnpackType.read(data)
4493 if tag == PARAMETERS:
4494 return Parameters.read(data)
4495 if tag == UNINHABITED_TYPE:
4496 return UninhabitedType.read(data)
4497 if tag == UNBOUND_TYPE:
4498 return UnboundType.read(data)
4499 if tag == DELETED_TYPE:
4500 return DeletedType.read(data)
4501 assert False, f"Unknown type tag {tag}"
4502
4503
4504 def read_function_like(data: ReadBuffer, tag: Tag) -> FunctionLike:
4505 if tag == CALLABLE_TYPE:
4506 return CallableType.read(data)
4507 if tag == OVERLOADED:
4508 return Overloaded.read(data)
4509 assert False, f"Invalid type tag for FunctionLike {tag}"
4510
4511
4512 def read_type_var_likes(data: ReadBuffer) -> list[TypeVarLikeType]:
4513 """Specialized version of read_type_list() for lists of type variables."""
4514 assert read_tag(data) == LIST_GEN
4515 ret: list[TypeVarLikeType] = []
4516 for _ in range(read_int_bare(data)):
4517 tag = read_tag(data)
4518 if tag == TYPE_VAR_TYPE:
4519 ret.append(TypeVarType.read(data))
4520 elif tag == PARAM_SPEC_TYPE:
4521 ret.append(ParamSpecType.read(data))
4522 elif tag == TYPE_VAR_TUPLE_TYPE:
4523 ret.append(TypeVarTupleType.read(data))
4524 else:
4525 assert False, f"Invalid type tag for TypeVarLikeType {tag}"
4526 return ret
4527
4528
4529 def read_type_opt(data: ReadBuffer) -> Type | None:
4530 tag = read_tag(data)
4531 if tag == LITERAL_NONE:
4532 return None
4533 return read_type(data, tag)
4534
4535
4536 def write_type_opt(data: WriteBuffer, value: Type | None) -> None:
4537 if value is not None:
4538 value.write(data)
4539 else:
4540 write_tag(data, LITERAL_NONE)
4541
4542
4543 def read_type_list(data: ReadBuffer) -> list[Type]:
4544 assert read_tag(data) == LIST_GEN
4545 size = read_int_bare(data)
4546 return [read_type(data) for _ in range(size)]
4547
4548
4549 def write_type_list(data: WriteBuffer, value: Sequence[Type]) -> None:
4550 write_tag(data, LIST_GEN)
4551 write_int_bare(data, len(value))
4552 for item in value:
4553 item.write(data)
4554
4555
4556 def read_type_map(data: ReadBuffer) -> dict[str, Type]:
4557 assert read_tag(data) == DICT_STR_GEN
4558 size = read_int_bare(data)
4559 return {read_str_bare(data): read_type(data) for _ in range(size)}
4560
4561
4562 def write_type_map(data: WriteBuffer, value: dict[str, Type]) -> None:
4563 write_tag(data, DICT_STR_GEN)
4564 write_int_bare(data, len(value))
4565 for key in sorted(value):
4566 write_str_bare(data, key)
4567 value[key].write(data)
4568
4569
4570 # This cyclic import is unfortunate, but to avoid it we would need to move away all uses
4571 # of get_proper_type() from types.py. Majority of them have been removed, but few remaining
4572 # are quite tricky to get rid of, but ultimately we want to do it at some point.
4573 from mypy.expandtype import ExpandTypeVisitor
4574
4575
4576 class InstantiateAliasVisitor(ExpandTypeVisitor):
4577 def visit_union_type(self, t: UnionType) -> Type:
4578 # Unlike regular expand_type(), we don't do any simplification for unions,
4579 # not even removing strict duplicates. There are three reasons for this:
4580 # * get_proper_type() is a very hot function, even slightest slow down will
4581 # cause a perf regression
4582 # * We want to preserve this historical behaviour, to avoid possible
4583 # regressions
4584 # * Simplifying unions may (indirectly) call get_proper_type(), causing
4585 # infinite recursion.
4586 return TypeTranslator.visit_union_type(self, t)