-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
typeAnalyzer.ts
3234 lines (2734 loc) · 140 KB
/
typeAnalyzer.ts
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
/*
* typeAnalyzer.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* A parse tree walker that performs static type checking. It assumes
* that the semanticAnalyzer has already run and added information to
* the parse nodes.
*/
import * as assert from 'assert';
import { DiagnosticLevel } from '../common/configOptions';
import { DiagnosticAddendum } from '../common/diagnostic';
import { convertOffsetsToRange } from '../common/positionUtils';
import { PythonVersion } from '../common/pythonVersion';
import { TextRange } from '../common/textRange';
import { AssertNode, AssignmentNode, AugmentedAssignmentExpressionNode,
BinaryExpressionNode, BreakNode, CallExpressionNode, ClassNode, ConstantNode,
DecoratorNode, DelNode, ErrorExpressionNode, ExceptNode, ExpressionNode, FormatStringNode,
ForNode, FunctionNode, IfNode, ImportAsNode, ImportFromNode,
IndexExpressionNode, LambdaNode, ListComprehensionForNode, ListComprehensionNode,
ListNode, MemberAccessExpressionNode, ModuleNode, NameNode, ParameterCategory,
ParseNode, RaiseNode, ReturnNode, SliceExpressionNode, StringListNode,
SuiteNode, TernaryExpressionNode, TryNode, TupleExpressionNode,
TypeAnnotationExpressionNode, UnaryExpressionNode, UnpackExpressionNode, WhileNode,
WithNode, YieldExpressionNode, YieldFromExpressionNode } from '../parser/parseNodes';
import { KeywordType } from '../parser/tokenizerTypes';
import { ScopeUtils } from '../scopeUtils';
import { AnalyzerFileInfo } from './analyzerFileInfo';
import { AnalyzerNodeInfo } from './analyzerNodeInfo';
import { EvaluatorFlags, ExpressionEvaluator } from './expressionEvaluator';
import { ExpressionUtils } from './expressionUtils';
import { ImportResult, ImportType } from './importResult';
import { DefaultTypeSourceId, TypeSourceId } from './inferredType';
import { ParseTreeUtils } from './parseTreeUtils';
import { ParseTreeWalker } from './parseTreeWalker';
import { Scope, ScopeType, SymbolWithScope } from './scope';
import { Declaration, Symbol, SymbolCategory, SymbolTable } from './symbol';
import { SymbolUtils } from './symbolUtils';
import { TypeConstraintBuilder } from './typeConstraint';
import { TypeConstraintUtils } from './typeConstraintUtils';
import { AnyType, ClassType, ClassTypeFlags, FunctionParameter, FunctionType,
FunctionTypeFlags, ModuleType, NoneType, ObjectType, OverloadedFunctionType,
PropertyType, Type, TypeCategory, TypeVarType, UnboundType, UnionType,
UnknownType } from './types';
import { ClassMemberLookupFlags, TypeUtils } from './typeUtils';
interface AliasMapEntry {
alias: string;
module: 'builtins' | 'collections';
}
// At some point, we'll cut off the analysis passes and assume
// we're making no forward progress. This should happen only
// on the case of bugs in the analyzer.
// The number is somewhat arbitrary. It needs to be at least
// 21 or so to handle all of the import cycles in the stdlib
// files.
const MaxAnalysisPassCount = 25;
// There are rare circumstances where we can get into a "beating
// pattern" where one variable is assigned to another in one pass
// and the second assigned to the first in the second pass and
// they both contain an "unknown" in their union. In this case,
// we will never converge. Look for this particular case after
// several analysis passes.
const CheckForBeatingUnknownPassCount = 16;
export class TypeAnalyzer extends ParseTreeWalker {
private readonly _moduleNode: ModuleNode;
private readonly _fileInfo: AnalyzerFileInfo;
private _currentScope: Scope;
// Indicates where there was a change in the type analysis
// the last time analyze() was called. Callers should repeatedly
// call analyze() until this returns false.
private _didAnalysisChange: boolean;
// Analysis version is incremented each time an analyzer pass
// is performed. It allows the code to determine when cached
// type information needs to be regenerated because it was
// from a previous pass.
private _analysisVersion = 0;
constructor(node: ModuleNode, fileInfo: AnalyzerFileInfo, analysisVersion: number) {
super();
this._moduleNode = node;
this._fileInfo = fileInfo;
this._currentScope = AnalyzerNodeInfo.getScope(node)!;
this._didAnalysisChange = false;
this._analysisVersion = analysisVersion;
}
analyze() {
this._didAnalysisChange = false;
let declaration: Declaration = {
category: SymbolCategory.Module,
node: this._moduleNode,
path: this._fileInfo.filePath,
range: { start: { line: 0, column: 0 }, end: { line: 0, column: 0 } }
};
AnalyzerNodeInfo.setDeclarations(this._moduleNode, [declaration]);
this.walk(this._moduleNode);
// Clear out any type constraints that were collected
// during the processing of the scope.
this._currentScope.clearTypeConstraints();
// If we've already analyzed the file the max number of times,
// just give up and admit defeat. This should happen only in
// the case of analyzer bugs.
if (this._analysisVersion >= MaxAnalysisPassCount) {
this._fileInfo.console.log(
`Hit max analysis pass count for ${ this._fileInfo.filePath }`);
return false;
}
return this._didAnalysisChange;
}
visitClass(node: ClassNode): boolean {
// We should have already resolved most of the base class
// parameters in the semantic analyzer, but if these parameters
// are variables, they may not have been resolved at that time.
let classType = AnalyzerNodeInfo.getExpressionType(node) as ClassType;
assert(classType instanceof ClassType);
// Keep a list of unique type parameters that are used in the
// base class arguments.
let typeParameters: TypeVarType[] = [];
node.arguments.forEach((arg, index) => {
// Ignore keyword parameters other than metaclass.
if (!arg.name || arg.name.nameToken.value === 'metaclass') {
let argType = this._getTypeOfExpression(arg.valueExpression);
// In some stub files, classes are conditionally defined (e.g. based
// on platform type). We'll assume that the conditional logic is correct
// and strip off the "unbound" union.
if (argType instanceof UnionType) {
argType = TypeUtils.removeUnboundFromUnion(argType);
}
if (!argType.isAny() && argType.category !== TypeCategory.Class) {
this._addError(`Argument to class must be a base class`, arg);
argType = UnknownType.create();
}
if (argType instanceof ClassType) {
if (argType.isBuiltIn() && argType.getClassName() === 'Protocol') {
if (!this._fileInfo.isStubFile && this._fileInfo.executionEnvironment.pythonVersion < PythonVersion.V37) {
this._addError(`Use of 'Protocol' requires Python 3.7 or newer`, arg.valueExpression);
}
}
// If the class directly derives from NamedTuple (in Python 3.6 or
// newer), it's considered a dataclass.
if (this._fileInfo.executionEnvironment.pythonVersion >= PythonVersion.V36) {
if (argType.isBuiltIn() && argType.getClassName() === 'NamedTuple') {
classType.setIsDataClass();
}
}
// Validate that the class isn't deriving from itself, creating a
// circular dependency.
if (TypeUtils.derivesFromClassRecursive(argType, classType)) {
this._addError(`Class cannot derive from itself`, arg);
argType = UnknownType.create();
}
}
if (argType instanceof UnknownType ||
argType instanceof UnionType && argType.getTypes().some(t => t instanceof UnknownType)) {
this._addDiagnostic(
this._fileInfo.diagnosticSettings.reportUntypedBaseClass,
`Base class type is unknown, obscuring type of derived class`,
arg);
}
if (classType.updateBaseClassType(index, argType)) {
this._setAnalysisChanged();
}
// TODO - validate that we are not adding type parameters that
// are unique type vars but have conflicting names.
TypeUtils.addTypeVarsToListIfUnique(typeParameters,
TypeUtils.getTypeVarArgumentsRecursive(argType));
}
});
// Update the type parameters for the class.
if (classType.setTypeParameters(typeParameters)) {
this._setAnalysisChanged();
}
this._enterScope(node, () => {
this.walk(node.suite);
});
let decoratedType: Type = classType;
let foundUnknown = decoratedType instanceof UnknownType;
for (let i = node.decorators.length - 1; i >= 0; i--) {
const decorator = node.decorators[i];
decoratedType = this._applyClassDecorator(decoratedType,
classType, decorator);
if (decoratedType instanceof UnknownType) {
// Report this error only on the first unknown type.
if (!foundUnknown) {
this._addDiagnostic(
this._fileInfo.diagnosticSettings.reportUntypedClassDecorator,
`Untyped class declarator obscures type of class`,
node.decorators[i].leftExpression);
foundUnknown = true;
}
}
}
if (classType.isDataClass()) {
let evaluator = this._createEvaluator();
evaluator.synthesizeDataClassMethods(node, classType);
}
let declaration: Declaration = {
category: SymbolCategory.Class,
node: node.name,
path: this._fileInfo.filePath,
range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines)
};
this._assignTypeToNameNode(node.name, decoratedType, declaration);
this._validateClassMethods(classType);
this._updateExpressionTypeForNode(node.name, classType);
this.walkMultiple(node.decorators);
this.walkMultiple(node.arguments);
this._conditionallyReportUnusedName(node.name, true,
this._fileInfo.diagnosticSettings.reportUnusedClass,
`Class '${ node.name.nameToken.value }' is not accessed`);
return false;
}
visitFunction(node: FunctionNode): boolean {
// Retrieve the containing class node if the function is a method.
const containingClassNode = ParseTreeUtils.getEnclosingClass(node, true);
const containingClassType = containingClassNode ?
AnalyzerNodeInfo.getExpressionType(containingClassNode) as ClassType : undefined;
const functionType = AnalyzerNodeInfo.getExpressionType(node) as FunctionType;
assert(functionType instanceof FunctionType);
if (this._fileInfo.isBuiltInStubFile) {
// Stash away the name of the function since we need to handle
// 'namedtuple', 'abstractmethod' and 'dataclass' specially.
functionType.setBuiltInName(node.name.nameToken.value);
}
let asyncType = functionType;
if (node.isAsync) {
asyncType = this._createAwaitableFunction(functionType);
}
// Apply all of the decorators in reverse order.
let decoratedType: Type = asyncType;
let foundUnknown = decoratedType instanceof UnknownType;
for (let i = node.decorators.length - 1; i >= 0; i--) {
const decorator = node.decorators[i];
decoratedType = this._applyFunctionDecorator(decoratedType,
functionType, decorator, node);
if (decoratedType instanceof UnknownType) {
// Report this error only on the first unknown type.
if (!foundUnknown) {
this._addDiagnostic(
this._fileInfo.diagnosticSettings.reportUntypedFunctionDecorator,
`Untyped function declarator obscures type of function`,
node.decorators[i].leftExpression);
foundUnknown = true;
}
}
}
// Mark the class as abstract if it contains at least one abstract method.
if (functionType.isAbstractMethod() && containingClassType) {
containingClassType.setIsAbstractClass();
}
if (containingClassNode) {
if (!functionType.isClassMethod() && !functionType.isStaticMethod()) {
// Mark the function as an instance method.
functionType.setIsInstanceMethod();
// If there's a separate async version, mark it as an instance
// method as well.
if (functionType !== asyncType) {
asyncType.setIsInstanceMethod();
}
}
}
node.parameters.forEach((param, index) => {
let annotatedType: Type | undefined;
let defaultValueType: Type | undefined;
if (param.defaultValue) {
defaultValueType = this._getTypeOfExpression(param.defaultValue,
EvaluatorFlags.ConvertEllipsisToAny);
this.walk(param.defaultValue);
}
if (param.typeAnnotation) {
annotatedType = this._getTypeOfAnnotation(param.typeAnnotation);
// PEP 484 indicates that if a parameter has a default value of 'None'
// the type checker should assume that the type is optional (i.e. a union
// of the specified type and 'None').
// TODO - tighten this up, perhaps using a config setting
if (param.defaultValue instanceof ConstantNode) {
if (param.defaultValue.token.keywordType === KeywordType.None) {
annotatedType = TypeUtils.combineTypes(
[annotatedType, NoneType.create()]);
}
}
// If there was both a type annotation and a default value, verify
// that the default value matches the annotation.
if (param.defaultValue && defaultValueType) {
const concreteAnnotatedType = TypeUtils.specializeType(annotatedType, undefined);
const diagAddendum = new DiagnosticAddendum();
if (!TypeUtils.canAssignType(concreteAnnotatedType, defaultValueType, diagAddendum, undefined)) {
this._addError(
`Value of type '${ defaultValueType.asString() }' cannot` +
` be assiged to parameter of type '${ annotatedType.asString() }'` +
diagAddendum.getString(),
param.defaultValue);
}
}
if (functionType.setParameterType(index, annotatedType)) {
this._setAnalysisChanged();
}
this.walk(param.typeAnnotation);
} else if (index === 0 && (
functionType.isInstanceMethod() ||
functionType.isClassMethod() ||
functionType.isConstructorMethod())) {
// Specify type of "self" or "cls" parameter for instance or class methods
// if the type is not explicitly provided.
if (containingClassType) {
const paramType = functionType.getParameters()[0].type;
if (paramType instanceof UnknownType) {
// Don't specialize the "self" for protocol classes because type
// comparisons will fail during structural typing analysis.
if (containingClassType && !containingClassType.isProtocol()) {
if (functionType.isInstanceMethod()) {
const specializedClassType = TypeUtils.selfSpecializeClassType(
containingClassType);
if (functionType.setParameterType(index, new ObjectType(specializedClassType))) {
this._setAnalysisChanged();
}
} else if (functionType.isClassMethod() || functionType.isConstructorMethod()) {
// For class methods, the cls parameter is allowed to skip the
// abstract class test because the caller is possibly passing
// in a non-abstract subclass.
const specializedClassType = TypeUtils.selfSpecializeClassType(
containingClassType, true);
if (functionType.setParameterType(index, specializedClassType)) {
this._setAnalysisChanged();
}
}
}
}
}
} else {
// There is no annotation, and we can't infer the type.
if (param.name) {
this._addDiagnostic(this._fileInfo.diagnosticSettings.reportUnknownParameterType,
`Type of '${ param.name.nameToken.value }' is unknown`,
param.name);
}
}
});
if (node.returnTypeAnnotation) {
const returnType = this._getTypeOfAnnotation(node.returnTypeAnnotation);
if (functionType.setDeclaredReturnType(returnType)) {
this._setAnalysisChanged();
}
this.walk(node.returnTypeAnnotation);
} else {
let inferredReturnType: Type = UnknownType.create();
if (this._fileInfo.isStubFile) {
// If a return type annotation is missing in a stub file, assume
// it's an "unknown" type. In normal source files, we can infer the
// type from the implementation.
functionType.setDeclaredReturnType(inferredReturnType);
} else {
inferredReturnType = functionType.getInferredReturnType().getType();
}
// Include Any in this check. If "Any" really is desired, it should
// be made explicit through a type annotation.
if (inferredReturnType.isAny()) {
this._addDiagnostic(this._fileInfo.diagnosticSettings.reportUnknownParameterType,
`Inferred return type is unknown`, node.name);
} else if (TypeUtils.containsUnknown(inferredReturnType)) {
this._addDiagnostic(this._fileInfo.diagnosticSettings.reportUnknownParameterType,
`Return type '${ inferredReturnType.asString() }' is partially unknown`,
node.name);
}
}
const functionScope = this._enterScope(node, () => {
const parameters = functionType.getParameters();
assert(parameters.length === node.parameters.length);
// Add the parameters to the scope and bind their types.
parameters.forEach((param, index) => {
const paramNode = node.parameters[index];
if (paramNode.name) {
const specializedParamType = TypeUtils.specializeType(param.type, undefined);
let declaration: Declaration | undefined;
declaration = {
category: SymbolCategory.Parameter,
node: paramNode,
path: this._fileInfo.filePath,
range: convertOffsetsToRange(paramNode.start, paramNode.end, this._fileInfo.lines),
declaredType: specializedParamType
};
assert(paramNode !== undefined && paramNode.name !== undefined);
// If the type contains type variables, specialize them now
// so we convert them to a concrete type (or unknown if there
// is no bound or contraint).
const variadicParamType = this._getVariadicParamType(param.category, specializedParamType);
this._addTypeSourceToNameNode(paramNode.name, variadicParamType, declaration);
// Cache the type for the hover provider. Don't walk
// the default value because it needs to be evaluated
// outside of this scope.
this.walk(paramNode.name);
}
});
// If this function is part of a class, add an implied "super" method.
// TODO - this code assumes the zero-parameter version of super. Another
// approach will be needed to handle the multi-parameter version which
// can even be used outside of a class definition.
let classNode = ParseTreeUtils.getEnclosingClass(node);
if (classNode) {
let classType = AnalyzerNodeInfo.getExpressionType(classNode) as ClassType;
assert(classType !== undefined && classType instanceof ClassType);
let superType = new FunctionType(FunctionTypeFlags.None);
superType.addParameter({
category: ParameterCategory.VarArgList,
name: 'args',
type: UnknownType.create()
});
superType.addParameter({
category: ParameterCategory.VarArgDictionary,
name: 'kwargs',
type: UnknownType.create()
});
if (classType.getBaseClasses().length > 0) {
// TODO - we currently use only the first base class, but we should
// be doing a full MRO search when evaluating super().
let baseClass = classType.getBaseClasses()[0];
if (baseClass.type instanceof ClassType) {
superType.setDeclaredReturnType(new ObjectType(baseClass.type));
} else {
superType.setDeclaredReturnType(UnknownType.create());
}
}
this._addSymbolToPermanentScope('super');
this._addTypeSourceToName('super', superType, DefaultTypeSourceId);
}
this.walk(node.suite);
});
// Validate that the function returns the declared type.
this._validateFunctionReturn(node, functionType, functionScope);
let declaration: Declaration = {
category: containingClassNode ? SymbolCategory.Method : SymbolCategory.Function,
node: node.name,
path: this._fileInfo.filePath,
range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines),
declaredType: decoratedType
};
this._assignTypeToNameNode(node.name, decoratedType, declaration);
if (containingClassNode) {
this._validateMethod(node, functionType);
}
this._updateExpressionTypeForNode(node.name, functionType);
this.walkMultiple(node.decorators);
this._conditionallyReportUnusedName(node.name, true,
this._fileInfo.diagnosticSettings.reportUnusedFunction,
`Function '${ node.name.nameToken.value }' is not accessed`);
return false;
}
visitLambda(node: LambdaNode): boolean {
const functionType = new FunctionType(FunctionTypeFlags.None);
this._enterScope(node, () => {
node.parameters.forEach(param => {
if (param.name) {
// Set the declaration on the node for the definition provider.
const symbol = this._currentScope.lookUpSymbol(param.name.nameToken.value);
if (symbol && symbol.hasDeclarations()) {
AnalyzerNodeInfo.setDeclarations(param.name, symbol.getDeclarations());
}
let declaration: Declaration | undefined;
declaration = {
category: SymbolCategory.Parameter,
node: param,
path: this._fileInfo.filePath,
range: convertOffsetsToRange(param.start, param.end, this._fileInfo.lines)
};
const paramType = UnknownType.create();
this._addTypeSourceToNameNode(param.name, paramType, declaration);
// Cache the type for the hover provider.
this._getTypeOfExpression(param.name);
}
const functionParam: FunctionParameter = {
category: param.category,
name: param.name ? param.name.nameToken.value : undefined,
hasDefault: !!param.defaultValue,
type: UnknownType.create()
};
functionType.addParameter(functionParam);
});
// Infer the return type.
const returnType = this._getTypeOfExpression(node.expression);
functionType.getInferredReturnType().addSource(
returnType, AnalyzerNodeInfo.getTypeSourceId(node.expression));
this.walkChildren(node.expression);
});
// Cache the function type.
this._updateExpressionTypeForNode(node, functionType);
return false;
}
visitCall(node: CallExpressionNode): boolean {
// Calculate and cache the expression and report
// any validation errors.
const returnValue = this._getTypeOfExpression(node);
// If the call indicates that it never returns, mark the
// scope as raising an exception.
if (TypeUtils.isNoReturnType(returnValue)) {
this._currentScope.setAlwaysRaises();
}
return true;
}
visitFor(node: ForNode): boolean {
this.walk(node.iterableExpression);
const iteratorType = this._getTypeOfExpression(node.iterableExpression);
const evaluator = this._createEvaluator();
const iteratedType = evaluator.getTypeFromIterable(
iteratorType, !!node.isAsync, node.iterableExpression, !node.isAsync);
const loopScope = this._enterTemporaryScope(() => {
this._assignTypeToExpression(node.targetExpression, iteratedType, node.targetExpression);
this.walk(node.targetExpression);
this.walk(node.forSuite);
}, true, node);
const elseScope = this._enterTemporaryScope(() => {
if (node.elseSuite) {
this.walk(node.elseSuite);
}
}, true);
if (loopScope.getAlwaysReturnsOrRaises() && elseScope.getAlwaysReturnsOrRaises()) {
// If both an loop and else clauses are executed but they both return or
// raise an exception, mark the current scope as always returning or
// raising an exception.
if (loopScope.getAlwaysRaises() && elseScope.getAlwaysRaises()) {
this._currentScope.setAlwaysRaises();
} else {
this._currentScope.setAlwaysReturns();
}
} else if (loopScope.getAlwaysReturnsOrRaises()) {
elseScope.setUnconditional();
this._mergeToCurrentScope(elseScope);
} else if (elseScope.getAlwaysReturnsOrRaises()) {
loopScope.setUnconditional();
this._mergeToCurrentScope(loopScope);
} else if (!loopScope.getAlwaysReturnsOrRaises() && !elseScope.getAlwaysReturnsOrRaises()) {
const scopeToMerge = Scope.combineConditionalScopes([loopScope, elseScope]);
this._mergeToCurrentScope(scopeToMerge);
}
return false;
}
visitListComprehension(node: ListComprehensionNode): boolean {
// We need to "execute" the comprehension clauses first, even
// though they appear afterward in the syntax. We'll do so
// within a temporary scope so we can throw away the target
// when complete.
this._enterTemporaryScope(() => {
node.comprehensions.forEach(compr => {
if (compr instanceof ListComprehensionForNode) {
this.walk(compr.iterableExpression);
const iteratorType = this._getTypeOfExpression(compr.iterableExpression);
const evaluator = this._createEvaluator();
const iteratedType = evaluator.getTypeFromIterable(
iteratorType, !!compr.isAsync, compr.iterableExpression, false);
this._addNamedTargetToCurrentScope(compr.targetExpression);
this._assignTypeToExpression(compr.targetExpression, iteratedType, compr.iterableExpression);
this.walk(compr.targetExpression);
} else {
this.walk(compr.testExpression);
}
});
this.walk(node.expression);
});
return false;
}
visitIf(node: IfNode): boolean {
this._handleIfWhileCommon(node.testExpression, node.ifSuite,
node.elseSuite, false);
return false;
}
visitWhile(node: WhileNode): boolean {
this._handleIfWhileCommon(node.testExpression, node.whileSuite,
node.elseSuite, true);
return false;
}
visitWith(node: WithNode): boolean {
node.withItems.forEach(item => {
this.walk(item.expression);
});
node.withItems.forEach(item => {
let exprType = this._getTypeOfExpression(item.expression);
if (TypeUtils.isOptionalType(exprType)) {
this._addDiagnostic(
this._fileInfo.diagnosticSettings.reportOptionalContextManager,
`Object of type 'None' cannot be used with 'with'`,
item.expression);
exprType = TypeUtils.removeNoneFromUnion(exprType);
}
const enterMethodName = node.isAsync ? '__aenter__' : '__enter__';
const scopedType = TypeUtils.doForSubtypes(exprType, subtype => {
if (subtype.isAny()) {
return subtype;
}
if (subtype instanceof ObjectType) {
let evaluator = this._createEvaluator();
let memberType = evaluator.getTypeFromObjectMember(item.expression,
subtype, enterMethodName, { method: 'get' });
if (memberType) {
let memberReturnType: Type;
if (memberType instanceof FunctionType) {
memberReturnType = memberType.getEffectiveReturnType();
} else {
memberReturnType = UnknownType.create();
}
// For "async while", an implicit "await" is performed.
if (node.isAsync) {
memberReturnType = evaluator.getTypeFromAwaitable(
memberReturnType, item);
}
return memberReturnType;
}
}
this._addError(`Type ${ subtype.asString() } cannot be used ` +
`with 'with' because it does not implement '${ enterMethodName }'`,
item.expression);
return UnknownType.create();
});
if (item.target) {
this._assignTypeToExpression(item.target, scopedType, item.target);
this.walk(item.target);
}
});
this.walk(node.suite);
return false;
}
visitReturn(node: ReturnNode): boolean {
let declaredReturnType: Type | undefined;
let returnType: Type;
let enclosingFunctionNode = ParseTreeUtils.getEnclosingFunction(node);
if (enclosingFunctionNode) {
let functionType = AnalyzerNodeInfo.getExpressionType(
enclosingFunctionNode) as FunctionType;
if (functionType) {
assert(functionType instanceof FunctionType);
if (functionType.isGenerator()) {
declaredReturnType = TypeUtils.getDeclaredGeneratorReturnType(functionType);
} else {
declaredReturnType = functionType.getDeclaredReturnType();
}
// Ignore this check for abstract methods, which often
// don't actually return any value.
if (functionType.isAbstractMethod()) {
declaredReturnType = undefined;
}
}
}
if (node.returnExpression) {
returnType = this._getTypeOfExpression(node.returnExpression);
} else {
// There is no return expression, so "None" is assumed.
returnType = NoneType.create();
}
let typeSourceId = AnalyzerNodeInfo.getTypeSourceId(node);
this._currentScope.getReturnType().addSource(returnType, typeSourceId);
if (declaredReturnType) {
if (TypeUtils.isNoReturnType(declaredReturnType)) {
this._addError(
`Function with declared return type 'NoReturn' cannot include a return statement`,
node);
} else if (!this._currentScope.getAlwaysReturnsOrRaises()) {
const diagAddendum = new DiagnosticAddendum();
// Specialize the return type in case it contains references to type variables.
// These will be replaced with the corresponding constraint or bound types.
const specializedDeclaredType = TypeUtils.specializeType(declaredReturnType, undefined);
if (!TypeUtils.canAssignType(specializedDeclaredType, returnType, diagAddendum)) {
this._addError(
`Expression of type '${ returnType.asString() }' cannot be assigned ` +
`to return type '${ specializedDeclaredType.asString() }'` +
diagAddendum.getString(),
node.returnExpression ? node.returnExpression : node);
}
}
}
if (!this._currentScope.getAlwaysRaises()) {
this._currentScope.setAlwaysReturns();
}
return true;
}
visitYield(node: YieldExpressionNode) {
let yieldType = this._getTypeOfExpression(node.expression);
const typeSourceId = AnalyzerNodeInfo.getTypeSourceId(node.expression);
this._currentScope.getYieldType().addSource(yieldType, typeSourceId);
// Wrap the yield type in an Iterator.
const iteratorType = ScopeUtils.getBuiltInType(this._currentScope, 'Iterator');
if (iteratorType instanceof ClassType) {
yieldType = new ObjectType(iteratorType.cloneForSpecialization([yieldType]));
} else {
yieldType = UnknownType.create();
}
this._validateYieldType(node, yieldType);
return true;
}
visitYieldFrom(node: YieldFromExpressionNode) {
let yieldType = this._getTypeOfExpression(node.expression);
let typeSourceId = AnalyzerNodeInfo.getTypeSourceId(node.expression);
this._currentScope.getYieldType().addSource(yieldType, typeSourceId);
this._validateYieldType(node, yieldType);
return true;
}
visitBreak(node: BreakNode): boolean {
this._currentScope.setBreaksFromLoop();
return true;
}
visitRaise(node: RaiseNode): boolean {
if (node.typeExpression) {
this._markExpressionAccessed(node.typeExpression);
}
if (node.valueExpression) {
const exceptionType = this._getTypeOfExpression(node.valueExpression);
// TODO - validate that it's an exception type.
}
if (!this._currentScope.getAlwaysReturns()) {
this._currentScope.setAlwaysRaises();
}
return true;
}
visitExcept(node: ExceptNode): boolean {
let exceptionType: Type;
if (node.typeExpression) {
exceptionType = this._getTypeOfExpression(node.typeExpression);
if (node.name) {
// If more than one type was specified for the exception, we'll receive
// a specialized tuple object here.
const tupleType = TypeUtils.getSpecializedTupleType(exceptionType);
if (tupleType && tupleType.getTypeArguments()) {
const entryTypes = tupleType.getTypeArguments()!.map(t => {
return this._validateExceptionType(t, node.typeExpression!);
});
exceptionType = TypeUtils.combineTypes(entryTypes);
} else if (exceptionType instanceof ClassType) {
exceptionType = this._validateExceptionType(
exceptionType, node.typeExpression);
}
let declaration: Declaration = {
category: SymbolCategory.Variable,
node: node.name,
path: this._fileInfo.filePath,
range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines)
};
this._addNamedTargetToCurrentScope(node.name);
this._assignTypeToNameNode(node.name, exceptionType, declaration);
this._updateExpressionTypeForNode(node.name, exceptionType);
}
}
return true;
}
visitTry(node: TryNode): boolean {
let conditionalScopesToMerge: Scope[] = [];
const tryScope = this._enterTemporaryScope(() => {
this.walk(node.trySuite);
});
let allPathsRaise = tryScope.getAlwaysRaises();
let allPathsRaiseOrReturn = tryScope.getAlwaysReturnsOrRaises();
// Clear the "always raises" and "always returns" flags for the try block
// because it may raise an exception before hitting these statements
// and cause code execution to resume within an except clause.
tryScope.clearAlwaysRaises();
tryScope.clearAlwaysReturns();
// Unconditionally merge the try scope into its parent.
this._mergeToCurrentScope(tryScope);
// Analyze the else scope. This is effectively a continuation of
// the try scope, except that it's conditionally executed (only
// if there are no exceptions raised in the try scope).
const elseScope = this._enterTemporaryScope(() => {
if (node.elseSuite) {
this.walk(node.elseSuite);
}
});
// Consider the try/else path, which is executed if there are no exceptions
// raised during execution. Does this path contain any unconditional raise
// or return statements?
if (elseScope.getAlwaysRaises()) {
allPathsRaise = true;
}
if (elseScope.getAlwaysReturnsOrRaises()) {
allPathsRaiseOrReturn = true;
}
conditionalScopesToMerge.push(elseScope);
// Now analyze the exception scopes.
node.exceptClauses.forEach(exceptNode => {
const exceptScope = this._enterTemporaryScope(() => {
this.walk(exceptNode);
});
conditionalScopesToMerge.push(exceptScope);
if (!exceptScope.getAlwaysRaises()) {
allPathsRaise = false;
}
if (!exceptScope.getAlwaysReturnsOrRaises()) {
allPathsRaiseOrReturn = false;
}
});
if (conditionalScopesToMerge.length > 1) {
// Mark the multiple scopes as conditional and merge them.
for (const scope of conditionalScopesToMerge) {
scope.setConditional();
}
this._mergeToCurrentScope(Scope.combineConditionalScopes(conditionalScopesToMerge));
} else if (conditionalScopesToMerge.length === 1) {
// We have only one scope that's contributing, so no need
// to mark it as conditional.
this._mergeToCurrentScope(conditionalScopesToMerge[0]);
}
if (allPathsRaise) {
this._currentScope.setAlwaysRaises();
} else if (allPathsRaiseOrReturn) {
this._currentScope.setAlwaysReturns();
}
if (node.finallySuite) {
this.walk(node.finallySuite);
}
return false;
}
visitAssignment(node: AssignmentNode): boolean {
// Special-case the typing.pyi file, which contains some special
// types that the type analyzer needs to interpret differently.
if (this._handleTypingStubAssignment(node)) {
return false;
}
// Evaluate the type of the right-hand side.
// An assignment of ellipsis means "Any" within a type stub file.
let srcType = this._getTypeOfExpression(node.rightExpression,
this._fileInfo.isStubFile ? EvaluatorFlags.ConvertEllipsisToAny : undefined);
// If a type declaration was provided, note it here.
if (node.typeAnnotationComment) {
const typeHintType = this._getTypeOfAnnotation(node.typeAnnotationComment);
this._declareTypeForExpression(node.leftExpression, typeHintType,
node.typeAnnotationComment, node.rightExpression);
const diagAddendum = new DiagnosticAddendum();
if (!TypeUtils.canAssignType(typeHintType, srcType, diagAddendum)) {
this._addError(`Expression of type '${ srcType.asString() }' cannot be ` +
`assigned to declared type '${ typeHintType.asString() }'` +
diagAddendum.getString(),
node.rightExpression);
srcType = typeHintType;
} else {
// Constrain the resulting type to match the declared type.
srcType = TypeUtils.constrainDeclaredTypeBasedOnAssignedType(typeHintType, srcType);
}
}
// If this is an enum, transform the type as required.
let effectiveType = srcType;