forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.py
More file actions
2245 lines (1812 loc) · 84.2 KB
/
types.py
File metadata and controls
2245 lines (1812 loc) · 84.2 KB
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 collections import OrderedDict
from typing import (
Any, TypeVar, Dict, List, Tuple, cast, Set, Optional, Union, Iterable, NamedTuple,
Sequence, Iterator, overload
)
from typing_extensions import ClassVar, Final, TYPE_CHECKING, overload
import mypy.nodes
from mypy import state
from mypy.nodes import (
INVARIANT, SymbolNode, ARG_POS, ARG_OPT, ARG_STAR, ARG_STAR2, ARG_NAMED, ARG_NAMED_OPT,
FuncDef,
)
from mypy.util import IdMapper
from mypy.bogus_type import Bogus
T = TypeVar('T')
JsonDict = 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 = 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 = ('typing.TypedDict',
'typing_extensions.TypedDict',
'mypy_extensions.TypedDict') # type: Final
# Supported fallback instance type names for TypedDict types.
TPDICT_FB_NAMES = ('typing._TypedDict',
'typing_extensions._TypedDict',
'mypy_extensions._TypedDict') # type: Final
# A placeholder used for Bogus[...] parameters
_dummy = object() # type: Final[Any]
class TypeOfAny:
"""
This class describes different types of Any. Each 'Any' can be of only one type at a time.
"""
# Was this Any type inferred without a type annotation?
unannotated = 1 # type: Final
# Does this Any come from an explicit type annotation?
explicit = 2 # type: Final
# Does this come from an unfollowed import? See --disallow-any-unimported option
from_unimported_type = 3 # type: Final
# Does this Any type come from omitted generics?
from_omitted_generics = 4 # type: Final
# Does this Any come from an error?
from_error = 5 # type: Final
# 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 = 6 # type: Final
# Does this Any come from interaction with another Any?
from_another_any = 7 # type: Final
# Does this Any come from an implementation limitation/bug?
implementation_artifact = 8 # type: Final
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')
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.
"""
def __init__(self, alias: Optional[mypy.nodes.TypeAlias], args: List[Type],
line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.alias = alias
self.args = args
self.type_ref = None # type: Optional[str]
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
return replace_alias_tvars(self.alias.target, self.alias.alias_tvars, self.args,
self.line, self.column)
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.
"""
raise NotImplementedError('TODO')
# TODO: remove ignore caused by https://github.com/python/mypy/issues/6759
@property
def can_be_true(self) -> bool: # type: ignore[override]
assert self.alias is not None
return self.alias.target.can_be_true
# TODO: remove ignore caused by https://github.com/python/mypy/issues/6759
@property
def can_be_false(self) -> bool: # type: ignore[override]
assert self.alias is not None
return self.alias.target.can_be_false
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:
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 = {'.class': 'TypeAliasType',
'type_ref': self.alias.fullname(),
'args': [arg.serialize() for arg in self.args]} # type: JsonDict
return data
@classmethod
def deserialize(cls, data: JsonDict) -> 'TypeAliasType':
assert data['.class'] == 'TypeAliasType'
args = [] # type: 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'] # TODO: fix this up in fixup.py.
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 ProperType(Type):
"""Not a type alias.
Every type except TypeAliasType must inherit from this type.
"""
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 = 0 # type: int
# Level of the variable in type inference. Currently either 0 for
# declared types, or 1 for type inference metavariables.
meta_level = 0 # type: int
# Class variable used for allocating fresh ids for metavariables.
next_raw_id = 1 # type: ClassVar[int]
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 TypeVarDef(mypy.nodes.Context):
"""Definition of a single type variable."""
name = '' # Name (may be qualified)
fullname = '' # Fully qualified name
id = None # type: TypeVarId
values = None # type: List[Type] # Value restriction, empty list if no restriction
upper_bound = None # type: Type
variance = INVARIANT # type: 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__(line, column)
assert values is not None, "No restrictions must be represented by empty list"
self.name = name
self.fullname = fullname
if isinstance(id, int):
id = TypeVarId(id)
self.id = id
self.values = values
self.upper_bound = upper_bound
self.variance = variance
@staticmethod
def new_unification_variable(old: 'TypeVarDef') -> 'TypeVarDef':
new_id = TypeVarId.new(meta_level=1)
return TypeVarDef(old.name, old.fullname, new_id, old.values,
old.upper_bound, old.variance, old.line, old.column)
def __repr__(self) -> str:
if self.values:
return '{} in {}'.format(self.name, tuple(self.values))
elif not is_named_instance(self.upper_bound, 'builtins.object'):
return '{} <: {}'.format(self.name, self.upper_bound)
else:
return self.name
def serialize(self) -> JsonDict:
assert not self.id.is_meta_var()
return {'.class': 'TypeVarDef',
'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) -> 'TypeVarDef':
assert data['.class'] == 'TypeVarDef'
return TypeVarDef(data['name'],
data['fullname'],
data['id'],
[deserialize_type(v) for v in data['values']],
deserialize_type(data['upper_bound']),
data['variance'],
)
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[List[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 = 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[List[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.
"""
typ = None # type: Type
name = None # type: Optional[str]
constructor = None # type: 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.
"""
items = None # type: 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 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
"""
is_noreturn = False # 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 = False # 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
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.
"""
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_erased_type(self)
class DeletedType(ProperType):
"""Type of deleted variables.
These can be used as lvalues but not rvalues.
"""
source = '' # type: Optional[str] # May be None; name that generated this value
def __init__(self, source: Optional[str] = None, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.source = source
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_deleted_type(self)
def serialize(self) -> JsonDict:
return {'.class': 'DeletedType',
'source': self.source}
@classmethod
def deserialize(cls, data: JsonDict) -> 'DeletedType':
assert data['.class'] == 'DeletedType'
return DeletedType(data['source'])
# Fake TypeInfo to be used as a placeholder during Instance de-serialization.
NOT_READY = mypy.nodes.FakeInfo('De-serialization failure: TypeInfo not fixed') # type: Final
class Instance(ProperType):
"""An instance type of form C[T1, ..., Tn].
The list of type variables may be empty.
"""
__slots__ = ('type', 'args', 'erased', 'invalid', 'type_ref', 'last_known_value')
def __init__(self, typ: mypy.nodes.TypeInfo, args: List[Type],
line: int = -1, column: int = -1, erased: bool = False,
last_known_value: Optional['LiteralType'] = None) -> None:
super().__init__(line, column)
self.type = typ
self.args = args
self.type_ref = None # type: Optional[str]
# True if result of type variable substitution
self.erased = erased
# True if recovered after incorrect number of type arguments error
self.invalid = False
# This field keeps track of the underlying Literal[...] value associated with
# this instance, if one is known.
#
# This field is set whenever possible within expressions, but is erased upon
# variable assignment (see erasetype.remove_instance_last_known_values) unless
# the variable is declared to be final.
#
# For example, consider the following program:
#
# a = 1
# b: Final[int] = 2
# c: Final = 3
# print(a + b + c + 4)
#
# The 'Instance' objects associated with the expressions '1', '2', '3', and '4' will
# have last_known_values of type Literal[1], Literal[2], Literal[3], and Literal[4]
# respectively. However, the Instance object assigned to 'a' and 'b' will have their
# last_known_value erased: variable 'a' is mutable; variable 'b' was declared to be
# specifically an int.
#
# Or more broadly, this field lets this Instance "remember" its original declaration
# when applicable. We want this behavior because we want implicit Final declarations
# to act pretty much identically with constants: we should be able to replace any
# places where we use some Final variable with the original value and get the same
# type-checking behavior. For example, we want this program:
#
# def expects_literal(x: Literal[3]) -> None: pass
# var: Final = 3
# expects_literal(var)
#
# ...to type-check in the exact same way as if we had written the program like this:
#
# def expects_literal(x: Literal[3]) -> None: pass
# expects_literal(3)
#
# In order to make this work (especially with literal types), we need var's type
# (an Instance) to remember the "original" value.
#
# Preserving this value within expressions is useful for similar reasons.
#
# Currently most of mypy will ignore this field and will continue to treat this type like
# a regular Instance. We end up using this field only when we are explicitly within a
# Literal context.
self.last_known_value = last_known_value
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_instance(self)
def __hash__(self) -> int:
return hash((self.type, tuple(self.args), self.last_known_value))
def __eq__(self, other: object) -> bool:
if not isinstance(other, Instance):
return NotImplemented
return (self.type == other.type
and self.args == other.args
and self.last_known_value == other.last_known_value)
def serialize(self) -> Union[JsonDict, str]:
assert self.type is not None
type_ref = self.type.fullname()
if not self.args and not self.last_known_value:
return type_ref
data = {'.class': 'Instance',
} # type: JsonDict
data['type_ref'] = type_ref
data['args'] = [arg.serialize() for arg in self.args]
if self.last_known_value is not None:
data['last_known_value'] = self.last_known_value.serialize()
return data
@classmethod
def deserialize(cls, data: Union[JsonDict, str]) -> 'Instance':
if isinstance(data, str):
inst = Instance(NOT_READY, [])
inst.type_ref = data
return inst
assert data['.class'] == 'Instance'
args = [] # type: List[Type]
if 'args' in data:
args_list = data['args']
assert isinstance(args_list, list)
args = [deserialize_type(arg) for arg in args_list]
inst = Instance(NOT_READY, args)
inst.type_ref = data['type_ref'] # Will be fixed up by fixup.py later.
if 'last_known_value' in data:
inst.last_known_value = LiteralType.deserialize(data['last_known_value'])
return inst
def copy_modified(self, *,
args: Bogus[List[Type]] = _dummy,
last_known_value: Bogus[Optional['LiteralType']] = _dummy) -> 'Instance':
return Instance(
self.type,
args if args is not _dummy else self.args,
self.line,
self.column,
self.erased,
last_known_value if last_known_value is not _dummy else self.last_known_value,
)
def has_readable_member(self, name: str) -> bool:
return self.type.has_readable_member(name)
class TypeVarType(ProperType):
"""A type variable type.
This refers to either a class type variable (id > 0) or a function
type variable (id < 0).
"""
__slots__ = ('name', 'fullname', 'id', 'values', 'upper_bound', 'variance')
def __init__(self, binder: TypeVarDef, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.name = binder.name # Name of the type variable (for messages and debugging)
self.fullname = binder.fullname # type: str
self.id = binder.id # type: TypeVarId
# Value restriction, empty list if no restriction
self.values = binder.values # type: List[Type]
# Upper bound for values
self.upper_bound = binder.upper_bound # type: Type
# See comments in TypeVarDef for more about variance.
self.variance = binder.variance # type: int
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'
tvdef = TypeVarDef(data['name'],
data['fullname'],
data['id'],
[deserialize_type(v) for v in data['values']],
deserialize_type(data['upper_bound']),
data['variance'])
return TypeVarType(tvdef)
class FunctionLike(ProperType):
"""Abstract base class for function types."""
__slots__ = ('fallback',)
def __init__(self, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.can_be_false = False
if TYPE_CHECKING: # we don't want a runtime None value
# Corresponding instance type (e.g. builtins.type)
self.fallback = cast(Instance, None)
@abstractmethod
def is_type_obj(self) -> bool: pass
@abstractmethod
def type_object(self) -> mypy.nodes.TypeInfo: pass
@abstractmethod
def items(self) -> List['CallableType']: pass
@abstractmethod
def with_name(self, name: str) -> 'FunctionLike': pass
@abstractmethod
def get_name(self) -> Optional[str]: pass
FormalArgument = NamedTuple('FormalArgument', [
('name', Optional[str]),
('pos', Optional[int]),
('typ', Type),
('required', bool)])
class CallableType(FunctionLike):
"""Type of a non-overloaded callable object (such as function)."""
__slots__ = ('arg_types', # Types of function arguments
'arg_kinds', # ARG_ constants
'arg_names', # Argument names; None if not a keyword argument
'min_args', # Minimum number of arguments; derived from arg_kinds
'ret_type', # Return value type
'name', # Name (may be None; for error messages and plugins)
'definition', # For error messages. May be None.
'variables', # Type variables for a generic function
'is_ellipsis_args', # Is this Callable[..., t] (with literal '...')?
'is_classmethod_class', # Is this callable constructed for the benefit
# of a classmethod's 'cls' argument?
'implicit', # Was this type implicitly generated instead of explicitly
# specified by the user?
'special_sig', # Non-None for signatures that require special handling
# (currently only value is 'dict' for a signature similar to
# 'dict')
'from_type_type', # Was this callable generated by analyzing Type[...]
# instantiation?
'bound_args', # Bound type args, mostly unused but may be useful for
# tools that consume mypy ASTs
'def_extras', # Information about original definition we want to serialize.
# This is used for more detailed error messages.
)
def __init__(self,
arg_types: Sequence[Type],
arg_kinds: List[int],
arg_names: Sequence[Optional[str]],
ret_type: Type,
fallback: Instance,
name: Optional[str] = None,
definition: Optional[SymbolNode] = None,
variables: Optional[List[TypeVarDef]] = None,
line: int = -1,
column: int = -1,
is_ellipsis_args: bool = False,
implicit: bool = False,
special_sig: Optional[str] = None,
from_type_type: bool = False,
bound_args: Sequence[Optional[Type]] = (),
def_extras: Optional[Dict[str, Any]] = None,
) -> None:
super().__init__(line, column)
assert len(arg_types) == len(arg_kinds) == len(arg_names)
if variables is None:
variables = []
self.arg_types = list(arg_types)
self.arg_kinds = arg_kinds
self.arg_names = list(arg_names)
self.min_args = arg_kinds.count(ARG_POS)
self.ret_type = ret_type
self.fallback = fallback
assert not name or '<bound method' not in name
self.name = name
self.definition = definition
self.variables = variables
self.is_ellipsis_args = is_ellipsis_args
self.implicit = implicit
self.special_sig = special_sig
self.from_type_type = from_type_type
if not bound_args:
bound_args = ()
self.bound_args = bound_args
if def_extras:
self.def_extras = def_extras
elif isinstance(definition, FuncDef):
# This information would be lost if we don't have definition
# after serialization, but it is useful in error messages.
# TODO: decide how to add more info here (file, line, column)
# without changing interface hash.
self.def_extras = {'first_arg': definition.arg_names[0]
if definition.arg_names and definition.info and
not definition.is_static else None}
else:
self.def_extras = {}
def copy_modified(self,
arg_types: Bogus[Sequence[Type]] = _dummy,
arg_kinds: Bogus[List[int]] = _dummy,
arg_names: Bogus[List[Optional[str]]] = _dummy,
ret_type: Bogus[Type] = _dummy,
fallback: Bogus[Instance] = _dummy,
name: Bogus[Optional[str]] = _dummy,
definition: Bogus[SymbolNode] = _dummy,
variables: Bogus[List[TypeVarDef]] = _dummy,
line: Bogus[int] = _dummy,
column: Bogus[int] = _dummy,
is_ellipsis_args: Bogus[bool] = _dummy,
implicit: Bogus[bool] = _dummy,
special_sig: Bogus[Optional[str]] = _dummy,
from_type_type: Bogus[bool] = _dummy,