-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
semanal.py
5146 lines (4595 loc) · 228 KB
/
semanal.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
"""The semantic analyzer.
Bind names to definitions and do various other simple consistency
checks. Populate symbol tables. The semantic analyzer also detects
special forms which reuse generic syntax such as NamedTuple and
cast(). Multiple analysis iterations may be needed to analyze forward
references and import cycles. Each iteration "fills in" additional
bindings and references until everything has been bound.
For example, consider this program:
x = 1
y = x
Here semantic analysis would detect that the assignment 'x = 1'
defines a new variable, the type of which is to be inferred (in a
later pass; type inference or type checking is not part of semantic
analysis). Also, it would bind both references to 'x' to the same
module-level variable (Var) node. The second assignment would also
be analyzed, and the type of 'y' marked as being inferred.
Semantic analysis of types is implemented in typeanal.py.
See semanal_main.py for the top-level logic.
Some important properties:
* After semantic analysis is complete, no PlaceholderNode and
PlaceholderType instances should remain. During semantic analysis,
if we encounter one of these, the current target should be deferred.
* A TypeInfo is only created once we know certain basic information about
a type, such as the MRO, existence of a Tuple base class (e.g., for named
tuples), and whether we have a TypedDict. We use a temporary
PlaceholderNode node in the symbol table if some such information is
missing.
* For assignments, we only add a non-placeholder symbol table entry once
we know the sort of thing being defined (variable, NamedTuple, type alias,
etc.).
* Every part of the analysis step must support multiple iterations over
the same AST nodes, and each iteration must be able to fill in arbitrary
things that were missing or incomplete in previous iterations.
* Changes performed by the analysis need to be reversible, since mypy
daemon strips and reuses existing ASTs (to improve performance and/or
reduce memory use).
"""
from contextlib import contextmanager
from typing import (
List, Dict, Set, Tuple, cast, TypeVar, Union, Optional, Callable, Iterator, Iterable
)
from typing_extensions import Final
from mypy.nodes import (
MypyFile, TypeInfo, Node, AssignmentStmt, FuncDef, OverloadedFuncDef,
ClassDef, Var, GDEF, FuncItem, Import, Expression, Lvalue,
ImportFrom, ImportAll, Block, LDEF, NameExpr, MemberExpr,
IndexExpr, TupleExpr, ListExpr, ExpressionStmt, ReturnStmt,
RaiseStmt, AssertStmt, OperatorAssignmentStmt, WhileStmt,
ForStmt, BreakStmt, ContinueStmt, IfStmt, TryStmt, WithStmt, DelStmt,
GlobalDecl, SuperExpr, DictExpr, CallExpr, RefExpr, OpExpr, UnaryExpr,
SliceExpr, CastExpr, RevealExpr, TypeApplication, Context, SymbolTable,
SymbolTableNode, ListComprehension, GeneratorExpr,
LambdaExpr, MDEF, Decorator, SetExpr, TypeVarExpr,
StrExpr, BytesExpr, PrintStmt, ConditionalExpr, PromoteExpr,
ComparisonExpr, StarExpr, ARG_POS, ARG_NAMED, type_aliases,
YieldFromExpr, NamedTupleExpr, NonlocalDecl, SymbolNode,
SetComprehension, DictionaryComprehension, TypeAlias, TypeAliasExpr,
YieldExpr, ExecStmt, BackquoteExpr, ImportBase, AwaitExpr,
IntExpr, FloatExpr, UnicodeExpr, TempNode, OverloadPart,
PlaceholderNode, COVARIANT, CONTRAVARIANT, INVARIANT,
get_nongen_builtins, get_member_expr_fullname, REVEAL_TYPE,
REVEAL_LOCALS, is_final_node, TypedDictExpr, type_aliases_source_versions,
EnumCallExpr, RUNTIME_PROTOCOL_DECOS, FakeExpression, Statement, AssignmentExpr,
ParamSpecExpr
)
from mypy.tvar_scope import TypeVarLikeScope
from mypy.typevars import fill_typevars
from mypy.visitor import NodeVisitor
from mypy.errors import Errors, report_internal_error
from mypy.messages import (
best_matches, MessageBuilder, pretty_seq, SUGGESTED_TEST_FIXTURES, TYPES_FOR_UNIMPORTED_HINTS
)
from mypy.errorcodes import ErrorCode
from mypy import message_registry, errorcodes as codes
from mypy.types import (
FunctionLike, UnboundType, TypeVarDef, TupleType, UnionType, StarType,
CallableType, Overloaded, Instance, Type, AnyType, LiteralType, LiteralValue,
TypeTranslator, TypeOfAny, TypeType, NoneType, PlaceholderType, TPDICT_NAMES, ProperType,
get_proper_type, get_proper_types, TypeAliasType)
from mypy.typeops import function_type
from mypy.type_visitor import TypeQuery
from mypy.nodes import implicit_module_attrs
from mypy.typeanal import (
TypeAnalyser, analyze_type_alias, no_subscript_builtin_alias,
TypeVarLikeQuery, TypeVarLikeList, remove_dups, has_any_from_unimported_type,
check_for_explicit_any, type_constructors, fix_instance_types
)
from mypy.exprtotype import expr_to_unanalyzed_type, TypeTranslationError
from mypy.options import Options
from mypy.plugin import (
Plugin, ClassDefContext, SemanticAnalyzerPluginInterface,
DynamicClassDefContext
)
from mypy.util import correct_relative_import, unmangle, module_prefix, is_typeshed_file
from mypy.scope import Scope
from mypy.semanal_shared import (
SemanticAnalyzerInterface, set_callable_name, calculate_tuple_fallback, PRIORITY_FALLBACKS
)
from mypy.semanal_namedtuple import NamedTupleAnalyzer
from mypy.semanal_typeddict import TypedDictAnalyzer
from mypy.semanal_enum import EnumCallAnalyzer
from mypy.semanal_newtype import NewTypeAnalyzer
from mypy.reachability import (
infer_reachability_of_if_statement, infer_condition_value, ALWAYS_FALSE, ALWAYS_TRUE,
MYPY_TRUE, MYPY_FALSE
)
from mypy.mro import calculate_mro, MroError
T = TypeVar('T')
FUTURE_IMPORTS = {
'__future__.nested_scopes': 'nested_scopes',
'__future__.generators': 'generators',
'__future__.division': 'division',
'__future__.absolute_import': 'absolute_import',
'__future__.with_statement': 'with_statement',
'__future__.print_function': 'print_function',
'__future__.unicode_literals': 'unicode_literals',
'__future__.barry_as_FLUFL': 'barry_as_FLUFL',
'__future__.generator_stop': 'generator_stop',
'__future__.annotations': 'annotations',
} # type: Final
# Special cased built-in classes that are needed for basic functionality and need to be
# available very early on.
CORE_BUILTIN_CLASSES = ['object', 'bool', 'function'] # type: Final
# Used for tracking incomplete references
Tag = int
class SemanticAnalyzer(NodeVisitor[None],
SemanticAnalyzerInterface,
SemanticAnalyzerPluginInterface):
"""Semantically analyze parsed mypy files.
The analyzer binds names and does various consistency checks for an
AST. Note that type checking is performed as a separate pass.
"""
# Module name space
modules = None # type: Dict[str, MypyFile]
# Global name space for current module
globals = None # type: SymbolTable
# Names declared using "global" (separate set for each scope)
global_decls = None # type: List[Set[str]]
# Names declated using "nonlocal" (separate set for each scope)
nonlocal_decls = None # type: List[Set[str]]
# Local names of function scopes; None for non-function scopes.
locals = None # type: List[Optional[SymbolTable]]
# Whether each scope is a comprehension scope.
is_comprehension_stack = None # type: List[bool]
# Nested block depths of scopes
block_depth = None # type: List[int]
# TypeInfo of directly enclosing class (or None)
type = None # type: Optional[TypeInfo]
# Stack of outer classes (the second tuple item contains tvars).
type_stack = None # type: List[Optional[TypeInfo]]
# Type variables bound by the current scope, be it class or function
tvar_scope = None # type: TypeVarLikeScope
# Per-module options
options = None # type: Options
# Stack of functions being analyzed
function_stack = None # type: List[FuncItem]
# Set to True if semantic analysis defines a name, or replaces a
# placeholder definition. If some iteration makes no progress,
# there can be at most one additional final iteration (see below).
progress = False
deferred = False # Set to true if another analysis pass is needed
incomplete = False # Set to true if current module namespace is missing things
# Is this the final iteration of semantic analysis (where we report
# unbound names due to cyclic definitions and should not defer)?
_final_iteration = False
# These names couldn't be added to the symbol table due to incomplete deps.
# Note that missing names are per module, _not_ per namespace. This means that e.g.
# a missing name at global scope will block adding same name at a class scope.
# This should not affect correctness and is purely a performance issue,
# since it can cause unnecessary deferrals. These are represented as
# PlaceholderNodes in the symbol table. We use this to ensure that the first
# definition takes precedence even if it's incomplete.
#
# Note that a star import adds a special name '*' to the set, this blocks
# adding _any_ names in the current file.
missing_names = None # type: List[Set[str]]
# Callbacks that will be called after semantic analysis to tweak things.
patches = None # type: List[Tuple[int, Callable[[], None]]]
loop_depth = 0 # Depth of breakable loops
cur_mod_id = '' # Current module id (or None) (phase 2)
_is_stub_file = False # Are we analyzing a stub file?
_is_typeshed_stub_file = False # Are we analyzing a typeshed stub file?
imports = None # type: Set[str] # Imported modules (during phase 2 analysis)
# Note: some imports (and therefore dependencies) might
# not be found in phase 1, for example due to * imports.
errors = None # type: Errors # Keeps track of generated errors
plugin = None # type: Plugin # Mypy plugin for special casing of library features
statement = None # type: Optional[Statement] # Statement/definition being analyzed
future_import_flags = None # type: Set[str]
# Mapping from 'async def' function definitions to their return type wrapped as a
# 'Coroutine[Any, Any, T]'. Used to keep track of whether a function definition's
# return type has already been wrapped, by checking if the function definition's
# type is stored in this mapping and that it still matches.
wrapped_coro_return_types = {} # type: Dict[FuncDef, Type]
def __init__(self,
modules: Dict[str, MypyFile],
missing_modules: Set[str],
incomplete_namespaces: Set[str],
errors: Errors,
plugin: Plugin) -> None:
"""Construct semantic analyzer.
We reuse the same semantic analyzer instance across multiple modules.
Args:
modules: Global modules dictionary
missing_modules: Modules that could not be imported encountered so far
incomplete_namespaces: Namespaces that are being populated during semantic analysis
(can contain modules and classes within the current SCC; mutated by the caller)
errors: Report analysis errors using this instance
"""
self.locals = [None]
self.is_comprehension_stack = [False]
# Saved namespaces from previous iteration. Every top-level function/method body is
# analyzed in several iterations until all names are resolved. We need to save
# the local namespaces for the top level function and all nested functions between
# these iterations. See also semanal_main.process_top_level_function().
self.saved_locals = {} \
# type: Dict[Union[FuncItem, GeneratorExpr, DictionaryComprehension], SymbolTable]
self.imports = set()
self.type = None
self.type_stack = []
self.tvar_scope = TypeVarLikeScope()
self.function_stack = []
self.block_depth = [0]
self.loop_depth = 0
self.errors = errors
self.modules = modules
self.msg = MessageBuilder(errors, modules)
self.missing_modules = missing_modules
self.missing_names = [set()]
# These namespaces are still in process of being populated. If we encounter a
# missing name in these namespaces, we need to defer the current analysis target,
# since it's possible that the name will be there once the namespace is complete.
self.incomplete_namespaces = incomplete_namespaces
self.all_exports = [] # type: List[str]
# Map from module id to list of explicitly exported names (i.e. names in __all__).
self.export_map = {} # type: Dict[str, List[str]]
self.plugin = plugin
# If True, process function definitions. If False, don't. This is used
# for processing module top levels in fine-grained incremental mode.
self.recurse_into_functions = True
self.scope = Scope()
# Trace line numbers for every file where deferral happened during analysis of
# current SCC or top-level function.
self.deferral_debug_context = [] # type: List[Tuple[str, int]]
self.future_import_flags = set() # type: Set[str]
# mypyc doesn't properly handle implementing an abstractproperty
# with a regular attribute so we make them properties
@property
def is_stub_file(self) -> bool:
return self._is_stub_file
@property
def is_typeshed_stub_file(self) -> bool:
return self._is_typeshed_stub_file
@property
def final_iteration(self) -> bool:
return self._final_iteration
#
# Preparing module (performed before semantic analysis)
#
def prepare_file(self, file_node: MypyFile) -> None:
"""Prepare a freshly parsed file for semantic analysis."""
if 'builtins' in self.modules:
file_node.names['__builtins__'] = SymbolTableNode(GDEF,
self.modules['builtins'])
if file_node.fullname == 'builtins':
self.prepare_builtins_namespace(file_node)
if file_node.fullname == 'typing':
self.prepare_typing_namespace(file_node)
def prepare_typing_namespace(self, file_node: MypyFile) -> None:
"""Remove dummy alias definitions such as List = TypeAlias(object) from typing.
They will be replaced with real aliases when corresponding targets are ready.
"""
# This is all pretty unfortunate. typeshed now has a
# sys.version_info check for OrderedDict, and we shouldn't
# take it out, because it is correct and a typechecker should
# use that as a source of truth. But instead we rummage
# through IfStmts to remove the info first. (I tried to
# remove this whole machinery and ran into issues with the
# builtins/typing import cycle.)
def helper(defs: List[Statement]) -> None:
for stmt in defs.copy():
if isinstance(stmt, IfStmt):
for body in stmt.body:
helper(body.body)
if stmt.else_body:
helper(stmt.else_body.body)
if (isinstance(stmt, AssignmentStmt) and len(stmt.lvalues) == 1 and
isinstance(stmt.lvalues[0], NameExpr)):
# Assignment to a simple name, remove it if it is a dummy alias.
if 'typing.' + stmt.lvalues[0].name in type_aliases:
defs.remove(stmt)
helper(file_node.defs)
def prepare_builtins_namespace(self, file_node: MypyFile) -> None:
"""Add certain special-cased definitions to the builtins module.
Some definitions are too special or fundamental to be processed
normally from the AST.
"""
names = file_node.names
# Add empty definition for core built-in classes, since they are required for basic
# operation. These will be completed later on.
for name in CORE_BUILTIN_CLASSES:
cdef = ClassDef(name, Block([])) # Dummy ClassDef, will be replaced later
info = TypeInfo(SymbolTable(), cdef, 'builtins')
info._fullname = 'builtins.%s' % name
names[name] = SymbolTableNode(GDEF, info)
bool_info = names['bool'].node
assert isinstance(bool_info, TypeInfo)
bool_type = Instance(bool_info, [])
special_var_types = [
('None', NoneType()),
# reveal_type is a mypy-only function that gives an error with
# the type of its arg.
('reveal_type', AnyType(TypeOfAny.special_form)),
# reveal_locals is a mypy-only function that gives an error with the types of
# locals
('reveal_locals', AnyType(TypeOfAny.special_form)),
('True', bool_type),
('False', bool_type),
('__debug__', bool_type),
] # type: List[Tuple[str, Type]]
for name, typ in special_var_types:
v = Var(name, typ)
v._fullname = 'builtins.%s' % name
file_node.names[name] = SymbolTableNode(GDEF, v)
#
# Analyzing a target
#
def refresh_partial(self,
node: Union[MypyFile, FuncDef, OverloadedFuncDef],
patches: List[Tuple[int, Callable[[], None]]],
final_iteration: bool,
file_node: MypyFile,
options: Options,
active_type: Optional[TypeInfo] = None) -> None:
"""Refresh a stale target in fine-grained incremental mode."""
self.patches = patches
self.deferred = False
self.incomplete = False
self._final_iteration = final_iteration
self.missing_names[-1] = set()
with self.file_context(file_node, options, active_type):
if isinstance(node, MypyFile):
self.refresh_top_level(node)
else:
self.recurse_into_functions = True
self.accept(node)
del self.patches
def refresh_top_level(self, file_node: MypyFile) -> None:
"""Reanalyze a stale module top-level in fine-grained incremental mode."""
self.recurse_into_functions = False
self.add_implicit_module_attrs(file_node)
for d in file_node.defs:
self.accept(d)
if file_node.fullname == 'typing':
self.add_builtin_aliases(file_node)
self.adjust_public_exports()
self.export_map[self.cur_mod_id] = self.all_exports
self.all_exports = []
def add_implicit_module_attrs(self, file_node: MypyFile) -> None:
"""Manually add implicit definitions of module '__name__' etc."""
for name, t in implicit_module_attrs.items():
# unicode docstrings should be accepted in Python 2
if name == '__doc__':
if self.options.python_version >= (3, 0):
typ = UnboundType('__builtins__.str') # type: Type
else:
typ = UnionType([UnboundType('__builtins__.str'),
UnboundType('__builtins__.unicode')])
else:
assert t is not None, 'type should be specified for {}'.format(name)
typ = UnboundType(t)
existing = file_node.names.get(name)
if existing is not None and not isinstance(existing.node, PlaceholderNode):
# Already exists.
continue
an_type = self.anal_type(typ)
if an_type:
var = Var(name, an_type)
var._fullname = self.qualified_name(name)
var.is_ready = True
self.add_symbol(name, var, dummy_context())
else:
self.add_symbol(name,
PlaceholderNode(self.qualified_name(name), file_node, -1),
dummy_context())
def add_builtin_aliases(self, tree: MypyFile) -> None:
"""Add builtin type aliases to typing module.
For historical reasons, the aliases like `List = list` are not defined
in typeshed stubs for typing module. Instead we need to manually add the
corresponding nodes on the fly. We explicitly mark these aliases as normalized,
so that a user can write `typing.List[int]`.
"""
assert tree.fullname == 'typing'
for alias, target_name in type_aliases.items():
if type_aliases_source_versions[alias] > self.options.python_version:
# This alias is not available on this Python version.
continue
name = alias.split('.')[-1]
if name in tree.names and not isinstance(tree.names[name].node, PlaceholderNode):
continue
tag = self.track_incomplete_refs()
n = self.lookup_fully_qualified_or_none(target_name)
if n:
if isinstance(n.node, PlaceholderNode):
self.mark_incomplete(name, tree)
else:
# Found built-in class target. Create alias.
target = self.named_type_or_none(target_name, [])
assert target is not None
# Transform List to List[Any], etc.
fix_instance_types(target, self.fail, self.note, self.options.python_version)
alias_node = TypeAlias(target, alias,
line=-1, column=-1, # there is no context
no_args=True, normalized=True)
self.add_symbol(name, alias_node, tree)
elif self.found_incomplete_ref(tag):
# Built-in class target may not ready yet -- defer.
self.mark_incomplete(name, tree)
else:
# Test fixtures may be missing some builtin classes, which is okay.
# Kill the placeholder if there is one.
if name in tree.names:
assert isinstance(tree.names[name].node, PlaceholderNode)
del tree.names[name]
def adjust_public_exports(self) -> None:
"""Adjust the module visibility of globals due to __all__."""
if '__all__' in self.globals:
for name, g in self.globals.items():
# Being included in __all__ explicitly exports and makes public.
if name in self.all_exports:
g.module_public = True
g.module_hidden = False
# But when __all__ is defined, and a symbol is not included in it,
# it cannot be public.
else:
g.module_public = False
@contextmanager
def file_context(self,
file_node: MypyFile,
options: Options,
active_type: Optional[TypeInfo] = None) -> Iterator[None]:
"""Configure analyzer for analyzing targets within a file/class.
Args:
file_node: target file
options: options specific to the file
active_type: must be the surrounding class to analyze method targets
"""
scope = self.scope
self.options = options
self.errors.set_file(file_node.path, file_node.fullname, scope=scope)
self.cur_mod_node = file_node
self.cur_mod_id = file_node.fullname
scope.enter_file(self.cur_mod_id)
self._is_stub_file = file_node.path.lower().endswith('.pyi')
self._is_typeshed_stub_file = is_typeshed_file(file_node.path)
self.globals = file_node.names
self.tvar_scope = TypeVarLikeScope()
self.named_tuple_analyzer = NamedTupleAnalyzer(options, self)
self.typed_dict_analyzer = TypedDictAnalyzer(options, self, self.msg)
self.enum_call_analyzer = EnumCallAnalyzer(options, self)
self.newtype_analyzer = NewTypeAnalyzer(options, self, self.msg)
# Counter that keeps track of references to undefined things potentially caused by
# incomplete namespaces.
self.num_incomplete_refs = 0
if active_type:
scope.enter_class(active_type)
self.enter_class(active_type.defn.info)
for tvar in active_type.defn.type_vars:
self.tvar_scope.bind_existing(tvar)
yield
if active_type:
scope.leave()
self.leave_class()
self.type = None
scope.leave()
del self.options
#
# Functions
#
def visit_func_def(self, defn: FuncDef) -> None:
self.statement = defn
# Visit default values because they may contain assignment expressions.
for arg in defn.arguments:
if arg.initializer:
arg.initializer.accept(self)
defn.is_conditional = self.block_depth[-1] > 0
# Set full names even for those definitions that aren't added
# to a symbol table. For example, for overload items.
defn._fullname = self.qualified_name(defn.name)
# We don't add module top-level functions to symbol tables
# when we analyze their bodies in the second phase on analysis,
# since they were added in the first phase. Nested functions
# get always added, since they aren't separate targets.
if not self.recurse_into_functions or len(self.function_stack) > 0:
if not defn.is_decorated and not defn.is_overload:
self.add_function_to_symbol_table(defn)
if not self.recurse_into_functions:
return
with self.scope.function_scope(defn):
self.analyze_func_def(defn)
def analyze_func_def(self, defn: FuncDef) -> None:
self.function_stack.append(defn)
if defn.type:
assert isinstance(defn.type, CallableType)
self.update_function_type_variables(defn.type, defn)
self.function_stack.pop()
if self.is_class_scope():
# Method definition
assert self.type is not None
defn.info = self.type
if defn.type is not None and defn.name in ('__init__', '__init_subclass__'):
assert isinstance(defn.type, CallableType)
if isinstance(get_proper_type(defn.type.ret_type), AnyType):
defn.type = defn.type.copy_modified(ret_type=NoneType())
self.prepare_method_signature(defn, self.type)
# Analyze function signature
with self.tvar_scope_frame(self.tvar_scope.method_frame()):
if defn.type:
self.check_classvar_in_signature(defn.type)
assert isinstance(defn.type, CallableType)
# Signature must be analyzed in the surrounding scope so that
# class-level imported names and type variables are in scope.
analyzer = self.type_analyzer()
tag = self.track_incomplete_refs()
result = analyzer.visit_callable_type(defn.type, nested=False)
# Don't store not ready types (including placeholders).
if self.found_incomplete_ref(tag) or has_placeholder(result):
self.defer(defn)
return
assert isinstance(result, ProperType)
defn.type = result
self.add_type_alias_deps(analyzer.aliases_used)
self.check_function_signature(defn)
if isinstance(defn, FuncDef):
assert isinstance(defn.type, CallableType)
defn.type = set_callable_name(defn.type, defn)
self.analyze_arg_initializers(defn)
self.analyze_function_body(defn)
if (defn.is_coroutine and
isinstance(defn.type, CallableType) and
self.wrapped_coro_return_types.get(defn) != defn.type):
if defn.is_async_generator:
# Async generator types are handled elsewhere
pass
else:
# A coroutine defined as `async def foo(...) -> T: ...`
# has external return type `Coroutine[Any, Any, T]`.
any_type = AnyType(TypeOfAny.special_form)
ret_type = self.named_type_or_none('typing.Coroutine',
[any_type, any_type, defn.type.ret_type])
assert ret_type is not None, "Internal error: typing.Coroutine not found"
defn.type = defn.type.copy_modified(ret_type=ret_type)
self.wrapped_coro_return_types[defn] = defn.type
def prepare_method_signature(self, func: FuncDef, info: TypeInfo) -> None:
"""Check basic signature validity and tweak annotation of self/cls argument."""
# Only non-static methods are special.
functype = func.type
if not func.is_static:
if func.name in ['__init_subclass__', '__class_getitem__']:
func.is_class = True
if not func.arguments:
self.fail('Method must have at least one argument', func)
elif isinstance(functype, CallableType):
self_type = get_proper_type(functype.arg_types[0])
if isinstance(self_type, AnyType):
leading_type = fill_typevars(info) # type: Type
if func.is_class or func.name == '__new__':
leading_type = self.class_type(leading_type)
func.type = replace_implicit_first_type(functype, leading_type)
def set_original_def(self, previous: Optional[Node], new: Union[FuncDef, Decorator]) -> bool:
"""If 'new' conditionally redefine 'previous', set 'previous' as original
We reject straight redefinitions of functions, as they are usually
a programming error. For example:
def f(): ...
def f(): ... # Error: 'f' redefined
"""
if isinstance(new, Decorator):
new = new.func
if isinstance(previous, (FuncDef, Var, Decorator)) and new.is_conditional:
new.original_def = previous
return True
else:
return False
def update_function_type_variables(self, fun_type: CallableType, defn: FuncItem) -> None:
"""Make any type variables in the signature of defn explicit.
Update the signature of defn to contain type variable definitions
if defn is generic.
"""
with self.tvar_scope_frame(self.tvar_scope.method_frame()):
a = self.type_analyzer()
fun_type.variables = a.bind_function_type_variables(fun_type, defn)
def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
self.statement = defn
self.add_function_to_symbol_table(defn)
if not self.recurse_into_functions:
return
# NB: Since _visit_overloaded_func_def will call accept on the
# underlying FuncDefs, the function might get entered twice.
# This is fine, though, because only the outermost function is
# used to compute targets.
with self.scope.function_scope(defn):
self.analyze_overloaded_func_def(defn)
def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
# OverloadedFuncDef refers to any legitimate situation where you have
# more than one declaration for the same function in a row. This occurs
# with a @property with a setter or a deleter, and for a classic
# @overload.
defn._fullname = self.qualified_name(defn.name)
# TODO: avoid modifying items.
defn.items = defn.unanalyzed_items.copy()
first_item = defn.items[0]
first_item.is_overload = True
first_item.accept(self)
if isinstance(first_item, Decorator) and first_item.func.is_property:
# This is a property.
first_item.func.is_overload = True
self.analyze_property_with_multi_part_definition(defn)
typ = function_type(first_item.func, self.builtin_type('builtins.function'))
assert isinstance(typ, CallableType)
types = [typ]
else:
# This is an a normal overload. Find the item signatures, the
# implementation (if outside a stub), and any missing @overload
# decorators.
types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn)
defn.impl = impl
if non_overload_indexes:
self.handle_missing_overload_decorators(defn, non_overload_indexes,
some_overload_decorators=len(types) > 0)
# If we found an implementation, remove it from the overload item list,
# as it's special.
if impl is not None:
assert impl is defn.items[-1]
defn.items = defn.items[:-1]
elif not non_overload_indexes:
self.handle_missing_overload_implementation(defn)
if types:
defn.type = Overloaded(types)
defn.type.line = defn.line
if not defn.items:
# It was not a real overload after all, but function redefinition. We've
# visited the redefinition(s) already.
if not defn.impl:
# For really broken overloads with no items and no implementation we need to keep
# at least one item to hold basic information like function name.
defn.impl = defn.unanalyzed_items[-1]
return
# We know this is an overload def. Infer properties and perform some checks.
self.process_final_in_overload(defn)
self.process_static_or_class_method_in_overload(defn)
def analyze_overload_sigs_and_impl(
self,
defn: OverloadedFuncDef) -> Tuple[List[CallableType],
Optional[OverloadPart],
List[int]]:
"""Find overload signatures, the implementation, and items with missing @overload.
Assume that the first was already analyzed. As a side effect:
analyzes remaining items and updates 'is_overload' flags.
"""
types = []
non_overload_indexes = []
impl = None # type: Optional[OverloadPart]
for i, item in enumerate(defn.items):
if i != 0:
# Assume that the first item was already visited
item.is_overload = True
item.accept(self)
# TODO: support decorated overloaded functions properly
if isinstance(item, Decorator):
callable = function_type(item.func, self.builtin_type('builtins.function'))
assert isinstance(callable, CallableType)
if not any(refers_to_fullname(dec, 'typing.overload')
for dec in item.decorators):
if i == len(defn.items) - 1 and not self.is_stub_file:
# Last item outside a stub is impl
impl = item
else:
# Oops it wasn't an overload after all. A clear error
# will vary based on where in the list it is, record
# that.
non_overload_indexes.append(i)
else:
item.func.is_overload = True
types.append(callable)
elif isinstance(item, FuncDef):
if i == len(defn.items) - 1 and not self.is_stub_file:
impl = item
else:
non_overload_indexes.append(i)
return types, impl, non_overload_indexes
def handle_missing_overload_decorators(self,
defn: OverloadedFuncDef,
non_overload_indexes: List[int],
some_overload_decorators: bool) -> None:
"""Generate errors for overload items without @overload.
Side effect: remote non-overload items.
"""
if some_overload_decorators:
# Some of them were overloads, but not all.
for idx in non_overload_indexes:
if self.is_stub_file:
self.fail("An implementation for an overloaded function "
"is not allowed in a stub file", defn.items[idx])
else:
self.fail("The implementation for an overloaded function "
"must come last", defn.items[idx])
else:
for idx in non_overload_indexes[1:]:
self.name_already_defined(defn.name, defn.items[idx], defn.items[0])
if defn.impl:
self.name_already_defined(defn.name, defn.impl, defn.items[0])
# Remove the non-overloads
for idx in reversed(non_overload_indexes):
del defn.items[idx]
def handle_missing_overload_implementation(self, defn: OverloadedFuncDef) -> None:
"""Generate error about missing overload implementation (only if needed)."""
if not self.is_stub_file:
if self.type and self.type.is_protocol and not self.is_func_scope():
# An overloded protocol method doesn't need an implementation.
for item in defn.items:
if isinstance(item, Decorator):
item.func.is_abstract = True
else:
item.is_abstract = True
else:
self.fail(
"An overloaded function outside a stub file must have an implementation",
defn)
def process_final_in_overload(self, defn: OverloadedFuncDef) -> None:
"""Detect the @final status of an overloaded function (and perform checks)."""
# If the implementation is marked as @final (or the first overload in
# stubs), then the whole overloaded definition if @final.
if any(item.is_final for item in defn.items):
# We anyway mark it as final because it was probably the intention.
defn.is_final = True
# Only show the error once per overload
bad_final = next(ov for ov in defn.items if ov.is_final)
if not self.is_stub_file:
self.fail("@final should be applied only to overload implementation",
bad_final)
elif any(item.is_final for item in defn.items[1:]):
bad_final = next(ov for ov in defn.items[1:] if ov.is_final)
self.fail("In a stub file @final must be applied only to the first overload",
bad_final)
if defn.impl is not None and defn.impl.is_final:
defn.is_final = True
def process_static_or_class_method_in_overload(self, defn: OverloadedFuncDef) -> None:
class_status = []
static_status = []
for item in defn.items:
if isinstance(item, Decorator):
inner = item.func
elif isinstance(item, FuncDef):
inner = item
else:
assert False, "The 'item' variable is an unexpected type: {}".format(type(item))
class_status.append(inner.is_class)
static_status.append(inner.is_static)
if defn.impl is not None:
if isinstance(defn.impl, Decorator):
inner = defn.impl.func
elif isinstance(defn.impl, FuncDef):
inner = defn.impl
else:
assert False, "Unexpected impl type: {}".format(type(defn.impl))
class_status.append(inner.is_class)
static_status.append(inner.is_static)
if len(set(class_status)) != 1:
self.msg.overload_inconsistently_applies_decorator('classmethod', defn)
elif len(set(static_status)) != 1:
self.msg.overload_inconsistently_applies_decorator('staticmethod', defn)
else:
defn.is_class = class_status[0]
defn.is_static = static_status[0]
def analyze_property_with_multi_part_definition(self, defn: OverloadedFuncDef) -> None:
"""Analyze a property defined using multiple methods (e.g., using @x.setter).
Assume that the first method (@property) has already been analyzed.
"""
defn.is_property = True
items = defn.items
first_item = cast(Decorator, defn.items[0])
deleted_items = []
for i, item in enumerate(items[1:]):
if isinstance(item, Decorator):
if len(item.decorators) == 1:
node = item.decorators[0]
if isinstance(node, MemberExpr):
if node.name == 'setter':
# The first item represents the entire property.
first_item.var.is_settable_property = True
# Get abstractness from the original definition.
item.func.is_abstract = first_item.func.is_abstract
else:
self.fail("Decorated property not supported", item)
item.func.accept(self)
else:
self.fail('Unexpected definition for property "{}"'.format(first_item.func.name),
item)
deleted_items.append(i + 1)
for i in reversed(deleted_items):
del items[i]
def add_function_to_symbol_table(self, func: Union[FuncDef, OverloadedFuncDef]) -> None:
if self.is_class_scope():
assert self.type is not None
func.info = self.type
func._fullname = self.qualified_name(func.name)
self.add_symbol(func.name, func, func)
def analyze_arg_initializers(self, defn: FuncItem) -> None:
with self.tvar_scope_frame(self.tvar_scope.method_frame()):
# Analyze default arguments
for arg in defn.arguments:
if arg.initializer:
arg.initializer.accept(self)
def analyze_function_body(self, defn: FuncItem) -> None:
is_method = self.is_class_scope()
with self.tvar_scope_frame(self.tvar_scope.method_frame()):
# Bind the type variables again to visit the body.
if defn.type:
a = self.type_analyzer()
a.bind_function_type_variables(cast(CallableType, defn.type), defn)
self.function_stack.append(defn)
self.enter(defn)
for arg in defn.arguments:
self.add_local(arg.variable, defn)
# The first argument of a non-static, non-class method is like 'self'
# (though the name could be different), having the enclosing class's
# instance type.
if is_method and not defn.is_static and not defn.is_class and defn.arguments:
defn.arguments[0].variable.is_self = True
defn.body.accept(self)
self.leave()
self.function_stack.pop()
def check_classvar_in_signature(self, typ: ProperType) -> None:
if isinstance(typ, Overloaded):
for t in typ.items(): # type: ProperType
self.check_classvar_in_signature(t)
return
if not isinstance(typ, CallableType):
return
for t in get_proper_types(typ.arg_types) + [get_proper_type(typ.ret_type)]:
if self.is_classvar(t):
self.fail_invalid_classvar(t)
# Show only one error per signature
break
def check_function_signature(self, fdef: FuncItem) -> None:
sig = fdef.type
assert isinstance(sig, CallableType)
if len(sig.arg_types) < len(fdef.arguments):
self.fail('Type signature has too few arguments', fdef)
# Add dummy Any arguments to prevent crashes later.
num_extra_anys = len(fdef.arguments) - len(sig.arg_types)
extra_anys = [AnyType(TypeOfAny.from_error)] * num_extra_anys
sig.arg_types.extend(extra_anys)
elif len(sig.arg_types) > len(fdef.arguments):
self.fail('Type signature has too many arguments', fdef, blocker=True)
def visit_decorator(self, dec: Decorator) -> None:
self.statement = dec
# TODO: better don't modify them at all.
dec.decorators = dec.original_decorators.copy()
dec.func.is_conditional = self.block_depth[-1] > 0
if not dec.is_overload:
self.add_symbol(dec.name, dec, dec)
dec.func._fullname = self.qualified_name(dec.name)
for d in dec.decorators:
d.accept(self)
removed = [] # type: List[int]
no_type_check = False
for i, d in enumerate(dec.decorators):
# A bunch of decorators are special cased here.
if refers_to_fullname(d, 'abc.abstractmethod'):
removed.append(i)
dec.func.is_abstract = True
self.check_decorated_function_is_method('abstractmethod', dec)
elif (refers_to_fullname(d, 'asyncio.coroutines.coroutine') or
refers_to_fullname(d, 'types.coroutine')):
removed.append(i)
dec.func.is_awaitable_coroutine = True
elif refers_to_fullname(d, 'builtins.staticmethod'):
removed.append(i)
dec.func.is_static = True
dec.var.is_staticmethod = True
self.check_decorated_function_is_method('staticmethod', dec)
elif refers_to_fullname(d, 'builtins.classmethod'):
removed.append(i)
dec.func.is_class = True
dec.var.is_classmethod = True
self.check_decorated_function_is_method('classmethod', dec)