forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecker.py
2667 lines (2288 loc) · 111 KB
/
checker.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
"""Mypy type checker."""
import itertools
import contextlib
import os
import os.path
from typing import (
Any, Dict, Set, List, cast, Tuple, TypeVar, Union, Optional, NamedTuple
)
from mypy.errors import Errors, report_internal_error
from mypy.nodes import (
SymbolTable, Node, MypyFile, Var,
OverloadedFuncDef, FuncDef, FuncItem, FuncBase, TypeInfo,
ClassDef, GDEF, Block, AssignmentStmt, NameExpr, MemberExpr, IndexExpr,
TupleExpr, ListExpr, ExpressionStmt, ReturnStmt, IfStmt,
WhileStmt, OperatorAssignmentStmt, WithStmt, AssertStmt,
RaiseStmt, TryStmt, ForStmt, DelStmt, CallExpr, IntExpr, StrExpr,
BytesExpr, UnicodeExpr, FloatExpr, OpExpr, UnaryExpr, CastExpr, RevealTypeExpr, SuperExpr,
TypeApplication, DictExpr, SliceExpr, FuncExpr, TempNode, SymbolTableNode,
Context, ListComprehension, ConditionalExpr, GeneratorExpr,
Decorator, SetExpr, TypeVarExpr, PrintStmt,
LITERAL_TYPE, BreakStmt, ContinueStmt, ComparisonExpr, StarExpr,
YieldFromExpr, NamedTupleExpr, SetComprehension,
DictionaryComprehension, ComplexExpr, EllipsisExpr, TypeAliasExpr,
RefExpr, YieldExpr, BackquoteExpr, ImportFrom, ImportAll, ImportBase,
CONTRAVARIANT, COVARIANT
)
from mypy.nodes import function_type, method_type, method_type_with_fallback
from mypy import nodes
from mypy.types import (
Type, AnyType, CallableType, Void, FunctionLike, Overloaded, TupleType,
Instance, NoneTyp, ErrorType, strip_type,
UnionType, TypeVarId, TypeVarType, PartialType, DeletedType, UninhabitedType
)
from mypy.sametypes import is_same_type
from mypy.messages import MessageBuilder
import mypy.checkexpr
from mypy.checkmember import map_type_from_supertype
from mypy import defaults
from mypy import messages
from mypy.subtypes import (
is_subtype, is_equivalent, is_proper_subtype,
is_more_precise, restrict_subtype_away
)
from mypy.maptype import map_instance_to_supertype
from mypy.semanal import self_type, set_callable_name, refers_to_fullname
from mypy.erasetype import erase_typevars
from mypy.expandtype import expand_type_by_instance, expand_type
from mypy.visitor import NodeVisitor
from mypy.join import join_simple, join_types
from mypy.treetransform import TransformVisitor
from mypy.meet import meet_simple, nearest_builtin_ancestor, is_overlapping_types
from mypy import experiments
T = TypeVar('T')
def min_with_None_large(x: T, y: T) -> T:
"""Return min(x, y) but with a < None for all variables a that are not None"""
if x is None:
return y
return min(x, x if y is None else y)
class Frame(Dict[Any, Type]):
pass
class Key(AnyType):
pass
class ConditionalTypeBinder:
"""Keep track of conditional types of variables."""
def __init__(self) -> None:
self.frames = [] # type: List[Frame]
# The first frame is special: it's the declared types of variables.
self.frames.append(Frame())
# Set of other keys to invalidate if a key is changed.
self.dependencies = {} # type: Dict[Key, Set[Key]]
# Set of keys with dependencies added already.
self._added_dependencies = set() # type: Set[Key]
self.frames_on_escape = {} # type: Dict[int, List[Frame]]
self.try_frames = set() # type: Set[int]
self.loop_frames = [] # type: List[int]
def _add_dependencies(self, key: Key, value: Key = None) -> None:
if value is None:
value = key
if value in self._added_dependencies:
return
self._added_dependencies.add(value)
if isinstance(key, tuple):
key = cast(Any, key) # XXX sad
if key != value:
self.dependencies[key] = set()
self.dependencies.setdefault(key, set()).add(value)
for elt in cast(Any, key):
self._add_dependencies(elt, value)
def push_frame(self) -> Frame:
d = Frame()
self.frames.append(d)
return d
def _push(self, key: Key, type: Type, index: int=-1) -> None:
self._add_dependencies(key)
self.frames[index][key] = type
def _get(self, key: Key, index: int=-1) -> Type:
if index < 0:
index += len(self.frames)
for i in range(index, -1, -1):
if key in self.frames[i]:
return self.frames[i][key]
return None
def push(self, expr: Node, typ: Type) -> None:
if not expr.literal:
return
key = expr.literal_hash
self.frames[0][key] = self.get_declaration(expr)
self._push(key, typ)
def get(self, expr: Node) -> Type:
return self._get(expr.literal_hash)
def cleanse(self, expr: Node) -> None:
"""Remove all references to a Node from the binder."""
key = expr.literal_hash
for frame in self.frames:
if key in frame:
del frame[key]
def update_from_options(self, frames: List[Frame]) -> bool:
"""Update the frame to reflect that each key will be updated
as in one of the frames. Return whether any item changes.
If a key is declared as AnyType, only update it if all the
options are the same.
"""
changed = False
keys = set(key for f in frames for key in f)
for key in keys:
current_value = self._get(key)
resulting_values = [f.get(key, current_value) for f in frames]
if any(x is None for x in resulting_values):
continue
if isinstance(self.frames[0].get(key), AnyType):
type = resulting_values[0]
if not all(is_same_type(type, t) for t in resulting_values[1:]):
type = AnyType()
else:
type = resulting_values[0]
for other in resulting_values[1:]:
type = join_simple(self.frames[0][key], type, other)
if not is_same_type(type, current_value):
self._push(key, type)
changed = True
return changed
def update_expand(self, frame: Frame, index: int = -1) -> bool:
"""Update frame to include another one, if that other one is larger than the current value.
Return whether anything changed."""
result = False
for key in frame:
old_type = self._get(key, index)
if old_type is None:
continue
replacement = join_simple(self.frames[0][key], old_type, frame[key])
if not is_same_type(replacement, old_type):
self._push(key, replacement, index)
result = True
return result
def pop_frame(self, canskip=True, fallthrough=False) -> Tuple[bool, Frame]:
"""Pop a frame.
If canskip, then allow types to skip all the inner frame
blocks. That is, changes that happened in the inner frames
are not necessarily reflected in the outer frame (for example,
an if block that may be skipped).
If fallthrough, then allow types to escape from the inner
frame to the resulting frame. That is, the state of types at
the end of the last frame are allowed to fall through into the
enclosing frame.
Return whether the newly innermost frame was modified since it
was last on top, and what it would be if the block had run to
completion.
"""
result = self.frames.pop()
options = self.frames_on_escape.pop(len(self.frames) - 1, []) # type: List[Frame]
if canskip:
options.append(self.frames[-1])
if fallthrough:
options.append(result)
changed = self.update_from_options(options)
return (changed, result)
def get_declaration(self, expr: Any) -> Type:
if hasattr(expr, 'node') and isinstance(expr.node, Var):
type = expr.node.type
if isinstance(type, PartialType):
return None
return type
else:
return self.frames[0].get(expr.literal_hash)
def assign_type(self, expr: Node,
type: Type,
declared_type: Type,
restrict_any: bool = False) -> None:
if not expr.literal:
return
self.invalidate_dependencies(expr)
if declared_type is None:
# Not sure why this happens. It seems to mainly happen in
# member initialization.
return
if not is_subtype(type, declared_type):
# Pretty sure this is only happens when there's a type error.
# Ideally this function wouldn't be called if the
# expression has a type error, though -- do other kinds of
# errors cause this function to get called at invalid
# times?
return
# If x is Any and y is int, after x = y we do not infer that x is int.
# This could be changed.
# Eric: I'm changing it in weak typing mode, since Any is so common.
if (isinstance(self.most_recent_enclosing_type(expr, type), AnyType)
and not restrict_any):
pass
elif isinstance(type, AnyType):
self.push(expr, declared_type)
else:
self.push(expr, type)
for i in self.try_frames:
# XXX This should probably not copy the entire frame, but
# just copy this variable into a single stored frame.
self.allow_jump(i)
def invalidate_dependencies(self, expr: Node) -> None:
"""Invalidate knowledge of types that include expr, but not expr itself.
For example, when expr is foo.bar, invalidate foo.bar.baz and
foo.bar[0].
It is overly conservative: it invalidates globally, including
in code paths unreachable from here.
"""
for dep in self.dependencies.get(expr.literal_hash, set()):
for f in self.frames:
if dep in f:
del f[dep]
def most_recent_enclosing_type(self, expr: Node, type: Type) -> Type:
if isinstance(type, AnyType):
return self.get_declaration(expr)
key = expr.literal_hash
enclosers = ([self.get_declaration(expr)] +
[f[key] for f in self.frames
if key in f and is_subtype(type, f[key])])
return enclosers[-1]
def allow_jump(self, index: int) -> None:
new_frame = Frame()
for f in self.frames[index + 1:]:
for k in f:
new_frame[k] = f[k]
self.frames_on_escape.setdefault(index, []).append(new_frame)
def push_loop_frame(self):
self.loop_frames.append(len(self.frames) - 1)
def pop_loop_frame(self):
self.loop_frames.pop()
def __enter__(self) -> None:
self.push_frame()
def __exit__(self, *args: Any) -> None:
self.pop_frame()
def meet_frames(*frames: Frame) -> Frame:
answer = Frame()
for f in frames:
for key in f:
if key in answer:
answer[key] = meet_simple(answer[key], f[key])
else:
answer[key] = f[key]
return answer
# A node which is postponed to be type checked during the next pass.
DeferredNode = NamedTuple(
'DeferredNode',
[
('node', Node),
('context_type_name', Optional[str]), # Name of the surrounding class (for error messages)
])
class TypeChecker(NodeVisitor[Type]):
"""Mypy type checker.
Type check mypy source files that have been semantically analyzed.
"""
# Target Python version
pyversion = defaults.PYTHON3_VERSION
# Are we type checking a stub?
is_stub = False
# Error message reporter
errors = None # type: Errors
# Utility for generating messages
msg = None # type: MessageBuilder
# Types of type checked nodes
type_map = None # type: Dict[Node, Type]
# Helper for managing conditional types
binder = None # type: ConditionalTypeBinder
# Helper for type checking expressions
expr_checker = None # type: mypy.checkexpr.ExpressionChecker
# Stack of function return types
return_types = None # type: List[Type]
# Type context for type inference
type_context = None # type: List[Type]
# Flags; true for dynamically typed functions
dynamic_funcs = None # type: List[bool]
# Stack of functions being type checked
function_stack = None # type: List[FuncItem]
# Set to True on return/break/raise, False on blocks that can block any of them
breaking_out = False
# Do weak type checking in this file
weak_opts = set() # type: Set[str]
# Stack of collections of variables with partial types
partial_types = None # type: List[Dict[Var, Context]]
globals = None # type: SymbolTable
modules = None # type: Dict[str, MypyFile]
# Nodes that couldn't be checked because some types weren't available. We'll run
# another pass and try these again.
deferred_nodes = None # type: List[DeferredNode]
# Type checking pass number (0 = first pass)
pass_num = 0
# Have we deferred the current function? If yes, don't infer additional
# types during this pass within the function.
current_node_deferred = False
# This makes it an error to call an untyped function from a typed one
disallow_untyped_calls = False
# This makes it an error to define an untyped or partially-typed function
disallow_untyped_defs = False
# Should we check untyped function defs?
check_untyped_defs = False
warn_incomplete_stub = False
warn_redundant_casts = False
is_typeshed_stub = False
def __init__(self, errors: Errors, modules: Dict[str, MypyFile],
pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
disallow_untyped_calls=False, disallow_untyped_defs=False,
check_untyped_defs=False, warn_incomplete_stub=False,
warn_redundant_casts=False) -> None:
"""Construct a type checker.
Use errors to report type check errors.
"""
self.errors = errors
self.modules = modules
self.pyversion = pyversion
self.msg = MessageBuilder(errors, modules)
self.type_map = {}
self.binder = ConditionalTypeBinder()
self.binder.push_frame()
self.expr_checker = mypy.checkexpr.ExpressionChecker(self, self.msg)
self.return_types = []
self.type_context = []
self.dynamic_funcs = []
self.function_stack = []
self.weak_opts = set() # type: Set[str]
self.partial_types = []
self.deferred_nodes = []
self.pass_num = 0
self.current_node_deferred = False
self.disallow_untyped_calls = disallow_untyped_calls
self.disallow_untyped_defs = disallow_untyped_defs
self.check_untyped_defs = check_untyped_defs
self.warn_incomplete_stub = warn_incomplete_stub
self.warn_redundant_casts = warn_redundant_casts
def visit_file(self, file_node: MypyFile, path: str) -> None:
"""Type check a mypy file with the given path."""
self.pass_num = 0
self.is_stub = file_node.is_stub
self.errors.set_file(path)
self.globals = file_node.names
self.weak_opts = file_node.weak_opts
self.enter_partial_types()
# gross, but no other clear way to tell
self.is_typeshed_stub = self.is_stub and 'typeshed' in os.path.normpath(path).split(os.sep)
for d in file_node.defs:
self.accept(d)
self.leave_partial_types()
if self.deferred_nodes:
self.check_second_pass()
self.current_node_deferred = False
all_ = self.globals.get('__all__')
if all_ is not None and all_.type is not None:
seq_str = self.named_generic_type('typing.Sequence',
[self.named_type('builtins.str')])
if not is_subtype(all_.type, seq_str):
str_seq_s, all_s = self.msg.format_distinctly(seq_str, all_.type)
self.fail(messages.ALL_MUST_BE_SEQ_STR.format(str_seq_s, all_s),
all_.node)
def check_second_pass(self):
"""Run second pass of type checking which goes through deferred nodes."""
self.pass_num = 1
for node, type_name in self.deferred_nodes:
if type_name:
self.errors.push_type(type_name)
self.accept(node)
if type_name:
self.errors.pop_type()
self.deferred_nodes = []
def handle_cannot_determine_type(self, name: str, context: Context) -> None:
if self.pass_num == 0 and self.function_stack:
# Don't report an error yet. Just defer.
node = self.function_stack[-1]
if self.errors.type_name:
type_name = self.errors.type_name[-1]
else:
type_name = None
self.deferred_nodes.append(DeferredNode(node, type_name))
# Set a marker so that we won't infer additional types in this
# function. Any inferred types could be bogus, because there's at
# least one type that we don't know.
self.current_node_deferred = True
else:
self.msg.cannot_determine_type(name, context)
def accept(self, node: Node, type_context: Type = None) -> Type:
"""Type check a node in the given type context."""
self.type_context.append(type_context)
try:
typ = node.accept(self)
except Exception as err:
report_internal_error(err, self.errors.file, node.line)
self.type_context.pop()
self.store_type(node, typ)
if self.typing_mode_none():
return AnyType()
else:
return typ
def accept_in_frame(self, node: Node, type_context: Type = None,
repeat_till_fixed: bool = False) -> Type:
"""Type check a node in the given type context in a new frame of inferred types."""
while True:
self.binder.push_frame()
answer = self.accept(node, type_context)
changed, _ = self.binder.pop_frame(True, True)
self.breaking_out = False
if not repeat_till_fixed or not changed:
return answer
#
# Definitions
#
def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> Type:
num_abstract = 0
if defn.is_property:
# HACK: Infer the type of the property.
self.visit_decorator(defn.items[0])
for fdef in defn.items:
self.check_func_item(fdef.func, name=fdef.func.name())
if fdef.func.is_abstract:
num_abstract += 1
if num_abstract not in (0, len(defn.items)):
self.fail(messages.INCONSISTENT_ABSTRACT_OVERLOAD, defn)
if defn.info:
self.check_method_override(defn)
self.check_inplace_operator_method(defn)
self.check_overlapping_overloads(defn)
def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None:
for i, item in enumerate(defn.items):
for j, item2 in enumerate(defn.items[i + 1:]):
# TODO overloads involving decorators
sig1 = self.function_type(item.func)
sig2 = self.function_type(item2.func)
if is_unsafe_overlapping_signatures(sig1, sig2):
self.msg.overloaded_signatures_overlap(i + 1, i + j + 2,
item.func)
def is_generator_return_type(self, typ: Type) -> bool:
return is_subtype(self.named_generic_type('typing.Generator',
[AnyType(), AnyType(), AnyType()]),
typ)
def get_generator_yield_type(self, return_type: Type) -> Type:
if isinstance(return_type, AnyType):
return AnyType()
elif not self.is_generator_return_type(return_type):
# If the function doesn't have a proper Generator (or superclass) return type, anything
# is permissible.
return AnyType()
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType()
elif return_type.args:
return return_type.args[0]
else:
# If the function's declared supertype of Generator has no type
# parameters (i.e. is `object`), then the yielded values can't
# be accessed so any type is acceptable.
return AnyType()
def get_generator_receive_type(self, return_type: Type) -> Type:
if isinstance(return_type, AnyType):
return AnyType()
elif not self.is_generator_return_type(return_type):
# If the function doesn't have a proper Generator (or superclass) return type, anything
# is permissible.
return AnyType()
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType()
elif return_type.type.fullname() == 'typing.Generator':
# Generator is the only type which specifies the type of values it can receive.
return return_type.args[1]
else:
# `return_type` is a supertype of Generator, so callers won't be able to send it
# values.
return Void()
def get_generator_return_type(self, return_type: Type) -> Type:
if isinstance(return_type, AnyType):
return AnyType()
elif not self.is_generator_return_type(return_type):
# If the function doesn't have a proper Generator (or superclass) return type, anything
# is permissible.
return AnyType()
elif not isinstance(return_type, Instance):
# Same as above, but written as a separate branch so the typechecker can understand.
return AnyType()
elif return_type.type.fullname() == 'typing.Generator':
# Generator is the only type which specifies the type of values it returns into
# `yield from` expressions.
return return_type.args[2]
else:
# `return_type` is supertype of Generator, so callers won't be able to see the return
# type when used in a `yield from` expression.
return AnyType()
def visit_func_def(self, defn: FuncDef) -> Type:
"""Type check a function definition."""
self.check_func_item(defn, name=defn.name())
if defn.info:
if not defn.is_dynamic():
self.check_method_override(defn)
self.check_inplace_operator_method(defn)
if defn.original_def:
# Override previous definition.
new_type = self.function_type(defn)
if isinstance(defn.original_def, FuncDef):
# Function definition overrides function definition.
if not is_same_type(new_type, self.function_type(defn.original_def)):
self.msg.incompatible_conditional_function_def(defn)
else:
# Function definition overrides a variable initialized via assignment.
orig_type = defn.original_def.type
if isinstance(orig_type, PartialType):
if orig_type.type is None:
# Ah this is a partial type. Give it the type of the function.
var = defn.original_def
partial_types = self.find_partial_types(var)
if partial_types is not None:
var.type = new_type
del partial_types[var]
else:
# Trying to redefine something like partial empty list as function.
self.fail(messages.INCOMPATIBLE_REDEFINITION, defn)
else:
# TODO: Update conditional type binder.
self.check_subtype(new_type, orig_type, defn,
messages.INCOMPATIBLE_REDEFINITION,
'redefinition with type',
'original type')
def check_func_item(self, defn: FuncItem,
type_override: CallableType = None,
name: str = None) -> Type:
"""Type check a function.
If type_override is provided, use it as the function type.
"""
# We may be checking a function definition or an anonymous function. In
# the first case, set up another reference with the precise type.
fdef = None # type: FuncDef
if isinstance(defn, FuncDef):
fdef = defn
self.function_stack.append(defn)
self.dynamic_funcs.append(defn.is_dynamic() and not type_override)
if fdef:
self.errors.push_function(fdef.name())
self.enter_partial_types()
typ = self.function_type(defn)
if type_override:
typ = type_override
if isinstance(typ, CallableType):
self.check_func_def(defn, typ, name)
else:
raise RuntimeError('Not supported')
self.leave_partial_types()
if fdef:
self.errors.pop_function()
self.dynamic_funcs.pop()
self.function_stack.pop()
self.current_node_deferred = False
def check_func_def(self, defn: FuncItem, typ: CallableType, name: str) -> None:
"""Type check a function definition."""
# Expand type variables with value restrictions to ordinary types.
for item, typ in self.expand_typevars(defn, typ):
old_binder = self.binder
self.binder = ConditionalTypeBinder()
self.binder.push_frame()
defn.expanded.append(item)
# We may be checking a function definition or an anonymous
# function. In the first case, set up another reference with the
# precise type.
if isinstance(item, FuncDef):
fdef = item
else:
fdef = None
if fdef:
# Check if __init__ has an invalid, non-None return type.
if (fdef.info and fdef.name() == '__init__' and
not isinstance(typ.ret_type, Void) and
not self.dynamic_funcs[-1]):
self.fail(messages.INIT_MUST_HAVE_NONE_RETURN_TYPE,
item.type)
show_untyped = not self.is_typeshed_stub or self.warn_incomplete_stub
if self.disallow_untyped_defs and show_untyped:
# Check for functions with unspecified/not fully specified types.
def is_implicit_any(t: Type) -> bool:
return isinstance(t, AnyType) and t.implicit
if fdef.type is None:
self.fail(messages.FUNCTION_TYPE_EXPECTED, fdef)
elif isinstance(fdef.type, CallableType):
if is_implicit_any(fdef.type.ret_type):
self.fail(messages.RETURN_TYPE_EXPECTED, fdef)
if any(is_implicit_any(t) for t in fdef.type.arg_types):
self.fail(messages.ARGUMENT_TYPE_EXPECTED, fdef)
if name in nodes.reverse_op_method_set:
self.check_reverse_op_method(item, typ, name)
elif name == '__getattr__':
self.check_getattr_method(typ, defn)
# Refuse contravariant return type variable
if isinstance(typ.ret_type, TypeVarType):
if typ.ret_type.variance == CONTRAVARIANT:
self.fail(messages.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT,
typ.ret_type)
# Check that Generator functions have the appropriate return type.
if defn.is_generator:
if not self.is_generator_return_type(typ.ret_type):
self.fail(messages.INVALID_RETURN_TYPE_FOR_GENERATOR, typ)
# Python 2 generators aren't allowed to return values.
if (self.pyversion[0] == 2 and
isinstance(typ.ret_type, Instance) and
typ.ret_type.type.fullname() == 'typing.Generator'):
if not (isinstance(typ.ret_type.args[2], Void)
or isinstance(typ.ret_type.args[2], AnyType)):
self.fail(messages.INVALID_GENERATOR_RETURN_ITEM_TYPE, typ)
# Push return type.
self.return_types.append(typ.ret_type)
# Store argument types.
for i in range(len(typ.arg_types)):
arg_type = typ.arg_types[i]
# Refuse covariant parameter type variables
if isinstance(arg_type, TypeVarType):
if arg_type.variance == COVARIANT:
self.fail(messages.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT,
arg_type)
if typ.arg_kinds[i] == nodes.ARG_STAR:
# builtins.tuple[T] is typing.Tuple[T, ...]
arg_type = self.named_generic_type('builtins.tuple',
[arg_type])
elif typ.arg_kinds[i] == nodes.ARG_STAR2:
arg_type = self.named_generic_type('builtins.dict',
[self.str_type(),
arg_type])
item.arguments[i].variable.type = arg_type
# Type check initialization expressions.
for arg in item.arguments:
init = arg.initialization_statement
if init:
self.accept(init)
# Clear out the default assignments from the binder
self.binder.pop_frame()
self.binder.push_frame()
# Type check body in a new scope.
self.accept_in_frame(item.body)
self.return_types.pop()
self.binder = old_binder
def check_reverse_op_method(self, defn: FuncItem, typ: CallableType,
method: str) -> None:
"""Check a reverse operator method such as __radd__."""
# This used to check for some very obscure scenario. It now
# just decides whether it's worth calling
# check_overlapping_op_methods().
if method in ('__eq__', '__ne__'):
# These are defined for all objects => can't cause trouble.
return
# With 'Any' or 'object' return type we are happy, since any possible
# return value is valid.
ret_type = typ.ret_type
if isinstance(ret_type, AnyType):
return
if isinstance(ret_type, Instance):
if ret_type.type.fullname() == 'builtins.object':
return
# Plausibly the method could have too few arguments, which would result
# in an error elsewhere.
if len(typ.arg_types) <= 2:
# TODO check self argument kind
# Check for the issue described above.
arg_type = typ.arg_types[1]
other_method = nodes.normal_from_reverse_op[method]
if isinstance(arg_type, Instance):
if not arg_type.type.has_readable_member(other_method):
return
elif isinstance(arg_type, AnyType):
return
elif isinstance(arg_type, UnionType):
if not arg_type.has_readable_member(other_method):
return
else:
return
typ2 = self.expr_checker.analyze_external_member_access(
other_method, arg_type, defn)
self.check_overlapping_op_methods(
typ, method, defn.info,
typ2, other_method, cast(Instance, arg_type),
defn)
def check_overlapping_op_methods(self,
reverse_type: CallableType,
reverse_name: str,
reverse_class: TypeInfo,
forward_type: Type,
forward_name: str,
forward_base: Instance,
context: Context) -> None:
"""Check for overlapping method and reverse method signatures.
Assume reverse method has valid argument count and kinds.
"""
# Reverse operator method that overlaps unsafely with the
# forward operator method can result in type unsafety. This is
# similar to overlapping overload variants.
#
# This example illustrates the issue:
#
# class X: pass
# class A:
# def __add__(self, x: X) -> int:
# if isinstance(x, X):
# return 1
# return NotImplemented
# class B:
# def __radd__(self, x: A) -> str: return 'x'
# class C(X, B): pass
# def f(b: B) -> None:
# A() + b # Result is 1, even though static type seems to be str!
# f(C())
#
# The reason for the problem is that B and X are overlapping
# types, and the return types are different. Also, if the type
# of x in __radd__ would not be A, the methods could be
# non-overlapping.
if isinstance(forward_type, CallableType):
# TODO check argument kinds
if len(forward_type.arg_types) < 1:
# Not a valid operator method -- can't succeed anyway.
return
# Construct normalized function signatures corresponding to the
# operator methods. The first argument is the left operand and the
# second operand is the right argument -- we switch the order of
# the arguments of the reverse method.
forward_tweaked = CallableType(
[forward_base, forward_type.arg_types[0]],
[nodes.ARG_POS] * 2,
[None] * 2,
forward_type.ret_type,
forward_type.fallback,
name=forward_type.name)
reverse_args = reverse_type.arg_types
reverse_tweaked = CallableType(
[reverse_args[1], reverse_args[0]],
[nodes.ARG_POS] * 2,
[None] * 2,
reverse_type.ret_type,
fallback=self.named_type('builtins.function'),
name=reverse_type.name)
if is_unsafe_overlapping_signatures(forward_tweaked,
reverse_tweaked):
self.msg.operator_method_signatures_overlap(
reverse_class.name(), reverse_name,
forward_base.type.name(), forward_name, context)
elif isinstance(forward_type, Overloaded):
for item in forward_type.items():
self.check_overlapping_op_methods(
reverse_type, reverse_name, reverse_class,
item, forward_name, forward_base, context)
elif not isinstance(forward_type, AnyType):
self.msg.forward_operator_not_callable(forward_name, context)
def check_inplace_operator_method(self, defn: FuncBase) -> None:
"""Check an inplace operator method such as __iadd__.
They cannot arbitrarily overlap with __add__.
"""
method = defn.name()
if method not in nodes.inplace_operator_methods:
return
typ = self.method_type(defn)
cls = defn.info
other_method = '__' + method[3:]
if cls.has_readable_member(other_method):
instance = self_type(cls)
typ2 = self.expr_checker.analyze_external_member_access(
other_method, instance, defn)
fail = False
if isinstance(typ2, FunctionLike):
if not is_more_general_arg_prefix(typ, typ2):
fail = True
else:
# TODO overloads
fail = True
if fail:
self.msg.signatures_incompatible(method, other_method, defn)
def check_getattr_method(self, typ: CallableType, context: Context) -> None:
method_type = CallableType([AnyType(), self.named_type('builtins.str')],
[nodes.ARG_POS, nodes.ARG_POS],
[None],
AnyType(),
self.named_type('builtins.function'))
if not is_subtype(typ, method_type):
self.msg.invalid_signature(typ, context)
def expand_typevars(self, defn: FuncItem,
typ: CallableType) -> List[Tuple[FuncItem, CallableType]]:
# TODO use generator
subst = [] # type: List[List[Tuple[TypeVarId, Type]]]
tvars = typ.variables or []
tvars = tvars[:]
if defn.info:
# Class type variables
tvars += defn.info.defn.type_vars or []
for tvar in tvars:
if tvar.values:
subst.append([(tvar.id, value)
for value in tvar.values])
if subst:
result = [] # type: List[Tuple[FuncItem, CallableType]]
for substitutions in itertools.product(*subst):
mapping = dict(substitutions)
expanded = cast(CallableType, expand_type(typ, mapping))
result.append((expand_func(defn, mapping), expanded))
return result
else:
return [(defn, typ)]
def check_method_override(self, defn: FuncBase) -> None:
"""Check if function definition is compatible with base classes."""
# Check against definitions in base classes.
for base in defn.info.mro[1:]:
self.check_method_or_accessor_override_for_base(defn, base)
def check_method_or_accessor_override_for_base(self, defn: FuncBase,
base: TypeInfo) -> None:
"""Check if method definition is compatible with a base class."""
if base:
name = defn.name()
if name not in ('__init__', '__new__'):
# Check method override (__init__ and __new__ are special).
self.check_method_override_for_base_with_name(defn, name, base)
if name in nodes.inplace_operator_methods:
# Figure out the name of the corresponding operator method.
method = '__' + name[3:]
# An inplace operator method such as __iadd__ might not be
# always introduced safely if a base class defined __add__.
# TODO can't come up with an example where this is
# necessary; now it's "just in case"
self.check_method_override_for_base_with_name(defn, method,
base)
def check_method_override_for_base_with_name(
self, defn: FuncBase, name: str, base: TypeInfo) -> None:
base_attr = base.names.get(name)
if base_attr:
# The name of the method is defined in the base class.
# Construct the type of the overriding method.
typ = self.method_type(defn)
# Map the overridden method type to subtype context so that
# it can be checked for compatibility.
original_type = base_attr.type
if original_type is None and isinstance(base_attr.node,
FuncDef):
original_type = self.function_type(base_attr.node)
if isinstance(original_type, FunctionLike):
original = map_type_from_supertype(
method_type(original_type),
defn.info, base)
# Check that the types are compatible.
# TODO overloaded signatures
self.check_override(typ,
cast(FunctionLike, original),
defn.name(),
name,
base.name(),
defn)
else:
assert original_type is not None
self.msg.signature_incompatible_with_supertype(
defn.name(), name, base.name(), defn)
def check_override(self, override: FunctionLike, original: FunctionLike,
name: str, name_in_super: str, supertype: str,