-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
types.py
2982 lines (2424 loc) · 109 KB
/
types.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Classes for representing mypy types."""
import copy
import sys
from abc import abstractmethod
from typing import (
Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple,
Sequence
)
from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload, TypeAlias as _TypeAlias
from mypy.backports import OrderedDict
import mypy.nodes
from mypy.state import state
from mypy.nodes import (
INVARIANT, SymbolNode, FuncDef,
ArgKind, ARG_POS, ARG_STAR, ARG_STAR2,
)
from mypy.util import IdMapper
from mypy.bogus_type import Bogus
T = TypeVar('T')
JsonDict: _TypeAlias = Dict[str, Any]
# The set of all valid expressions that can currently be contained
# inside of a Literal[...].
#
# Literals can contain bytes and enum-values: we special-case both of these
# and store the value as a string. We rely on the fallback type that's also
# stored with the Literal to determine how a string is being used.
#
# TODO: confirm that we're happy with representing enums (and the
# other types) in the manner described above.
#
# Note: if we change the set of types included below, we must also
# make sure to audit the following methods:
#
# 1. types.LiteralType's serialize and deserialize methods: this method
# needs to make sure it can convert the below types into JSON and back.
#
# 2. types.LiteralType's 'alue_repr` method: this method is ultimately used
# by TypeStrVisitor's visit_literal_type to generate a reasonable
# repr-able output.
#
# 3. server.astdiff.SnapshotTypeVisitor's visit_literal_type_method: this
# method assumes that the following types supports equality checks and
# hashability.
#
# Note: Although "Literal[None]" is a valid type, we internally always convert
# such a type directly into "None". So, "None" is not a valid parameter of
# LiteralType and is omitted from this list.
LiteralValue: _TypeAlias = Union[int, str, bool]
# If we only import type_visitor in the middle of the file, mypy
# breaks, and if we do it at the top, it breaks at runtime because of
# import cycle issues, so we do it at the top while typechecking and
# then again in the middle at runtime.
# We should be able to remove this once we are switched to the new
# semantic analyzer!
if TYPE_CHECKING:
from mypy.type_visitor import (
TypeVisitor as TypeVisitor,
SyntheticTypeVisitor as SyntheticTypeVisitor,
)
# Supported names of TypedDict type constructors.
TPDICT_NAMES: Final = (
"typing.TypedDict",
"typing_extensions.TypedDict",
"mypy_extensions.TypedDict",
)
# Supported fallback instance type names for TypedDict types.
TPDICT_FB_NAMES: Final = (
"typing._TypedDict",
"typing_extensions._TypedDict",
"mypy_extensions._TypedDict",
)
# Supported names of Protocol base class.
PROTOCOL_NAMES: Final = (
'typing.Protocol',
'typing_extensions.Protocol',
)
# Supported TypeAlias names.
TYPE_ALIAS_NAMES: Final = (
"typing.TypeAlias",
"typing_extensions.TypeAlias",
)
# Supported Final type names.
FINAL_TYPE_NAMES: Final = (
'typing.Final',
'typing_extensions.Final',
)
# Supported @final decorator names.
FINAL_DECORATOR_NAMES: Final = (
'typing.final',
'typing_extensions.final',
)
# Supported Literal type names.
LITERAL_TYPE_NAMES: Final = (
'typing.Literal',
'typing_extensions.Literal',
)
# Supported Annotated type names.
ANNOTATED_TYPE_NAMES: Final = (
'typing.Annotated',
'typing_extensions.Annotated',
)
# We use this constant in various places when checking `tuple` subtyping:
TUPLE_LIKE_INSTANCE_NAMES: Final = (
'builtins.tuple',
'typing.Iterable',
'typing.Container',
'typing.Sequence',
'typing.Reversible',
)
REVEAL_TYPE_NAMES: Final = (
'builtins.reveal_type',
'typing.reveal_type',
'typing_extensions.reveal_type',
)
ASSERT_TYPE_NAMES: Final = (
'typing.assert_type',
'typing_extensions.assert_type',
)
OVERLOAD_NAMES: Final = (
'typing.overload',
'typing_extensions.overload',
)
# Attributes that can optionally be defined in the body of a subclass of
# enum.Enum but are removed from the class __dict__ by EnumMeta.
ENUM_REMOVED_PROPS: Final = (
'_ignore_',
'_order_',
'__order__',
)
NEVER_NAMES: Final = (
'typing.NoReturn',
'typing_extensions.NoReturn',
'mypy_extensions.NoReturn',
'typing.Never',
'typing_extensions.Never',
)
# A placeholder used for Bogus[...] parameters
_dummy: Final[Any] = object()
class TypeOfAny:
"""
This class describes different types of Any. Each 'Any' can be of only one type at a time.
"""
__slots__ = ()
# Was this Any type inferred without a type annotation?
unannotated: Final = 1
# Does this Any come from an explicit type annotation?
explicit: Final = 2
# Does this come from an unfollowed import? See --disallow-any-unimported option
from_unimported_type: Final = 3
# Does this Any type come from omitted generics?
from_omitted_generics: Final = 4
# Does this Any come from an error?
from_error: Final = 5
# Is this a type that can't be represented in mypy's type system? For instance, type of
# call to NewType...). Even though these types aren't real Anys, we treat them as such.
# Also used for variables named '_'.
special_form: Final = 6
# Does this Any come from interaction with another Any?
from_another_any: Final = 7
# Does this Any come from an implementation limitation/bug?
implementation_artifact: Final = 8
# Does this Any come from use in the suggestion engine? This is
# used to ignore Anys inserted by the suggestion engine when
# generating constraints.
suggestion_engine: Final = 9
def deserialize_type(data: Union[JsonDict, str]) -> 'Type':
if isinstance(data, str):
return Instance.deserialize(data)
classname = data['.class']
method = deserialize_map.get(classname)
if method is not None:
return method(data)
raise NotImplementedError('unexpected .class {}'.format(classname))
class Type(mypy.nodes.Context):
"""Abstract base class for all types."""
__slots__ = ('can_be_true', 'can_be_false')
# 'can_be_true' and 'can_be_false' mean whether the value of the
# expression can be true or false in a boolean context. They are useful
# when inferring the type of logic expressions like `x and y`.
#
# For example:
# * the literal `False` can't be true while `True` can.
# * a value with type `bool` can be true or false.
# * `None` can't be true
# * ...
def __init__(self, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.can_be_true = self.can_be_true_default()
self.can_be_false = self.can_be_false_default()
def can_be_true_default(self) -> bool:
return True
def can_be_false_default(self) -> bool:
return True
def accept(self, visitor: 'TypeVisitor[T]') -> T:
raise RuntimeError('Not implemented')
def __repr__(self) -> str:
return self.accept(TypeStrVisitor())
def serialize(self) -> Union[JsonDict, str]:
raise NotImplementedError('Cannot serialize {} instance'.format(self.__class__.__name__))
@classmethod
def deserialize(cls, data: JsonDict) -> 'Type':
raise NotImplementedError('Cannot deserialize {} instance'.format(cls.__name__))
class TypeAliasType(Type):
"""A type alias to another type.
NOTE: this is not being used yet, and the implementation is still incomplete.
To support recursive type aliases we don't immediately expand a type alias
during semantic analysis, but create an instance of this type that records the target alias
definition node (mypy.nodes.TypeAlias) and type arguments (for generic aliases).
This is very similar to how TypeInfo vs Instance interact, where a recursive class-based
structure like
class Node:
value: int
children: List[Node]
can be represented in a tree-like manner.
"""
__slots__ = ('alias', 'args', 'line', 'column', 'type_ref')
def __init__(self, alias: Optional[mypy.nodes.TypeAlias], args: List[Type],
line: int = -1, column: int = -1) -> None:
self.alias = alias
self.args = args
self.type_ref: Optional[str] = None
super().__init__(line, column)
def _expand_once(self) -> Type:
"""Expand to the target type exactly once.
This doesn't do full expansion, i.e. the result can contain another
(or even this same) type alias. Use this internal helper only when really needed,
its public wrapper mypy.types.get_proper_type() is preferred.
"""
assert self.alias is not None
if self.alias.no_args:
# We know that no_args=True aliases like L = List must have an instance
# as their target.
assert isinstance(self.alias.target, Instance) # type: ignore[misc]
return self.alias.target.copy_modified(args=self.args)
return replace_alias_tvars(self.alias.target, self.alias.alias_tvars, self.args,
self.line, self.column)
def _partial_expansion(self) -> Tuple['ProperType', bool]:
# Private method mostly for debugging and testing.
unroller = UnrollAliasVisitor(set())
unrolled = self.accept(unroller)
assert isinstance(unrolled, ProperType)
return unrolled, unroller.recursed
def expand_all_if_possible(self) -> Optional['ProperType']:
"""Attempt a full expansion of the type alias (including nested aliases).
If the expansion is not possible, i.e. the alias is (mutually-)recursive,
return None.
"""
unrolled, recursed = self._partial_expansion()
if recursed:
return None
return unrolled
@property
def is_recursive(self) -> bool:
assert self.alias is not None, 'Unfixed type alias'
is_recursive = self.alias._is_recursive
if is_recursive is None:
is_recursive = self.expand_all_if_possible() is None
# We cache the value on the underlying TypeAlias node as an optimization,
# since the value is the same for all instances of the same alias.
self.alias._is_recursive = is_recursive
return is_recursive
def can_be_true_default(self) -> bool:
if self.alias is not None:
return self.alias.target.can_be_true
return super().can_be_true_default()
def can_be_false_default(self) -> bool:
if self.alias is not None:
return self.alias.target.can_be_false
return super().can_be_false_default()
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_type_alias_type(self)
def __hash__(self) -> int:
return hash((self.alias, tuple(self.args)))
def __eq__(self, other: object) -> bool:
# Note: never use this to determine subtype relationships, use is_subtype().
if not isinstance(other, TypeAliasType):
return NotImplemented
return (self.alias == other.alias
and self.args == other.args)
def serialize(self) -> JsonDict:
assert self.alias is not None
data: JsonDict = {
".class": "TypeAliasType",
"type_ref": self.alias.fullname,
"args": [arg.serialize() for arg in self.args],
}
return data
@classmethod
def deserialize(cls, data: JsonDict) -> 'TypeAliasType':
assert data['.class'] == 'TypeAliasType'
args: List[Type] = []
if 'args' in data:
args_list = data['args']
assert isinstance(args_list, list)
args = [deserialize_type(arg) for arg in args_list]
alias = TypeAliasType(None, args)
alias.type_ref = data['type_ref']
return alias
def copy_modified(self, *,
args: Optional[List[Type]] = None) -> 'TypeAliasType':
return TypeAliasType(
self.alias,
args if args is not None else self.args.copy(),
self.line, self.column)
class TypeGuardedType(Type):
"""Only used by find_isinstance_check() etc."""
__slots__ = ('type_guard',)
def __init__(self, type_guard: Type):
super().__init__(line=type_guard.line, column=type_guard.column)
self.type_guard = type_guard
def __repr__(self) -> str:
return "TypeGuard({})".format(self.type_guard)
class RequiredType(Type):
"""Required[T] or NotRequired[T]. Only usable at top-level of a TypedDict definition."""
def __init__(self, item: Type, *, required: bool) -> None:
super().__init__(line=item.line, column=item.column)
self.item = item
self.required = required
def __repr__(self) -> str:
if self.required:
return "Required[{}]".format(self.item)
else:
return "NotRequired[{}]".format(self.item)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return self.item.accept(visitor)
class ProperType(Type):
"""Not a type alias.
Every type except TypeAliasType must inherit from this type.
"""
__slots__ = ()
class TypeVarId:
# A type variable is uniquely identified by its raw id and meta level.
# For plain variables (type parameters of generic classes and
# functions) raw ids are allocated by semantic analysis, using
# positive ids 1, 2, ... for generic class parameters and negative
# ids -1, ... for generic function type arguments. This convention
# is only used to keep type variable ids distinct when allocating
# them; the type checker makes no distinction between class and
# function type variables.
# Metavariables are allocated unique ids starting from 1.
raw_id: int = 0
# Level of the variable in type inference. Currently either 0 for
# declared types, or 1 for type inference metavariables.
meta_level: int = 0
# Class variable used for allocating fresh ids for metavariables.
next_raw_id: ClassVar[int] = 1
def __init__(self, raw_id: int, meta_level: int = 0) -> None:
self.raw_id = raw_id
self.meta_level = meta_level
@staticmethod
def new(meta_level: int) -> 'TypeVarId':
raw_id = TypeVarId.next_raw_id
TypeVarId.next_raw_id += 1
return TypeVarId(raw_id, meta_level)
def __repr__(self) -> str:
return self.raw_id.__repr__()
def __eq__(self, other: object) -> bool:
if isinstance(other, TypeVarId):
return (self.raw_id == other.raw_id and
self.meta_level == other.meta_level)
else:
return False
def __ne__(self, other: object) -> bool:
return not (self == other)
def __hash__(self) -> int:
return hash((self.raw_id, self.meta_level))
def is_meta_var(self) -> bool:
return self.meta_level > 0
class TypeVarLikeType(ProperType):
__slots__ = ('name', 'fullname', 'id', 'upper_bound')
name: str # Name (may be qualified)
fullname: str # Fully qualified name
id: TypeVarId
upper_bound: Type
def __init__(
self, name: str, fullname: str, id: Union[TypeVarId, int], upper_bound: Type,
line: int = -1, column: int = -1
) -> None:
super().__init__(line, column)
self.name = name
self.fullname = fullname
if isinstance(id, int):
id = TypeVarId(id)
self.id = id
self.upper_bound = upper_bound
def serialize(self) -> JsonDict:
raise NotImplementedError
@classmethod
def deserialize(cls, data: JsonDict) -> 'TypeVarLikeType':
raise NotImplementedError
class TypeVarType(TypeVarLikeType):
"""Type that refers to a type variable."""
__slots__ = ('values', 'variance')
values: List[Type] # Value restriction, empty list if no restriction
variance: int
def __init__(self, name: str, fullname: str, id: Union[TypeVarId, int], values: List[Type],
upper_bound: Type, variance: int = INVARIANT, line: int = -1,
column: int = -1) -> None:
super().__init__(name, fullname, id, upper_bound, line, column)
assert values is not None, "No restrictions must be represented by empty list"
self.values = values
self.variance = variance
@staticmethod
def new_unification_variable(old: 'TypeVarType') -> 'TypeVarType':
new_id = TypeVarId.new(meta_level=1)
return TypeVarType(old.name, old.fullname, new_id, old.values,
old.upper_bound, old.variance, old.line, old.column)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_type_var(self)
def __hash__(self) -> int:
return hash(self.id)
def __eq__(self, other: object) -> bool:
if not isinstance(other, TypeVarType):
return NotImplemented
return self.id == other.id
def serialize(self) -> JsonDict:
assert not self.id.is_meta_var()
return {'.class': 'TypeVarType',
'name': self.name,
'fullname': self.fullname,
'id': self.id.raw_id,
'values': [v.serialize() for v in self.values],
'upper_bound': self.upper_bound.serialize(),
'variance': self.variance,
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'TypeVarType':
assert data['.class'] == 'TypeVarType'
return TypeVarType(
data['name'],
data['fullname'],
data['id'],
[deserialize_type(v) for v in data['values']],
deserialize_type(data['upper_bound']),
data['variance'],
)
class ParamSpecFlavor:
# Simple ParamSpec reference such as "P"
BARE: Final = 0
# P.args
ARGS: Final = 1
# P.kwargs
KWARGS: Final = 2
class ParamSpecType(TypeVarLikeType):
"""Type that refers to a ParamSpec.
A ParamSpec is a type variable that represents the parameter
types, names and kinds of a callable (i.e., the signature without
the return type).
This can be one of these forms
* P (ParamSpecFlavor.BARE)
* P.args (ParamSpecFlavor.ARGS)
* P.kwargs (ParamSpecFLavor.KWARGS)
The upper_bound is really used as a fallback type -- it's shared
with TypeVarType for simplicity. It can't be specified by the user
and the value is directly derived from the flavor (currently
always just 'object').
"""
__slots__ = ('flavor', 'prefix')
flavor: int
prefix: 'Parameters'
def __init__(
self, name: str, fullname: str, id: Union[TypeVarId, int], flavor: int,
upper_bound: Type, *, line: int = -1, column: int = -1,
prefix: Optional['Parameters'] = None
) -> None:
super().__init__(name, fullname, id, upper_bound, line=line, column=column)
self.flavor = flavor
self.prefix = prefix or Parameters([], [], [])
@staticmethod
def new_unification_variable(old: 'ParamSpecType') -> 'ParamSpecType':
new_id = TypeVarId.new(meta_level=1)
return ParamSpecType(old.name, old.fullname, new_id, old.flavor, old.upper_bound,
line=old.line, column=old.column, prefix=old.prefix)
def with_flavor(self, flavor: int) -> 'ParamSpecType':
return ParamSpecType(self.name, self.fullname, self.id, flavor,
upper_bound=self.upper_bound, prefix=self.prefix)
def copy_modified(self, *,
id: Bogus[Union[TypeVarId, int]] = _dummy,
flavor: Bogus[int] = _dummy,
prefix: Bogus['Parameters'] = _dummy) -> 'ParamSpecType':
return ParamSpecType(
self.name,
self.fullname,
id if id is not _dummy else self.id,
flavor if flavor is not _dummy else self.flavor,
self.upper_bound,
line=self.line,
column=self.column,
prefix=prefix if prefix is not _dummy else self.prefix,
)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_param_spec(self)
def name_with_suffix(self) -> str:
n = self.name
if self.flavor == ParamSpecFlavor.ARGS:
return f'{n}.args'
elif self.flavor == ParamSpecFlavor.KWARGS:
return f'{n}.kwargs'
return n
def __hash__(self) -> int:
return hash((self.id, self.flavor))
def __eq__(self, other: object) -> bool:
if not isinstance(other, ParamSpecType):
return NotImplemented
# Upper bound can be ignored, since it's determined by flavor.
return self.id == other.id and self.flavor == other.flavor
def serialize(self) -> JsonDict:
assert not self.id.is_meta_var()
return {
'.class': 'ParamSpecType',
'name': self.name,
'fullname': self.fullname,
'id': self.id.raw_id,
'flavor': self.flavor,
'upper_bound': self.upper_bound.serialize(),
'prefix': self.prefix.serialize()
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'ParamSpecType':
assert data['.class'] == 'ParamSpecType'
return ParamSpecType(
data['name'],
data['fullname'],
data['id'],
data['flavor'],
deserialize_type(data['upper_bound']),
prefix=Parameters.deserialize(data['prefix'])
)
class UnboundType(ProperType):
"""Instance type that has not been bound during semantic analysis."""
__slots__ = ('name', 'args', 'optional', 'empty_tuple_index',
'original_str_expr', 'original_str_fallback')
def __init__(self,
name: Optional[str],
args: Optional[Sequence[Type]] = None,
line: int = -1,
column: int = -1,
optional: bool = False,
empty_tuple_index: bool = False,
original_str_expr: Optional[str] = None,
original_str_fallback: Optional[str] = None,
) -> None:
super().__init__(line, column)
if not args:
args = []
assert name is not None
self.name = name
self.args = tuple(args)
# Should this type be wrapped in an Optional?
self.optional = optional
# Special case for X[()]
self.empty_tuple_index = empty_tuple_index
# If this UnboundType was originally defined as a str or bytes, keep track of
# the original contents of that string-like thing. This way, if this UnboundExpr
# ever shows up inside of a LiteralType, we can determine whether that
# Literal[...] is valid or not. E.g. Literal[foo] is most likely invalid
# (unless 'foo' is an alias for another literal or something) and
# Literal["foo"] most likely is.
#
# We keep track of the entire string instead of just using a boolean flag
# so we can distinguish between things like Literal["foo"] vs
# Literal[" foo "].
#
# We also keep track of what the original base fallback type was supposed to be
# so we don't have to try and recompute it later
self.original_str_expr = original_str_expr
self.original_str_fallback = original_str_fallback
def copy_modified(self,
args: Bogus[Optional[Sequence[Type]]] = _dummy,
) -> 'UnboundType':
if args is _dummy:
args = self.args
return UnboundType(
name=self.name,
args=args,
line=self.line,
column=self.column,
optional=self.optional,
empty_tuple_index=self.empty_tuple_index,
original_str_expr=self.original_str_expr,
original_str_fallback=self.original_str_fallback,
)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_unbound_type(self)
def __hash__(self) -> int:
return hash((self.name, self.optional, tuple(self.args), self.original_str_expr))
def __eq__(self, other: object) -> bool:
if not isinstance(other, UnboundType):
return NotImplemented
return (self.name == other.name and self.optional == other.optional and
self.args == other.args and self.original_str_expr == other.original_str_expr and
self.original_str_fallback == other.original_str_fallback)
def serialize(self) -> JsonDict:
return {'.class': 'UnboundType',
'name': self.name,
'args': [a.serialize() for a in self.args],
'expr': self.original_str_expr,
'expr_fallback': self.original_str_fallback,
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'UnboundType':
assert data['.class'] == 'UnboundType'
return UnboundType(data['name'],
[deserialize_type(a) for a in data['args']],
original_str_expr=data['expr'],
original_str_fallback=data['expr_fallback'],
)
class CallableArgument(ProperType):
"""Represents a Arg(type, 'name') inside a Callable's type list.
Note that this is a synthetic type for helping parse ASTs, not a real type.
"""
__slots__ = ('typ', 'name', 'constructor')
typ: Type
name: Optional[str]
constructor: Optional[str]
def __init__(self, typ: Type, name: Optional[str], constructor: Optional[str],
line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.typ = typ
self.name = name
self.constructor = constructor
def accept(self, visitor: 'TypeVisitor[T]') -> T:
assert isinstance(visitor, SyntheticTypeVisitor)
return visitor.visit_callable_argument(self)
def serialize(self) -> JsonDict:
assert False, "Synthetic types don't serialize"
class TypeList(ProperType):
"""Information about argument types and names [...].
This is used for the arguments of a Callable type, i.e. for
[arg, ...] in Callable[[arg, ...], ret]. This is not a real type
but a syntactic AST construct. UnboundTypes can also have TypeList
types before they are processed into Callable types.
"""
__slots__ = ('items',)
items: List[Type]
def __init__(self, items: List[Type], line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.items = items
def accept(self, visitor: 'TypeVisitor[T]') -> T:
assert isinstance(visitor, SyntheticTypeVisitor)
return visitor.visit_type_list(self)
def serialize(self) -> JsonDict:
assert False, "Synthetic types don't serialize"
class UnpackType(ProperType):
"""Type operator Unpack from PEP646. Can be either with Unpack[]
or unpacking * syntax.
The inner type should be either a TypeVarTuple, a constant size
tuple, or a variable length tuple, or a union of one of those.
"""
__slots__ = ["type"]
def __init__(self, typ: Type, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.type = typ
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_unpack_type(self)
def serialize(self) -> JsonDict:
return {
".class": "UnpackType",
"type": self.type.serialize(),
}
@classmethod
def deserialize(cls, data: JsonDict) -> "UnpackType":
assert data[".class"] == "UnpackType"
typ = data["type"]
return UnpackType(deserialize_type(typ))
class AnyType(ProperType):
"""The type 'Any'."""
__slots__ = ('type_of_any', 'source_any', 'missing_import_name')
def __init__(self,
type_of_any: int,
source_any: Optional['AnyType'] = None,
missing_import_name: Optional[str] = None,
line: int = -1,
column: int = -1) -> None:
super().__init__(line, column)
self.type_of_any = type_of_any
# If this Any was created as a result of interacting with another 'Any', record the source
# and use it in reports.
self.source_any = source_any
if source_any and source_any.source_any:
self.source_any = source_any.source_any
if source_any is None:
self.missing_import_name = missing_import_name
else:
self.missing_import_name = source_any.missing_import_name
# Only unimported type anys and anys from other anys should have an import name
assert (missing_import_name is None or
type_of_any in (TypeOfAny.from_unimported_type, TypeOfAny.from_another_any))
# Only Anys that come from another Any can have source_any.
assert type_of_any != TypeOfAny.from_another_any or source_any is not None
# We should not have chains of Anys.
assert not self.source_any or self.source_any.type_of_any != TypeOfAny.from_another_any
@property
def is_from_error(self) -> bool:
return self.type_of_any == TypeOfAny.from_error
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_any(self)
def copy_modified(self,
# Mark with Bogus because _dummy is just an object (with type Any)
type_of_any: Bogus[int] = _dummy,
original_any: Bogus[Optional['AnyType']] = _dummy,
) -> 'AnyType':
if type_of_any is _dummy:
type_of_any = self.type_of_any
if original_any is _dummy:
original_any = self.source_any
return AnyType(type_of_any=type_of_any, source_any=original_any,
missing_import_name=self.missing_import_name,
line=self.line, column=self.column)
def __hash__(self) -> int:
return hash(AnyType)
def __eq__(self, other: object) -> bool:
return isinstance(other, AnyType)
def serialize(self) -> JsonDict:
return {'.class': 'AnyType', 'type_of_any': self.type_of_any,
'source_any': self.source_any.serialize() if self.source_any is not None else None,
'missing_import_name': self.missing_import_name}
@classmethod
def deserialize(cls, data: JsonDict) -> 'AnyType':
assert data['.class'] == 'AnyType'
source = data['source_any']
return AnyType(data['type_of_any'],
AnyType.deserialize(source) if source is not None else None,
data['missing_import_name'])
class UninhabitedType(ProperType):
"""This type has no members.
This type is the bottom type.
With strict Optional checking, it is the only common subtype between all
other types, which allows `meet` to be well defined. Without strict
Optional checking, NoneType fills this role.
In general, for any type T:
join(UninhabitedType, T) = T
meet(UninhabitedType, T) = UninhabitedType
is_subtype(UninhabitedType, T) = True
"""
__slots__ = ('ambiguous', 'is_noreturn',)
is_noreturn: bool # Does this come from a NoReturn? Purely for error messages.
# It is important to track whether this is an actual NoReturn type, or just a result
# of ambiguous type inference, in the latter case we don't want to mark a branch as
# unreachable in binder.
ambiguous: bool # Is this a result of inference for a variable without constraints?
def __init__(self, is_noreturn: bool = False, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.is_noreturn = is_noreturn
self.ambiguous = False
def can_be_true_default(self) -> bool:
return False
def can_be_false_default(self) -> bool:
return False
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_uninhabited_type(self)
def __hash__(self) -> int:
return hash(UninhabitedType)
def __eq__(self, other: object) -> bool:
return isinstance(other, UninhabitedType)
def serialize(self) -> JsonDict:
return {'.class': 'UninhabitedType',
'is_noreturn': self.is_noreturn}
@classmethod
def deserialize(cls, data: JsonDict) -> 'UninhabitedType':
assert data['.class'] == 'UninhabitedType'
return UninhabitedType(is_noreturn=data['is_noreturn'])
class NoneType(ProperType):
"""The type of 'None'.
This type can be written by users as 'None'.
"""
__slots__ = ()
def __init__(self, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
def can_be_true_default(self) -> bool:
return False
def __hash__(self) -> int:
return hash(NoneType)
def __eq__(self, other: object) -> bool:
return isinstance(other, NoneType)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_none_type(self)
def serialize(self) -> JsonDict:
return {'.class': 'NoneType'}
@classmethod
def deserialize(cls, data: JsonDict) -> 'NoneType':
assert data['.class'] == 'NoneType'
return NoneType()
# NoneType used to be called NoneTyp so to avoid needlessly breaking
# external plugins we keep that alias here.
NoneTyp = NoneType
class ErasedType(ProperType):
"""Placeholder for an erased type.
This is used during type inference. This has the special property that
it is ignored during type inference.
"""
__slots__ = ()
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_erased_type(self)
class DeletedType(ProperType):