forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecker.py
2719 lines (2368 loc) · 119 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 fnmatch
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, Expression,
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, NewTypeExpr, PrintStmt,
LITERAL_TYPE, BreakStmt, ContinueStmt, ComparisonExpr, StarExpr,
YieldFromExpr, NamedTupleExpr, SetComprehension,
DictionaryComprehension, ComplexExpr, EllipsisExpr, TypeAliasExpr,
RefExpr, YieldExpr, BackquoteExpr, ImportFrom, ImportAll, ImportBase,
AwaitExpr,
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,
true_only, false_only
)
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_types
from mypy.treetransform import TransformVisitor
from mypy.meet import meet_simple, nearest_builtin_ancestor, is_overlapping_types
from mypy.binder import ConditionalTypeBinder
from mypy.options import Options
from mypy import experiments
T = TypeVar('T')
# 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.
"""
# 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]
# Types of type checked nodes within this specific module
module_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]
# 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
# Is this file a typeshed stub?
is_typeshed_stub = False
# Should strict Optional-related errors be suppressed in this file?
suppress_none_errors = False # TODO: Get it from options instead
options = None # type: Options
# The set of all dependencies (suppressed or not) that this module accesses, either
# directly or indirectly.
module_refs = None # type: Set[str]
def __init__(self, errors: Errors, modules: Dict[str, MypyFile]) -> None:
"""Construct a type checker.
Use errors to report type check errors.
"""
self.errors = errors
self.modules = modules
self.msg = MessageBuilder(errors, modules)
self.type_map = {}
self.module_type_map = {}
self.binder = ConditionalTypeBinder()
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.module_refs = set()
def visit_file(self, file_node: MypyFile, path: str, options: Options) -> None:
"""Type check a mypy file with the given path."""
self.options = options
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()
self.is_typeshed_stub = self.errors.is_typeshed_file(path)
self.module_type_map = {}
self.module_refs = set()
if self.options.strict_optional_whitelist is None:
self.suppress_none_errors = not self.options.show_none_errors
else:
self.suppress_none_errors = not any(fnmatch.fnmatch(path, pattern)
for pattern
in self.options.strict_optional_whitelist)
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)
del self.options
def check_second_pass(self) -> None:
"""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.errors)
self.type_context.pop()
self.store_type(node, typ)
if self.typing_mode_none():
return AnyType()
else:
return typ
def accept_loop(self, body: Node, else_body: Node = None) -> Type:
"""Repeatedly type check a loop body until the frame doesn't change.
Then check the else_body.
"""
# The outer frame accumulates the results of all iterations
with self.binder.frame_context(1) as outer_frame:
self.binder.push_loop_frame()
while True:
with self.binder.frame_context(1):
# We may skip each iteration
self.binder.options_on_return[-1].append(outer_frame)
self.accept(body)
if not self.binder.last_pop_changed:
break
self.binder.pop_loop_frame()
if else_body:
self.accept(else_body)
#
# 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)
# Here's the scoop about generators and coroutines.
#
# There are two kinds of generators: classic generators (functions
# with `yield` or `yield from` in the body) and coroutines
# (functions declared with `async def`). The latter are specified
# in PEP 492 and only available in Python >= 3.5.
#
# Classic generators can be parameterized with three types:
# - ty is the Yield type (the type of y in `yield y`)
# - tc is the type reCeived by yield (the type of c in `c = yield`).
# - tr is the Return type (the type of r in `return r`)
#
# A classic generator must define a return type that's either
# `Generator[ty, tc, tr]`, Iterator[ty], or Iterable[ty] (or
# object or Any). If tc/tr are not given, both are Void.
#
# A coroutine must define a return type corresponding to tr; the
# other two are unconstrained. The "external" return type (seen
# by the caller) is Awaitable[tr].
#
# In addition, there's the synthetic type AwaitableGenerator: it
# inherits from both Awaitable and Generator and can be used both
# in `yield from` and in `await`. This type is set automatically
# for functions decorated with `@types.coroutine` or
# `@asyncio.coroutine`. Its single parameter corresponds to tr.
#
# There are several useful methods, each taking a type t and a
# flag c indicating whether it's for a generator or coroutine:
#
# - is_generator_return_type(t, c) returns whether t is a Generator,
# Iterator, Iterable (if not c), or Awaitable (if c), or
# AwaitableGenerator (regardless of c).
# - get_generator_yield_type(t, c) returns ty.
# - get_generator_receive_type(t, c) returns tc.
# - get_generator_return_type(t, c) returns tr.
def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool:
"""Is `typ` a valid type for a generator/coroutine?
True if `typ` is a *supertype* of Generator or Awaitable.
Also true it it's *exactly* AwaitableGenerator (modulo type parameters).
"""
if is_coroutine:
# This means we're in Python 3.5 or later.
at = self.named_generic_type('typing.Awaitable', [AnyType()])
if is_subtype(at, typ):
return True
else:
gt = self.named_generic_type('typing.Generator', [AnyType(), AnyType(), AnyType()])
if is_subtype(gt, typ):
return True
return isinstance(typ, Instance) and typ.type.fullname() == 'typing.AwaitableGenerator'
def get_generator_yield_type(self, return_type: Type, is_coroutine: bool) -> Type:
"""Given the declared return type of a generator (t), return the type it yields (ty)."""
if isinstance(return_type, AnyType):
return AnyType()
elif not self.is_generator_return_type(return_type, is_coroutine):
# If the function doesn't have a proper Generator (or
# Awaitable) 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.Awaitable':
# Awaitable: ty is Any.
return AnyType()
elif return_type.args:
# AwaitableGenerator, Generator, Iterator, or Iterable; ty is args[0].
ret_type = return_type.args[0]
# TODO not best fix, better have dedicated yield token
if isinstance(ret_type, NoneTyp):
if experiments.STRICT_OPTIONAL:
return NoneTyp(is_ret_type=True)
else:
return Void()
return ret_type
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. IOW, ty is Any.
# (However, see https://github.com/python/mypy/issues/1933)
return AnyType()
def get_generator_receive_type(self, return_type: Type, is_coroutine: bool) -> Type:
"""Given a declared generator return type (t), return the type its yield receives (tc)."""
if isinstance(return_type, AnyType):
return AnyType()
elif not self.is_generator_return_type(return_type, is_coroutine):
# If the function doesn't have a proper Generator (or
# Awaitable) 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.Awaitable':
# Awaitable, AwaitableGenerator: tc is Any.
return AnyType()
elif (return_type.type.fullname() in ('typing.Generator', 'typing.AwaitableGenerator')
and len(return_type.args) >= 3):
# Generator: tc is args[1].
return return_type.args[1]
else:
# `return_type` is a supertype of Generator, so callers won't be able to send it
# values. IOW, tc is None.
if experiments.STRICT_OPTIONAL:
return NoneTyp(is_ret_type=True)
else:
return Void()
def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Type:
"""Given the declared return type of a generator (t), return the type it returns (tr)."""
if isinstance(return_type, AnyType):
return AnyType()
elif not self.is_generator_return_type(return_type, is_coroutine):
# If the function doesn't have a proper Generator (or
# Awaitable) 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.Awaitable' and len(return_type.args) == 1:
# Awaitable: tr is args[0].
return return_type.args[0]
elif (return_type.type.fullname() in ('typing.Generator', 'typing.AwaitableGenerator')
and len(return_type.args) >= 3):
# AwaitableGenerator, Generator: tr is args[2].
return return_type.args[2]
else:
# Supertype of Generator (Iterator, Iterable, object): tr is any.
return AnyType()
def check_awaitable_expr(self, t: Type, ctx: Context, msg: str) -> Type:
"""Check the argument to `await` and extract the type of value.
Also used by `async for` and `async with`.
"""
if not self.check_subtype(t, self.named_type('typing.Awaitable'), ctx,
msg, 'actual type', 'expected type'):
return AnyType()
else:
echk = self.expr_checker
method = echk.analyze_external_member_access('__await__', t, ctx)
generator = echk.check_call(method, [], [], ctx)[0]
return self.get_generator_return_type(generator, False)
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 orig_type is None:
# XXX This can be None, as happens in
# test_testcheck_TypeCheckSuite.testRedefinedFunctionInTryWithElse
self.msg.note("Internal mypy error checking function redefinition.", defn)
return None
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()
with self.binder.frame_context():
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, NoneTyp)) 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.options.warn_incomplete_stub
if self.options.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, defn.is_coroutine):
self.fail(messages.INVALID_RETURN_TYPE_FOR_GENERATOR, typ)
# Python 2 generators aren't allowed to return values.
if (self.options.python_version[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, NoneTyp, AnyType)):
self.fail(messages.INVALID_GENERATOR_RETURN_ITEM_TYPE, typ)
# Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`.
if defn.is_awaitable_coroutine:
# Update the return type to AwaitableGenerator.
# (This doesn't exist in typing.py, only in typing.pyi.)
t = typ.ret_type
c = defn.is_coroutine
ty = self.get_generator_yield_type(t, c)
tc = self.get_generator_receive_type(t, c)
tr = self.get_generator_return_type(t, c)
ret_type = self.named_generic_type('typing.AwaitableGenerator',
[ty, tc, tr, t])
typ = typ.copy_modified(ret_type=ret_type)
defn.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)
# Type check body in a new scope.
with self.binder.frame_context():
self.accept(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:
if isinstance(base_attr.node, FuncDef):
original_type = self.function_type(base_attr.node)
elif isinstance(base_attr.node, Decorator):
original_type = self.function_type(base_attr.node.func)
else:
assert False, str(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:
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,
node: Context) -> None:
"""Check a method override with given signatures.
Arguments:
override: The signature of the overriding method.
original: The signature of the original supertype method.
name: The name of the subtype. This and the next argument are
only used for generating error messages.
supertype: The name of the supertype.
"""
# Use boolean variable to clarify code.
fail = False
if not is_subtype(override, original):
fail = True
elif (not isinstance(original, Overloaded) and
isinstance(override, Overloaded) and
name in nodes.reverse_op_methods.keys()):
# Operator method overrides cannot introduce overloading, as
# this could be unsafe with reverse operator methods.
fail = True
if fail:
emitted_msg = False
if (isinstance(override, CallableType) and
isinstance(original, CallableType) and
len(override.arg_types) == len(original.arg_types) and
override.min_args == original.min_args):
# Give more detailed messages for the common case of both
# signatures having the same number of arguments and no
# overloads.
# override might have its own generic function type
# variables. If an argument or return type of override
# does not have the correct subtyping relationship
# with the original type even after these variables
# are erased, then it is definitely an incompatiblity.
override_ids = override.type_var_ids()
def erase_override(t: Type) -> Type:
return erase_typevars(t, ids_to_erase=override_ids)
for i in range(len(override.arg_types)):
if not is_subtype(original.arg_types[i],
erase_override(override.arg_types[i])):
self.msg.argument_incompatible_with_supertype(
i + 1, name, name_in_super, supertype, node)
emitted_msg = True
if not is_subtype(erase_override(override.ret_type),
original.ret_type):
self.msg.return_type_incompatible_with_supertype(
name, name_in_super, supertype, node)
emitted_msg = True
if not emitted_msg:
# Fall back to generic incompatibility message.
self.msg.signature_incompatible_with_supertype(
name, name_in_super, supertype, node)
def visit_class_def(self, defn: ClassDef) -> Type:
"""Type check a class definition."""
typ = defn.info
self.errors.push_type(defn.name)
self.enter_partial_types()
old_binder = self.binder
self.binder = ConditionalTypeBinder()
with self.binder.frame_context():
self.accept(defn.defs)
self.binder = old_binder
if not defn.has_incompatible_baseclass:
# Otherwise we've already found errors; more errors are not useful
self.check_multiple_inheritance(typ)
self.leave_partial_types()
self.errors.pop_type()
def check_multiple_inheritance(self, typ: TypeInfo) -> None:
"""Check for multiple inheritance related errors."""
if len(typ.bases) <= 1:
# No multiple inheritance.
return
# Verify that inherited attributes are compatible.
mro = typ.mro[1:]
for i, base in enumerate(mro):
for name in base.names:
for base2 in mro[i + 1:]:
# We only need to check compatibility of attributes from classes not
# in a subclass relationship. For subclasses, normal (single inheritance)
# checks suffice (these are implemented elsewhere).
if name in base2.names and base2 not in base.mro:
self.check_compatibility(name, base, base2, typ)
# Verify that base class layouts are compatible.
builtin_bases = [nearest_builtin_ancestor(base.type)
for base in typ.bases]
for base1 in builtin_bases:
for base2 in builtin_bases:
if not (base1 in base2.mro or base2 in base1.mro):
self.fail(messages.INSTANCE_LAYOUT_CONFLICT, typ)
def check_compatibility(self, name: str, base1: TypeInfo,
base2: TypeInfo, ctx: Context) -> None:
"""Check if attribute name in base1 is compatible with base2 in multiple inheritance.
Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have
a direct subclass relationship (i.e., the compatibility requirement only derives from
multiple inheritance).
"""
if name == '__init__':
# __init__ can be incompatible -- it's a special case.
return
first = base1[name]
second = base2[name]
first_type = first.type
if first_type is None and isinstance(first.node, FuncDef):
first_type = self.function_type(first.node)
second_type = second.type
if second_type is None and isinstance(second.node, FuncDef):
second_type = self.function_type(second.node)
# TODO: What if some classes are generic?
if (isinstance(first_type, FunctionLike) and
isinstance(second_type, FunctionLike)):
# Method override
first_sig = method_type(first_type)
second_sig = method_type(second_type)
ok = is_subtype(first_sig, second_sig)
elif first_type and second_type:
ok = is_equivalent(first_type, second_type)
else:
if first_type is None:
self.msg.cannot_determine_type_in_base(name, base1.name(), ctx)
if second_type is None:
self.msg.cannot_determine_type_in_base(name, base2.name(), ctx)
ok = True
if not ok:
self.msg.base_class_definitions_incompatible(name, base1, base2,
ctx)
def visit_import_from(self, node: ImportFrom) -> Type:
self.check_import(node)
def visit_import_all(self, node: ImportAll) -> Type: