Repository navigation
Expand file tree
/
Copy pathsemanal.py
More file actions
2622 lines (2309 loc) · 108 KB
/
Copy pathsemanal.py
File metadata and controls
2622 lines (2309 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""The semantic analyzer.
Bind names to definitions and do various other simple consistency
checks. 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 node. The second assignment would also be
analyzed, and the type of 'y' marked as being inferred.
Semantic analysis is the first analysis pass after parsing, and it is
subdivided into three passes:
* FirstPass looks up externally visible names defined in a module but
ignores imports and local definitions. It helps enable (some)
cyclic references between modules, such as module 'a' that imports
module 'b' and used names defined in b *and* vice versa. The first
pass can be performed before dependent modules have been processed.
* SemanticAnalyzer is the second pass. It does the bulk of the work.
It assumes that dependent modules have been semantically analyzed,
up to the second pass, unless there is a import cycle.
* ThirdPass checks that type argument counts are valid; for example,
it will reject Dict[int]. We don't do this in the second pass,
since we infer the type argument counts of classes during this
pass, and it is possible to refer to classes defined later in a
file, which would not have the type argument count set yet.
Semantic analysis of types is implemented in module mypy.typeanal.
TODO: Check if the third pass slows down type checking significantly.
We could probably get rid of it -- for example, we could collect all
analyzed types in a collection and check them without having to
traverse the entire AST.
"""
from typing import (
List, Dict, Set, Tuple, cast, Any, overload, TypeVar, Union, Optional
)
from mypy.nodes import (
MypyFile, TypeInfo, Node, AssignmentStmt, FuncDef, OverloadedFuncDef,
ClassDef, Var, GDEF, MODULE_REF, FuncItem, Import,
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, TypeApplication, Context, SymbolTable,
SymbolTableNode, BOUND_TVAR, UNBOUND_TVAR, ListComprehension, GeneratorExpr,
FuncExpr, MDEF, FuncBase, Decorator, SetExpr, TypeVarExpr,
StrExpr, PrintStmt, ConditionalExpr, PromoteExpr,
ComparisonExpr, StarExpr, ARG_POS, ARG_NAMED, MroError, type_aliases,
YieldFromExpr, NamedTupleExpr, NonlocalDecl,
SetComprehension, DictionaryComprehension, TYPE_ALIAS, TypeAliasExpr,
YieldExpr, ExecStmt, Argument, BackquoteExpr, ImportBase, COVARIANT, CONTRAVARIANT,
INVARIANT, UNBOUND_IMPORTED
)
from mypy.visitor import NodeVisitor
from mypy.traverser import TraverserVisitor
from mypy.errors import Errors, report_internal_error
from mypy.types import (
NoneTyp, CallableType, Overloaded, Instance, Type, TypeVarType, AnyType,
FunctionLike, UnboundType, TypeList, ErrorType, TypeVarDef,
replace_leading_arg_type, TupleType, UnionType, StarType, EllipsisType
)
from mypy.nodes import function_type, implicit_module_attrs
from mypy.typeanal import TypeAnalyser, TypeAnalyserPass3, analyze_type_alias
from mypy.exprtotype import expr_to_unanalyzed_type, TypeTranslationError
from mypy.lex import lex
from mypy.parsetype import parse_type
from mypy.sametypes import is_same_type
from mypy import defaults
T = TypeVar('T')
# Inferred value of an expression.
ALWAYS_TRUE = 0
ALWAYS_FALSE = 1
TRUTH_VALUE_UNKNOWN = 2
# Map from obsolete name to the current spelling.
obsolete_name_mapping = {
'typing.Function': 'typing.Callable',
'typing.typevar': 'typing.TypeVar',
}
# Hard coded type promotions (shared between all Python versions).
# These add extra ad-hoc edges to the subtyping relation. For example,
# int is considered a subtype of float, even though there is no
# subclass relationship.
TYPE_PROMOTIONS = {
'builtins.int': 'builtins.float',
'builtins.float': 'builtins.complex',
}
# Hard coded type promotions for Python 3.
#
# Note that the bytearray -> bytes promotion is a little unsafe
# as some functions only accept bytes objects. Here convenience
# trumps safety.
TYPE_PROMOTIONS_PYTHON3 = TYPE_PROMOTIONS.copy()
TYPE_PROMOTIONS_PYTHON3.update({
'builtins.bytearray': 'builtins.bytes',
})
# Hard coded type promotions for Python 2.
#
# These promotions are unsafe, but we are doing them anyway
# for convenience and also for Python 3 compatibility
# (bytearray -> str).
TYPE_PROMOTIONS_PYTHON2 = TYPE_PROMOTIONS.copy()
TYPE_PROMOTIONS_PYTHON2.update({
'builtins.str': 'builtins.unicode',
'builtins.bytearray': 'builtins.str',
})
# When analyzing a function, should we analyze the whole function in one go, or
# should we only perform one phase of the analysis? The latter is used for
# nested functions. In the first phase we add the function to the symbol table
# but don't process body. In the second phase we process function body. This
# way we can have mutually recursive nested functions.
FUNCTION_BOTH_PHASES = 0 # Everthing in one go
FUNCTION_FIRST_PHASE_POSTPONE_SECOND = 1 # Add to symbol table but postpone body
FUNCTION_SECOND_PHASE = 2 # Only analyze body
class SemanticAnalyzer(NodeVisitor):
"""Semantically analyze parsed mypy files.
The analyzer binds names and does various consistency checks for a
parse tree. Note that type checking is performed as a separate
pass.
This is the second phase of semantic analysis.
"""
# Library search paths
lib_path = None # type: List[str]
# 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[SymbolTable]
# Nested block depths of scopes
block_depth = None # type: List[int]
# TypeInfo of directly enclosing class (or None)
type = None # type: TypeInfo
# Stack of outer classes (the second tuple item contains tvars).
type_stack = None # type: List[TypeInfo]
# Type variables that are bound by the directly enclosing class
bound_tvars = None # type: List[SymbolTableNode]
# Stack of type varialbes that were bound by outer classess
tvar_stack = None # type: List[List[SymbolTableNode]]
# Stack of functions being analyzed
function_stack = None # type: List[FuncItem]
# Status of postponing analysis of nested function bodies. By using this we
# can have mutually recursive nested functions. Values are FUNCTION_x
# constants. Note that separate phasea are not used for methods.
postpone_nested_functions_stack = None # type: List[int]
# Postponed functions collected if
# postpone_nested_functions_stack[-1] == FUNCTION_FIRST_PHASE_POSTPONE_SECOND.
postponed_functions_stack = None # type: List[List[Node]]
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?
imports = None # type: Set[str] # Imported modules (during phase 2 analysis)
errors = None # type: Errors # Keeps track of generated errors
def __init__(self, lib_path: List[str], errors: Errors,
pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION) -> None:
"""Construct semantic analyzer.
Use lib_path to search for modules, and report analysis errors
using the Errors instance.
"""
self.locals = [None]
self.imports = set()
self.type = None
self.type_stack = []
self.bound_tvars = None
self.tvar_stack = []
self.function_stack = []
self.block_depth = [0]
self.loop_depth = 0
self.lib_path = lib_path
self.errors = errors
self.modules = {}
self.pyversion = pyversion
self.postpone_nested_functions_stack = [FUNCTION_BOTH_PHASES]
self.postponed_functions_stack = []
def visit_file(self, file_node: MypyFile, fnam: str) -> None:
self.errors.set_file(fnam)
self.errors.set_ignored_lines(file_node.ignored_lines)
self.cur_mod_node = file_node
self.cur_mod_id = file_node.fullname()
self.is_stub_file = fnam.lower().endswith('.pyi')
self.globals = file_node.names
if 'builtins' in self.modules:
self.globals['__builtins__'] = SymbolTableNode(
MODULE_REF, self.modules['builtins'], self.cur_mod_id)
for name in implicit_module_attrs:
v = self.globals[name].node
if isinstance(v, Var):
v.type = self.anal_type(v.type)
v.is_ready = True
defs = file_node.defs
for d in defs:
self.accept(d)
if self.cur_mod_id == 'builtins':
remove_imported_names_from_symtable(self.globals, 'builtins')
self.errors.set_ignored_lines(set())
def visit_func_def(self, defn: FuncDef) -> None:
phase_info = self.postpone_nested_functions_stack[-1]
if phase_info != FUNCTION_SECOND_PHASE:
# First phase of analysis for function.
self.errors.push_function(defn.name())
self.update_function_type_variables(defn)
self.errors.pop_function()
defn.is_conditional = self.block_depth[-1] > 0
# TODO(jukka): Figure out how to share the various cases. It doesn't
# make sense to have (almost) duplicate code (here and elsewhere) for
# 3 cases: module-level, class-level and local names. Maybe implement
# a common stack of namespaces. As the 3 kinds of namespaces have
# different semantics, this wouldn't always work, but it might still
# be a win.
if self.is_class_scope():
# Method definition
defn.info = self.type
if not defn.is_decorated and not defn.is_overload:
if defn.name() in self.type.names:
# Redefinition. Conditional redefinition is okay.
n = self.type.names[defn.name()].node
if self.is_conditional_func(n, defn):
defn.original_def = cast(FuncDef, n)
else:
self.name_already_defined(defn.name(), defn)
self.type.names[defn.name()] = SymbolTableNode(MDEF, defn)
self.prepare_method_signature(defn)
elif self.is_func_scope():
# Nested function
if not defn.is_decorated and not defn.is_overload:
if defn.name() in self.locals[-1]:
# Redefinition. Conditional redefinition is okay.
n = self.locals[-1][defn.name()].node
if self.is_conditional_func(n, defn):
defn.original_def = cast(FuncDef, n)
else:
self.name_already_defined(defn.name(), defn)
else:
self.add_local(defn, defn)
else:
# Top-level function
if not defn.is_decorated and not defn.is_overload:
symbol = self.globals.get(defn.name())
if isinstance(symbol.node, FuncDef) and symbol.node != defn:
# This is redefinition. Conditional redefinition is okay.
original_def = symbol.node
if self.is_conditional_func(original_def, defn):
# Conditional function definition -- multiple defs are ok.
defn.original_def = cast(FuncDef, original_def)
else:
# Report error.
self.check_no_global(defn.name(), defn, True)
if phase_info == FUNCTION_FIRST_PHASE_POSTPONE_SECOND:
# Postpone this function (for the second phase).
self.postponed_functions_stack[-1].append(defn)
return
if phase_info != FUNCTION_FIRST_PHASE_POSTPONE_SECOND:
# Second phase of analysis for function.
self.errors.push_function(defn.name())
self.analyze_function(defn)
self.errors.pop_function()
def prepare_method_signature(self, func: FuncDef) -> None:
"""Check basic signature validity and tweak annotation of self/cls argument."""
# Only non-static methods are special.
if not func.is_static:
if not func.arguments:
self.fail('Method must have at least one argument', func)
elif func.type:
sig = cast(FunctionLike, func.type)
# TODO: A classmethod's first argument should be more
# precisely typed than Any.
leading_type = AnyType() if func.is_class else self_type(self.type)
func.type = replace_implicit_first_type(sig, leading_type)
def is_conditional_func(self, previous: Node, new: FuncDef) -> bool:
"""Does 'new' conditionally redefine 'previous'?
We reject straight redefinitions of functions, as they are usuallly
a programming error. For example:
. def f(): ...
. def f(): ... # Error: 'f' redefined
"""
return isinstance(previous, (FuncDef, Var)) and new.is_conditional
def update_function_type_variables(self, defn: FuncDef) -> 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.
"""
if defn.type:
functype = cast(CallableType, defn.type)
typevars = self.infer_type_variables(functype)
# Do not define a new type variable if already defined in scope.
typevars = [(name, tvar) for name, tvar in typevars
if not self.is_defined_type_var(name, defn)]
if typevars:
defs = [TypeVarDef(tvar[0], -i - 1, tvar[1].values, self.object_type(),
tvar[1].variance)
for i, tvar in enumerate(typevars)]
functype.variables = defs
def infer_type_variables(self,
type: CallableType) -> List[Tuple[str, TypeVarExpr]]:
"""Return list of unique type variables referred to in a callable."""
names = [] # type: List[str]
tvars = [] # type: List[TypeVarExpr]
for arg in type.arg_types + [type.ret_type]:
for name, tvar_expr in self.find_type_variables_in_type(arg):
if name not in names:
names.append(name)
tvars.append(tvar_expr)
return list(zip(names, tvars))
def find_type_variables_in_type(
self, type: Type) -> List[Tuple[str, TypeVarExpr]]:
"""Return a list of all unique type variable references in type.
This effectively does partial name binding, results of which are mostly thrown away.
"""
result = [] # type: List[Tuple[str, TypeVarExpr]]
if isinstance(type, UnboundType):
name = type.name
node = self.lookup_qualified(name, type)
if node and node.kind == UNBOUND_TVAR:
result.append((name, cast(TypeVarExpr, node.node)))
for arg in type.args:
result.extend(self.find_type_variables_in_type(arg))
elif isinstance(type, TypeList):
for item in type.items:
result.extend(self.find_type_variables_in_type(item))
elif isinstance(type, UnionType):
for item in type.items:
result.extend(self.find_type_variables_in_type(item))
elif isinstance(type, AnyType):
pass
elif isinstance(type, EllipsisType) or isinstance(type, TupleType):
pass
else:
assert False, 'Unsupported type %s' % type
return result
def is_defined_type_var(self, tvar: str, context: Node) -> bool:
return self.lookup_qualified(tvar, context).kind == BOUND_TVAR
def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
t = [] # type: List[CallableType]
for i, item in enumerate(defn.items):
# TODO support decorated overloaded functions properly
item.is_overload = True
item.func.is_overload = True
item.accept(self)
t.append(cast(CallableType, function_type(item.func,
self.builtin_type('builtins.function'))))
if item.func.is_property and i == 0:
# This defines a property, probably with a setter and/or deleter.
self.analyze_property_with_multi_part_definition(defn)
break
if not [dec for dec in item.decorators
if refers_to_fullname(dec, 'typing.overload')]:
self.fail("'overload' decorator expected", item)
defn.type = Overloaded(t)
defn.type.line = defn.line
if self.is_class_scope():
self.type.names[defn.name()] = SymbolTableNode(MDEF, defn,
typ=defn.type)
defn.info = self.type
elif self.is_func_scope():
self.add_local(defn, defn)
def analyze_property_with_multi_part_definition(self, defn: OverloadedFuncDef) -> None:
"""Analyze a propery 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
for item in items[1:]:
if len(item.decorators) == 1:
node = item.decorators[0]
if isinstance(node, MemberExpr):
if node.name == 'setter':
# The first item represents the entire property.
defn.items[0].var.is_settable_property = True
# Get abstractness from the original definition.
item.func.is_abstract = items[0].func.is_abstract
else:
self.fail("Decorated property not supported", item)
item.func.accept(self)
def analyze_function(self, defn: FuncItem) -> None:
is_method = self.is_class_scope()
tvarnodes = self.add_func_type_variables_to_symbol_table(defn)
if defn.type:
# Signature must be analyzed in the surrounding scope so that
# class-level imported names and type variables are in scope.
defn.type = self.anal_type(defn.type)
self.check_function_signature(defn)
if isinstance(defn, FuncDef):
defn.info = self.type
defn.type = set_callable_name(defn.type, defn)
for arg in defn.arguments:
if arg.initializer:
arg.initializer.accept(self)
self.function_stack.append(defn)
self.enter()
for arg in defn.arguments:
self.add_local(arg.variable, defn)
for arg in defn.arguments:
if arg.initialization_statement:
lvalue = arg.initialization_statement.lvalues[0]
lvalue.accept(self)
# 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
# First analyze body of the function but ignore nested functions.
self.postpone_nested_functions_stack.append(FUNCTION_FIRST_PHASE_POSTPONE_SECOND)
self.postponed_functions_stack.append([])
defn.body.accept(self)
# Analyze nested functions (if any) as a second phase.
self.postpone_nested_functions_stack[-1] = FUNCTION_SECOND_PHASE
for postponed in self.postponed_functions_stack[-1]:
postponed.accept(self)
self.postpone_nested_functions_stack.pop()
self.postponed_functions_stack.pop()
disable_typevars(tvarnodes)
self.leave()
self.function_stack.pop()
def add_func_type_variables_to_symbol_table(
self, defn: FuncItem) -> List[SymbolTableNode]:
nodes = [] # type: List[SymbolTableNode]
if defn.type:
tt = defn.type
names = self.type_var_names()
items = cast(CallableType, tt).variables
for i, item in enumerate(items):
name = item.name
if name in names:
self.name_already_defined(name, defn)
node = self.bind_type_var(name, -i - 1, defn)
nodes.append(node)
names.add(name)
return nodes
def type_var_names(self) -> Set[str]:
if not self.type:
return set()
else:
return set(self.type.type_vars)
def bind_type_var(self, fullname: str, id: int,
context: Context) -> SymbolTableNode:
node = self.lookup_qualified(fullname, context)
node.kind = BOUND_TVAR
node.tvar_id = id
return node
def check_function_signature(self, fdef: FuncItem) -> None:
sig = cast(CallableType, fdef.type)
if len(sig.arg_types) < len(fdef.arguments):
self.fail('Type signature has too few arguments', fdef)
elif len(sig.arg_types) > len(fdef.arguments):
self.fail('Type signature has too many arguments', fdef)
def visit_class_def(self, defn: ClassDef) -> None:
self.clean_up_bases_and_infer_type_variables(defn)
self.setup_class_def_analysis(defn)
self.bind_class_type_vars(defn)
self.analyze_base_classes(defn)
self.analyze_metaclass(defn)
for decorator in defn.decorators:
self.analyze_class_decorator(defn, decorator)
self.enter_class(defn)
self.setup_is_builtinclass(defn)
# Analyze class body.
defn.defs.accept(self)
self.calculate_abstract_status(defn.info)
self.setup_type_promotion(defn)
self.leave_class()
self.unbind_class_type_vars()
def enter_class(self, defn: ClassDef) -> None:
# Remember previous active class
self.type_stack.append(self.type)
self.locals.append(None) # Add class scope
self.block_depth.append(-1) # The class body increments this to 0
self.postpone_nested_functions_stack.append(FUNCTION_BOTH_PHASES)
self.type = defn.info
def leave_class(self) -> None:
""" Restore analyzer state. """
self.postpone_nested_functions_stack.pop()
self.block_depth.pop()
self.locals.pop()
self.type = self.type_stack.pop()
def bind_class_type_vars(self, defn: ClassDef) -> None:
""" Unbind type variables of previously active class and bind
the type variables for the active class.
"""
if self.bound_tvars:
disable_typevars(self.bound_tvars)
self.tvar_stack.append(self.bound_tvars)
self.bound_tvars = self.bind_class_type_variables_in_symbol_table(defn.info)
def unbind_class_type_vars(self) -> None:
""" Unbind the active class' type vars and rebind the
type vars of the previously active class.
"""
disable_typevars(self.bound_tvars)
self.bound_tvars = self.tvar_stack.pop()
if self.bound_tvars:
enable_typevars(self.bound_tvars)
def analyze_class_decorator(self, defn: ClassDef, decorator: Node) -> None:
decorator.accept(self)
def setup_is_builtinclass(self, defn: ClassDef):
for decorator in defn.decorators:
if refers_to_fullname(decorator, 'typing.builtinclass'):
defn.is_builtinclass = True
if defn.fullname == 'builtins.object':
# Only 'object' is marked as a built-in class, as otherwise things elsewhere
# would break. We need a better way of dealing with built-in classes.
defn.is_builtinclass = True
def calculate_abstract_status(self, typ: TypeInfo) -> None:
"""Calculate abstract status of a class.
Set is_abstract of the type to True if the type has an unimplemented
abstract attribute. Also compute a list of abstract attributes.
"""
concrete = set() # type: Set[str]
abstract = [] # type: List[str]
for base in typ.mro:
for name, symnode in base.names.items():
node = symnode.node
if isinstance(node, OverloadedFuncDef):
# Unwrap an overloaded function definition. We can just
# check arbitrarily the first overload item. If the
# different items have a different abstract status, there
# should be an error reported elsewhere.
func = node.items[0] # type: Node
else:
func = node
if isinstance(func, Decorator):
fdef = func.func
if fdef.is_abstract and name not in concrete:
typ.is_abstract = True
abstract.append(name)
concrete.add(name)
typ.abstract_attributes = sorted(abstract)
def setup_type_promotion(self, defn: ClassDef) -> None:
"""Setup extra, ad-hoc subtyping relationships between classes (promotion).
This includes things like 'int' being compatible with 'float'.
"""
promote_target = None # type: Type
for decorator in defn.decorators:
if isinstance(decorator, CallExpr):
analyzed = decorator.analyzed
if isinstance(analyzed, PromoteExpr):
# _promote class decorator (undocumented faeture).
promote_target = analyzed.type
if not promote_target:
promotions = (TYPE_PROMOTIONS_PYTHON3 if self.pyversion[0] >= 3
else TYPE_PROMOTIONS_PYTHON2)
if defn.fullname in promotions:
promote_target = self.named_type_or_none(promotions[defn.fullname])
defn.info._promote = promote_target
def clean_up_bases_and_infer_type_variables(self, defn: ClassDef) -> None:
"""Remove extra base classes such as Generic and infer type vars.
For example, consider this class:
. class Foo(Bar, Generic[T]): ...
Now we will remove Generic[T] from bases of Foo and infer that the
type variable 'T' is a type argument of Foo.
Note that this is performed *before* semantic analysis.
"""
removed = [] # type: List[int]
type_vars = [] # type: List[TypeVarDef]
for i, base_expr in enumerate(defn.base_type_exprs):
try:
base = expr_to_unanalyzed_type(base_expr)
except TypeTranslationError:
# This error will be caught later.
continue
tvars = self.analyze_typevar_declaration(base)
if tvars is not None:
if type_vars:
self.fail('Duplicate Generic in bases', defn)
removed.append(i)
for j, (name, tvar_expr) in enumerate(tvars):
type_vars.append(TypeVarDef(name, j + 1, tvar_expr.values,
self.object_type(), tvar_expr.variance))
if type_vars:
defn.type_vars = type_vars
if defn.info:
defn.info.type_vars = [tv.name for tv in type_vars]
for i in reversed(removed):
del defn.base_type_exprs[i]
def analyze_typevar_declaration(self, t: Type) -> Optional[List[Tuple[str, TypeVarExpr]]]:
if not isinstance(t, UnboundType):
return None
unbound = cast(UnboundType, t)
sym = self.lookup_qualified(unbound.name, unbound)
if sym is None or sym.node is None:
return None
if sym.node.fullname() == 'typing.Generic':
tvars = [] # type: List[Tuple[str, TypeVarExpr]]
for arg in unbound.args:
tvar = self.analyze_unbound_tvar(arg)
if tvar:
tvars.append(tvar)
else:
self.fail('Free type variable expected in %s[...]' %
sym.node.name(), t)
return tvars
return None
def analyze_unbound_tvar(self, t: Type) -> Tuple[str, TypeVarExpr]:
if not isinstance(t, UnboundType):
return None
unbound = cast(UnboundType, t)
sym = self.lookup_qualified(unbound.name, unbound)
if sym is not None and sym.kind == UNBOUND_TVAR:
return unbound.name, cast(TypeVarExpr, sym.node)
return None
def setup_class_def_analysis(self, defn: ClassDef) -> None:
"""Prepare for the analysis of a class definition."""
if not defn.info:
defn.info = TypeInfo(SymbolTable(), defn)
defn.info._fullname = defn.info.name()
if self.is_func_scope() or self.type:
kind = MDEF
if self.is_func_scope():
kind = LDEF
self.add_symbol(defn.name, SymbolTableNode(kind, defn.info), defn)
def analyze_base_classes(self, defn: ClassDef) -> None:
"""Analyze and set up base classes."""
for base_expr in defn.base_type_exprs:
# The base class is originallly an expression; convert it to a type.
try:
base = self.expr_to_analyzed_type(base_expr)
except TypeTranslationError:
self.fail('Invalid base class', base_expr)
defn.info.mro = []
return
if isinstance(base, TupleType):
if defn.info.tuple_type:
self.fail("Class has two incompatible bases derived from tuple", defn)
defn.info.tuple_type = base
base = base.fallback
if (not self.is_stub_file and not defn.info.is_named_tuple and
base.type.fullname() == 'builtins.tuple'):
self.fail("Tuple[...] not supported as a base class outside a stub file", defn)
if isinstance(base, Instance):
defn.base_types.append(base)
elif isinstance(base, TupleType):
assert False, "Internal error: Unexpected TupleType base class"
elif isinstance(base, AnyType):
# We don't know anything about the base class. Make any unknown attributes
# have type 'Any'.
defn.info.fallback_to_any = True
elif not isinstance(base, UnboundType):
self.fail('Invalid base class', base_expr)
if isinstance(base, Instance):
defn.info.is_enum = base.type.fullname() == 'enum.Enum'
# Add 'object' as implicit base if there is no other base class.
if (not defn.base_types and defn.fullname != 'builtins.object'):
obj = self.object_type()
defn.base_types.insert(0, obj)
defn.info.bases = defn.base_types
if not self.verify_base_classes(defn):
defn.info.mro = []
return
try:
defn.info.calculate_mro()
except MroError:
self.fail("Cannot determine consistent method resolution order "
'(MRO) for "%s"' % defn.name, defn)
defn.info.mro = []
else:
# If there are cyclic imports, we may be missing 'object' in
# the MRO. Fix MRO if needed.
if defn.info.mro[-1].fullname() != 'builtins.object':
defn.info.mro.append(self.object_type().type)
# The property of falling back to Any is inherited.
defn.info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in defn.info.mro)
def expr_to_analyzed_type(self, expr: Node) -> Type:
if isinstance(expr, CallExpr):
expr.accept(self)
info = self.check_namedtuple(expr)
if info is None:
# Some form of namedtuple is the only valid type that looks like a call
# expression. This isn't a valid type.
raise TypeTranslationError()
fallback = Instance(info, [])
return TupleType(info.tuple_type.items, fallback=fallback)
typ = expr_to_unanalyzed_type(expr)
return self.anal_type(typ)
def verify_base_classes(self, defn: ClassDef) -> bool:
info = defn.info
for base in info.bases:
baseinfo = base.type
if self.is_base_class(info, baseinfo):
self.fail('Cycle in inheritance hierarchy', defn)
# Clear bases to forcefully get rid of the cycle.
info.bases = []
if baseinfo.fullname() == 'builtins.bool':
self.fail("'%s' is not a valid base class" %
baseinfo.name(), defn)
return False
dup = find_duplicate(info.direct_base_classes())
if dup:
self.fail('Duplicate base class "%s"' % dup.name(), defn)
return False
return True
def is_base_class(self, t: TypeInfo, s: TypeInfo) -> bool:
"""Determine if t is a base class of s (but do not use mro)."""
# Search the base class graph for t, starting from s.
worklist = [s]
visited = {s}
while worklist:
nxt = worklist.pop()
if nxt == t:
return True
for base in nxt.bases:
if base.type not in visited:
worklist.append(base.type)
visited.add(base.type)
return False
def analyze_metaclass(self, defn: ClassDef) -> None:
if defn.metaclass:
sym = self.lookup_qualified(defn.metaclass, defn)
if sym is not None and not isinstance(sym.node, TypeInfo):
self.fail("Invalid metaclass '%s'" % defn.metaclass, defn)
def object_type(self) -> Instance:
return self.named_type('__builtins__.object')
def named_type(self, qualified_name: str, args: List[Type] = None) -> Instance:
sym = self.lookup_qualified(qualified_name, None)
return Instance(cast(TypeInfo, sym.node), args or [])
def named_type_or_none(self, qualified_name: str) -> Instance:
sym = self.lookup_fully_qualified_or_none(qualified_name)
if not sym:
return None
return Instance(cast(TypeInfo, sym.node), [])
def is_instance_type(self, t: Type) -> bool:
return isinstance(t, Instance)
def bind_class_type_variables_in_symbol_table(
self, info: TypeInfo) -> List[SymbolTableNode]:
vars = info.type_vars
nodes = [] # type: List[SymbolTableNode]
for index, var in enumerate(vars, 1):
node = self.bind_type_var(var, index, info)
nodes.append(node)
return nodes
def visit_import(self, i: Import) -> None:
for id, as_id in i.ids:
if as_id is not None:
self.add_module_symbol(id, as_id, module_public=True, context=i)
else:
# Modules imported in a stub file without using 'as x' won't get exported when
# doing 'from m import *'.
module_public = not self.is_stub_file
base = id.split('.')[0]
self.add_module_symbol(base, base, module_public=module_public,
context=i)
def add_module_symbol(self, id: str, as_id: str, module_public: bool,
context: Context) -> None:
if id in self.modules:
m = self.modules[id]
self.add_symbol(as_id, SymbolTableNode(MODULE_REF, m, self.cur_mod_id,
module_public=module_public), context)
else:
self.add_unknown_symbol(as_id, context)
def visit_import_from(self, imp: ImportFrom) -> None:
import_id = self.correct_relative_import(imp)
if import_id in self.modules:
module = self.modules[import_id]
for id, as_id in imp.names:
node = module.names.get(id)
if node and node.kind != UNBOUND_IMPORTED:
node = self.normalize_type_alias(node, imp)
if not node:
return
imported_id = as_id or id
existing_symbol = self.globals.get(imported_id)
if existing_symbol:
# Import can redefine a variable. They get special treatment.
if self.process_import_over_existing_name(
imported_id, existing_symbol, node, imp):
continue
# 'from m import x as x' exports x in a stub file.
module_public = not self.is_stub_file or as_id is not None
symbol = SymbolTableNode(node.kind, node.node,
self.cur_mod_id,
node.type_override,
module_public=module_public)
self.add_symbol(imported_id, symbol, imp)
else:
message = "Module has no attribute '{}'".format(id)
extra = self.undefined_name_extra_info('{}.{}'.format(import_id, id))
if extra:
message += " {}".format(extra)
self.fail(message, imp)
else:
# Missing module.
for id, as_id in imp.names:
self.add_unknown_symbol(as_id or id, imp)
def process_import_over_existing_name(self,
imported_id: str, existing_symbol: SymbolTableNode,
module_symbol: SymbolTableNode,
import_node: ImportBase) -> bool:
if (existing_symbol.kind in (LDEF, GDEF, MDEF) and
isinstance(existing_symbol.node, (Var, FuncDef))):
# This is a valid import over an existing definition in the file. Construct a dummy
# assignment that we'll use to type check the import.
lvalue = NameExpr(imported_id)
lvalue.kind = existing_symbol.kind
lvalue.node = existing_symbol.node
rvalue = NameExpr(imported_id)
rvalue.kind = module_symbol.kind
rvalue.node = module_symbol.node
assignment = AssignmentStmt([lvalue], rvalue)
for node in assignment, lvalue, rvalue:
node.set_line(import_node)
import_node.assignments.append(assignment)
return True
return False
def normalize_type_alias(self, node: SymbolTableNode,
ctx: Context) -> SymbolTableNode:
if node.fullname in type_aliases:
# Node refers to an aliased type such as typing.List; normalize.
node = self.lookup_qualified(type_aliases[node.fullname], ctx)
return node
def correct_relative_import(self, node: Union[ImportFrom, ImportAll]) -> str:
if node.relative == 0:
return node.id
parts = self.cur_mod_id.split(".")
cur_mod_id = self.cur_mod_id
rel = node.relative
if self.cur_mod_node.is_package_init_file():
rel -= 1
if len(parts) < rel:
self.fail("Relative import climbs too many namespaces", node)
if rel != 0:
cur_mod_id = ".".join(parts[:-rel])
return cur_mod_id + (("." + node.id) if node.id else "")
def visit_import_all(self, i: ImportAll) -> None:
i_id = self.correct_relative_import(i)
if i_id in self.modules:
m = self.modules[i_id]
for name, node in m.names.items():
node = self.normalize_type_alias(node, i)
if not name.startswith('_') and node.module_public:
existing_symbol = self.globals.get(name)
if existing_symbol:
# Import can redefine a variable. They get special treatment.
if self.process_import_over_existing_name(
name, existing_symbol, node, i):
continue
self.add_symbol(name, SymbolTableNode(node.kind, node.node,
self.cur_mod_id), i)
else:
# Don't add any dummy symbols for 'from x import *' if 'x' is unknown.
pass
def add_unknown_symbol(self, name: str, context: Context) -> None:
var = Var(name)
var._fullname = self.qualified_name(name)
var.is_ready = True
var.type = AnyType()
self.add_symbol(name, SymbolTableNode(GDEF, var, self.cur_mod_id), context)
#
# Statements
#
def visit_block(self, b: Block) -> None:
if b.is_unreachable:
return
self.block_depth[-1] += 1
for s in b.body:
self.accept(s)
self.block_depth[-1] -= 1
def visit_block_maybe(self, b: Block) -> None:
if b:
self.visit_block(b)
def anal_type(self, t: Type, allow_tuple_literal: bool = False) -> Type:
if t:
if allow_tuple_literal:
# Types such as (t1, t2, ...) only allowed in assignment statements. They'll
# generate errors elsewhere, and Tuple[t1, t2, ...] must be used instead.
if isinstance(t, TupleType):
# Unlike TypeAnalyser, also allow implicit tuple types (without Tuple[...]).
star_count = sum(1 for item in t.items if isinstance(item, StarType))
if star_count > 1:
self.fail('At most one star type allowed in a tuple', t)
return TupleType([AnyType() for _ in t.items],
self.builtin_type('builtins.tuple'), t.line)
items = [self.anal_type(item, True)
for item in t.items]
return TupleType(items, self.builtin_type('builtins.tuple'), t.line)
a = TypeAnalyser(self.lookup_qualified,
self.lookup_fully_qualified,
self.fail)
return t.accept(a)
else:
return None
def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
for lval in s.lvalues:
self.analyze_lvalue(lval, explicit_type=s.type is not None)