Repository navigation
Expand file tree
/
Copy pathtypes.py
More file actions
1805 lines (1423 loc) · 61.9 KB
/
Copy pathtypes.py
File metadata and controls
1805 lines (1423 loc) · 61.9 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."""
from abc import abstractmethod
import copy
from collections import OrderedDict
from typing import (
Any, TypeVar, Dict, List, Tuple, cast, Generic, Set, Sequence, Optional, Union, Iterable,
NamedTuple, Callable,
)
import mypy.nodes
from mypy.nodes import (
INVARIANT, SymbolNode,
ARG_POS, ARG_OPT, ARG_STAR, ARG_STAR2, ARG_NAMED, ARG_NAMED_OPT,
)
from mypy.sharedparse import argument_elide_name
from mypy.util import IdMapper
T = TypeVar('T')
JsonDict = Dict[str, Any]
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."""
line = 0
column = 0
can_be_true = True
can_be_false = True
def __init__(self, line: int = -1, column: int = -1) -> None:
self.line = line
self.column = column
def get_line(self) -> int:
return self.line
def get_column(self) -> int:
return self.column
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 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: 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 = ''
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
line = 0
column = 0
def __init__(self, name: str, id: Union[TypeVarId, int], values: List[Type],
upper_bound: Type, variance: int = INVARIANT, line: int = -1,
column: int = -1) -> None:
assert values is not None, "No restrictions must be represented by empty list"
self.name = name
if isinstance(id, int):
id = TypeVarId(id)
self.id = id
self.values = values
self.upper_bound = upper_bound
self.variance = variance
self.line = line
self.column = column
@staticmethod
def new_unification_variable(old: 'TypeVarDef') -> 'TypeVarDef':
new_id = TypeVarId.new(meta_level=1)
return TypeVarDef(old.name, new_id, old.values,
old.upper_bound, old.variance, old.line, old.column)
def get_line(self) -> int:
return self.line
def get_column(self) -> int:
return self.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,
'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['id'],
[deserialize_type(v) for v in data['values']],
deserialize_type(data['upper_bound']),
data['variance'],
)
class UnboundType(Type):
"""Instance type that has not been bound during semantic analysis."""
name = ''
args = None # type: List[Type]
# should this type be wrapped in an Optional?
optional = False
# special case for X[()]
empty_tuple_index = False
def __init__(self,
name: str,
args: List[Type] = None,
line: int = -1,
column: int = -1,
optional: bool = False,
empty_tuple_index: bool = False) -> None:
if not args:
args = []
self.name = name
self.args = args
self.optional = optional
self.empty_tuple_index = empty_tuple_index
super().__init__(line, column)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_unbound_type(self)
def serialize(self) -> JsonDict:
return {'.class': 'UnboundType',
'name': self.name,
'args': [a.serialize() for a in self.args],
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'UnboundType':
assert data['.class'] == 'UnboundType'
return UnboundType(data['name'],
[deserialize_type(a) for a in data['args']])
class CallableArgument(Type):
"""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(Type):
"""Information about argument types and names [...].
This is only 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.
"""
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, "Sythetic types don't serialize"
class AnyType(Type):
"""The type 'Any'."""
def __init__(self, implicit: bool = False, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.implicit = implicit
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_any(self)
def serialize(self) -> JsonDict:
return {'.class': 'AnyType'}
@classmethod
def deserialize(cls, data: JsonDict) -> 'AnyType':
assert data['.class'] == 'AnyType'
return AnyType()
class UninhabitedType(Type):
"""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, NoneTyp fills this role.
In general, for any type T:
join(UninhabitedType, T) = T
meet(UninhabitedType, T) = UninhabitedType
is_subtype(UninhabitedType, T) = True
"""
can_be_true = False
can_be_false = False
is_noreturn = False # Does this come from a NoReturn? Purely for error messages.
def __init__(self, is_noreturn: bool = False, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
self.is_noreturn = is_noreturn
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_uninhabited_type(self)
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 NoneTyp(Type):
"""The type of 'None'.
This type can be written by users as 'None'.
"""
can_be_true = False
def __init__(self, line: int = -1, column: int = -1) -> None:
super().__init__(line, column)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_none_type(self)
def serialize(self) -> JsonDict:
return {'.class': 'NoneTyp'}
@classmethod
def deserialize(cls, data: JsonDict) -> 'NoneTyp':
assert data['.class'] == 'NoneTyp'
return NoneTyp()
class ErasedType(Type):
"""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(Type):
"""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: str = None, line: int = -1, column: int = -1) -> None:
self.source = source
super().__init__(line, column)
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(mypy.nodes.SymbolTable(),
mypy.nodes.ClassDef('<NOT READY>', mypy.nodes.Block([])),
'<NOT READY>')
class Instance(Type):
"""An instance type of form C[T1, ..., Tn].
The list of type variables may be empty.
"""
type = None # type: mypy.nodes.TypeInfo
args = None # type: List[Type]
erased = False # True if result of type variable substitution
invalid = False # True if recovered after incorrect number of type arguments error
def __init__(self, typ: mypy.nodes.TypeInfo, args: List[Type],
line: int = -1, column: int = -1, erased: bool = False) -> None:
assert(typ is NOT_READY or typ.fullname() not in ["builtins.Any", "typing.Any"])
self.type = typ
self.args = args
self.erased = erased
super().__init__(line, column)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_instance(self)
type_ref = None # type: str
def serialize(self) -> Union[JsonDict, str]:
assert self.type is not None
type_ref = self.type.fullname()
if not self.args:
return type_ref
data = {'.class': 'Instance',
} # type: JsonDict
data['type_ref'] = type_ref
data['args'] = [arg.serialize() for arg in self.args]
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.
return inst
def copy_modified(self, *, args: List[Type]) -> 'Instance':
return Instance(self.type, args, self.line, self.column, self.erased)
class TypeVarType(Type):
"""A type variable type.
This refers to either a class type variable (id > 0) or a function
type variable (id < 0).
"""
name = '' # Name of the type variable (for messages and debugging)
id = None # type: TypeVarId
values = None # type: List[Type] # Value restriction, empty list if no restriction
upper_bound = None # type: Type # Upper bound for values
# See comments in TypeVarDef for more about variance.
variance = INVARIANT # type: int
def __init__(self, binder: TypeVarDef, line: int = -1, column: int = -1) -> None:
self.name = binder.name
self.id = binder.id
self.values = binder.values
self.upper_bound = binder.upper_bound
self.variance = binder.variance
super().__init__(line, column)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_type_var(self)
def erase_to_union_or_bound(self) -> Type:
if self.values:
return UnionType.make_simplified_union(self.values)
else:
return self.upper_bound
def serialize(self) -> JsonDict:
assert not self.id.is_meta_var()
return {'.class': 'TypeVarType',
'name': self.name,
'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['id'],
[deserialize_type(v) for v in data['values']],
deserialize_type(data['upper_bound']),
data['variance'])
return TypeVarType(tvdef)
class FunctionLike(Type):
"""Abstract base class for function types."""
can_be_false = False
@abstractmethod
def is_type_obj(self) -> bool: pass
def is_concrete_type_obj(self) -> bool:
return self.is_type_obj()
@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
# Corresponding instance type (e.g. builtins.type)
fallback = None # type: Instance
_dummy = object() # type: Any
FormalArgument = NamedTuple('FormalArgument', [
('name', Optional[str]),
('pos', Optional[int]),
('typ', Type),
('required', bool)])
class CallableType(FunctionLike):
"""Type of a non-overloaded callable object (function)."""
arg_types = None # type: List[Type] # Types of function arguments
arg_kinds = None # type: List[int] # ARG_ constants
arg_names = None # type: List[Optional[str]] # None if not a keyword argument
min_args = 0 # Minimum number of arguments; derived from arg_kinds
is_var_arg = False # Is it a varargs function? derived from arg_kinds
is_kw_arg = False
ret_type = None # type: Type # Return value type
name = '' # type: Optional[str] # Name (may be None; for error messages)
definition = None # type: Optional[SymbolNode] # For error messages. May be None.
# Type variables for a generic function
variables = None # type: List[TypeVarDef]
# Is this Callable[..., t] (with literal '...')?
is_ellipsis_args = False
# Is this callable constructed for the benefit of a classmethod's 'cls' argument?
is_classmethod_class = False
# Was this type implicitly generated instead of explicitly specified by the user?
implicit = False
# Defined for signatures that require special handling (currently only value is 'dict'
# for a signature similar to 'dict')
special_sig = None # type: Optional[str]
# Was this callable generated by analyzing Type[...] instantiation?
from_type_type = False # type: bool
bound_args = None # type: List[Optional[Type]]
def __init__(self,
arg_types: List[Type],
arg_kinds: List[int],
arg_names: List[Optional[str]],
ret_type: Type,
fallback: Instance,
name: str = None,
definition: SymbolNode = None,
variables: List[TypeVarDef] = None,
line: int = -1,
column: int = -1,
is_ellipsis_args: bool = False,
implicit: bool = False,
is_classmethod_class: bool = False,
special_sig: Optional[str] = None,
from_type_type: bool = False,
bound_args: List[Optional[Type]] = None,
) -> None:
if variables is None:
variables = []
assert len(arg_types) == len(arg_kinds)
assert not any(tp is None for tp in arg_types), "No annotation must be Any, not None"
self.arg_types = arg_types
self.arg_kinds = arg_kinds
self.arg_names = arg_names
self.min_args = arg_kinds.count(ARG_POS)
self.is_var_arg = ARG_STAR in arg_kinds
self.is_kw_arg = ARG_STAR2 in arg_kinds
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.is_classmethod_class = is_classmethod_class
self.special_sig = special_sig
self.from_type_type = from_type_type
self.bound_args = bound_args or []
super().__init__(line, column)
def copy_modified(self,
arg_types: List[Type] = _dummy,
arg_kinds: List[int] = _dummy,
arg_names: List[Optional[str]] = _dummy,
ret_type: Type = _dummy,
fallback: Instance = _dummy,
name: Optional[str] = _dummy,
definition: SymbolNode = _dummy,
variables: List[TypeVarDef] = _dummy,
line: int = _dummy,
column: int = _dummy,
is_ellipsis_args: bool = _dummy,
special_sig: Optional[str] = _dummy,
from_type_type: bool = _dummy,
bound_args: List[Optional[Type]] = _dummy) -> 'CallableType':
return CallableType(
arg_types=arg_types if arg_types is not _dummy else self.arg_types,
arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,
arg_names=arg_names if arg_names is not _dummy else self.arg_names,
ret_type=ret_type if ret_type is not _dummy else self.ret_type,
fallback=fallback if fallback is not _dummy else self.fallback,
name=name if name is not _dummy else self.name,
definition=definition if definition is not _dummy else self.definition,
variables=variables if variables is not _dummy else self.variables,
line=line if line is not _dummy else self.line,
column=column if column is not _dummy else self.column,
is_ellipsis_args=(
is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args),
implicit=self.implicit,
is_classmethod_class=self.is_classmethod_class,
special_sig=special_sig if special_sig is not _dummy else self.special_sig,
from_type_type=from_type_type if from_type_type is not _dummy else self.from_type_type,
bound_args=bound_args if bound_args is not _dummy else self.bound_args,
)
def is_type_obj(self) -> bool:
t = self.fallback.type
return t is not None and t.is_metaclass()
def is_concrete_type_obj(self) -> bool:
return self.is_type_obj() and self.is_classmethod_class
def type_object(self) -> mypy.nodes.TypeInfo:
assert self.is_type_obj()
ret = self.ret_type
if isinstance(ret, TupleType):
ret = ret.fallback
if isinstance(ret, TypeVarType):
ret = ret.upper_bound
assert isinstance(ret, Instance)
return ret.type
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_callable_type(self)
def with_name(self, name: str) -> 'CallableType':
"""Return a copy of this type with the specified name."""
return self.copy_modified(ret_type=self.ret_type, name=name)
def get_name(self) -> Optional[str]:
return self.name
def max_fixed_args(self) -> int:
n = len(self.arg_types)
if self.is_var_arg:
n -= 1
return n
def corresponding_argument(self, model: FormalArgument) -> Optional[FormalArgument]:
"""Return the argument in this function that corresponds to `model`"""
by_name = self.argument_by_name(model.name)
by_pos = self.argument_by_position(model.pos)
if by_name is None and by_pos is None:
return None
if by_name is not None and by_pos is not None:
if by_name == by_pos:
return by_name
# If we're dealing with an optional pos-only and an optional
# name-only arg, merge them. This is the case for all functions
# taking both *args and **args, or a pair of functions like so:
# def right(a: int = ...) -> None: ...
# def left(__a: int = ..., *, a: int = ...) -> None: ...
from mypy.subtypes import is_equivalent
if (not (by_name.required or by_pos.required)
and by_pos.name is None
and by_name.pos is None
and is_equivalent(by_name.typ, by_pos.typ)):
return FormalArgument(by_name.name, by_pos.pos, by_name.typ, False)
return by_name if by_name is not None else by_pos
def argument_by_name(self, name: Optional[str]) -> Optional[FormalArgument]:
if name is None:
return None
seen_star = False
star2_type = None # type: Optional[Type]
for i, (arg_name, kind, typ) in enumerate(
zip(self.arg_names, self.arg_kinds, self.arg_types)):
# No more positional arguments after these.
if kind in (ARG_STAR, ARG_STAR2, ARG_NAMED, ARG_NAMED_OPT):
seen_star = True
if kind == ARG_STAR:
continue
if kind == ARG_STAR2:
star2_type = typ
continue
if arg_name == name:
position = None if seen_star else i
return FormalArgument(name, position, typ, kind in (ARG_POS, ARG_NAMED))
if star2_type is not None:
return FormalArgument(name, None, star2_type, False)
return None
def argument_by_position(self, position: Optional[int]) -> Optional[FormalArgument]:
if position is None:
return None
if self.is_var_arg:
for kind, typ in zip(self.arg_kinds, self.arg_types):
if kind == ARG_STAR:
star_type = typ
break
if position >= len(self.arg_names):
if self.is_var_arg:
return FormalArgument(None, position, star_type, False)
else:
return None
name, kind, typ = (
self.arg_names[position],
self.arg_kinds[position],
self.arg_types[position],
)
if kind in (ARG_POS, ARG_OPT):
return FormalArgument(name, position, typ, kind == ARG_POS)
else:
if self.is_var_arg:
return FormalArgument(None, position, star_type, False)
else:
return None
def items(self) -> List['CallableType']:
return [self]
def is_generic(self) -> bool:
return bool(self.variables)
def type_var_ids(self) -> List[TypeVarId]:
a = [] # type: List[TypeVarId]
for tv in self.variables:
a.append(tv.id)
return a
def serialize(self) -> JsonDict:
# TODO: As an optimization, leave out everything related to
# generic functions for non-generic functions.
return {'.class': 'CallableType',
'arg_types': [t.serialize() for t in self.arg_types],
'arg_kinds': self.arg_kinds,
'arg_names': self.arg_names,
'ret_type': self.ret_type.serialize(),
'fallback': self.fallback.serialize(),
'name': self.name,
# We don't serialize the definition (only used for error messages).
'variables': [v.serialize() for v in self.variables],
'is_ellipsis_args': self.is_ellipsis_args,
'implicit': self.implicit,
'is_classmethod_class': self.is_classmethod_class,
'bound_args': [(None if t is None else t.serialize())
for t in self.bound_args],
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'CallableType':
assert data['.class'] == 'CallableType'
# TODO: Set definition to the containing SymbolNode?
return CallableType([deserialize_type(t) for t in data['arg_types']],
data['arg_kinds'],
data['arg_names'],
deserialize_type(data['ret_type']),
Instance.deserialize(data['fallback']),
name=data['name'],
variables=[TypeVarDef.deserialize(v) for v in data['variables']],
is_ellipsis_args=data['is_ellipsis_args'],
implicit=data['implicit'],
is_classmethod_class=data['is_classmethod_class'],
bound_args=[(None if t is None else deserialize_type(t))
for t in data['bound_args']],
)
class Overloaded(FunctionLike):
"""Overloaded function type T1, ... Tn, where each Ti is CallableType.
The variant to call is chosen based on static argument
types. Overloaded function types can only be defined in stub
files, and thus there is no explicit runtime dispatch
implementation.
"""
_items = None # type: List[CallableType] # Must not be empty
def __init__(self, items: List[CallableType]) -> None:
self._items = items
self.fallback = items[0].fallback
super().__init__(items[0].line, items[0].column)
def items(self) -> List[CallableType]:
return self._items
def name(self) -> Optional[str]:
return self.get_name()
def is_type_obj(self) -> bool:
# All the items must have the same type object status, so it's
# sufficient to query only (any) one of them.
return self._items[0].is_type_obj()
def type_object(self) -> mypy.nodes.TypeInfo:
# All the items must have the same type object, so it's sufficient to
# query only (any) one of them.
return self._items[0].type_object()
def with_name(self, name: str) -> 'Overloaded':
ni = [] # type: List[CallableType]
for it in self._items:
ni.append(it.with_name(name))
return Overloaded(ni)
def get_name(self) -> Optional[str]:
return self._items[0].name
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_overloaded(self)
def serialize(self) -> JsonDict:
return {'.class': 'Overloaded',
'items': [t.serialize() for t in self.items()],
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'Overloaded':
assert data['.class'] == 'Overloaded'
return Overloaded([CallableType.deserialize(t) for t in data['items']])
class TupleType(Type):
"""The tuple type Tuple[T1, ..., Tn] (at least one type argument).
Instance variables:
items: tuple item types
fallback: the underlying instance type that is used for non-tuple methods
(this is currently always builtins.tuple, but it could be different for named
tuples, for example)
implicit: if True, derived from a tuple expression (t,....) instead of Tuple[t, ...]
"""
items = None # type: List[Type]
fallback = None # type: Instance
implicit = False
def __init__(self, items: List[Type], fallback: Instance, line: int = -1,
column: int = -1, implicit: bool = False) -> None:
self.items = items
self.fallback = fallback
self.implicit = implicit
self.can_be_true = len(self.items) > 0
self.can_be_false = len(self.items) == 0
super().__init__(line, column)
def length(self) -> int:
return len(self.items)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_tuple_type(self)
def serialize(self) -> JsonDict:
return {'.class': 'TupleType',
'items': [t.serialize() for t in self.items],
'fallback': self.fallback.serialize(),
'implicit': self.implicit,
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'TupleType':
assert data['.class'] == 'TupleType'
return TupleType([deserialize_type(t) for t in data['items']],
Instance.deserialize(data['fallback']),
implicit=data['implicit'])
def copy_modified(self, *, fallback: Instance = None,
items: List[Type] = None) -> 'TupleType':
if fallback is None:
fallback = self.fallback
if items is None:
items = self.items
return TupleType(items, fallback, self.line, self.column)
def slice(self, begin: int, stride: int, end: int) -> 'TupleType':
return TupleType(self.items[begin:end:stride], self.fallback,
self.line, self.column, self.implicit)
class TypedDictType(Type):
"""The type of a TypedDict instance. TypedDict(K1=VT1, ..., Kn=VTn)
A TypedDictType can be either named or anonymous.
If it is anonymous then its fallback will be an Instance of Mapping[str, V].
If it is named then its fallback will be an Instance of the named type (ex: "Point")
whose TypeInfo has a typeddict_type that is anonymous.
"""
items = None # type: OrderedDict[str, Type] # (item_name, item_type)
fallback = None # type: Instance
def __init__(self, items: 'OrderedDict[str, Type]', fallback: Instance,
line: int = -1, column: int = -1) -> None:
self.items = items
self.fallback = fallback
self.can_be_true = len(self.items) > 0
self.can_be_false = len(self.items) == 0
super().__init__(line, column)
def accept(self, visitor: 'TypeVisitor[T]') -> T:
return visitor.visit_typeddict_type(self)
def serialize(self) -> JsonDict:
return {'.class': 'TypedDictType',
'items': [[n, t.serialize()] for (n, t) in self.items.items()],
'fallback': self.fallback.serialize(),
}
@classmethod
def deserialize(cls, data: JsonDict) -> 'TypedDictType':
assert data['.class'] == 'TypedDictType'
return TypedDictType(OrderedDict([(n, deserialize_type(t))
for (n, t) in data['items']]),
Instance.deserialize(data['fallback']))
def as_anonymous(self) -> 'TypedDictType':
if self.fallback.type.fullname() == 'typing.Mapping':
return self
assert self.fallback.type.typeddict_type is not None
return self.fallback.type.typeddict_type.as_anonymous()
def copy_modified(self, *, fallback: Instance = None,
item_types: List[Type] = None) -> 'TypedDictType':
if fallback is None:
fallback = self.fallback
if item_types is None:
items = self.items
else:
items = OrderedDict(zip(self.items, item_types))
return TypedDictType(items, fallback, self.line, self.column)
def create_anonymous_fallback(self, *, value_type: Type) -> Instance:
anonymous = self.as_anonymous()
return anonymous.fallback.copy_modified(args=[ # i.e. Mapping
anonymous.fallback.args[0], # i.e. str
value_type
])
def names_are_wider_than(self, other: 'TypedDictType') -> bool:
return len(other.items.keys() - self.items.keys()) == 0
def zip(self, right: 'TypedDictType') -> Iterable[Tuple[str, Type, Type]]:
left = self
for (item_name, left_item_type) in left.items.items():
right_item_type = right.items.get(item_name)
if right_item_type is not None:
yield (item_name, left_item_type, right_item_type)
def zipall(self, right: 'TypedDictType') \
-> Iterable[Tuple[str, Optional[Type], Optional[Type]]]:
left = self
for (item_name, left_item_type) in left.items.items():
right_item_type = right.items.get(item_name)
yield (item_name, left_item_type, right_item_type)
for (item_name, right_item_type) in right.items.items():
if item_name in left.items:
continue
yield (item_name, None, right_item_type)
class StarType(Type):
"""The star type *type_parameter.
This is not a real type but a syntactic AST construct.
"""
type = None # type: Type
def __init__(self, type: Type, line: int = -1, column: int = -1) -> None:
self.type = type
super().__init__(line, column)