forked from DetachHead/basedpyright
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinder.ts
More file actions
4469 lines (3806 loc) · 183 KB
/
binder.ts
File metadata and controls
4469 lines (3806 loc) · 183 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
/*
* binder.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* A parse tree walker that performs basic name binding (creation of
* scopes and associated symbol tables).
* The binder walks the parse tree by scopes starting at the module
* level. When a new scope is detected, it is pushed onto a list and
* walked separately at a later time. (The exception is a class scope,
* which is immediately walked.) Walking the tree in this manner
* simulates the order in which execution normally occurs in a Python
* file. The binder attempts to statically detect runtime errors that
* would be reported by the python interpreter when executing the code.
* This binder doesn't perform any static type checking.
*/
import { Commands } from '../commands/commands';
import { DiagnosticLevel } from '../common/configOptions';
import { assert, assertNever, fail } from '../common/debug';
import { CreateTypeStubFileAction, Diagnostic, DiagnosticAddendum } from '../common/diagnostic';
import { DiagnosticRule } from '../common/diagnosticRules';
import { stripFileExtension } from '../common/pathUtils';
import { convertTextRangeToRange } from '../common/positionUtils';
import { TextRange, getEmptyRange } from '../common/textRange';
import { Uri } from '../common/uri/uri';
import { LocAddendum, LocMessage } from '../localization/localize';
import {
ArgCategory,
AssertNode,
AssignmentExpressionNode,
AssignmentNode,
AugmentedAssignmentNode,
AwaitNode,
BinaryOperationNode,
BreakNode,
CallNode,
CaseNode,
ClassNode,
ComprehensionNode,
ContinueNode,
DelNode,
ExceptNode,
ExpressionNode,
ForNode,
FunctionNode,
GlobalNode,
IfNode,
ImportAsNode,
ImportFromNode,
IndexNode,
LambdaNode,
MatchNode,
MemberAccessNode,
ModuleNameNode,
ModuleNode,
NameNode,
NonlocalNode,
ParseNode,
ParseNodeType,
PatternAsNode,
PatternCaptureNode,
PatternMappingExpandEntryNode,
RaiseNode,
ReturnNode,
StatementNode,
StringListNode,
StringNode,
SuiteNode,
TernaryNode,
TryNode,
TypeAliasNode,
TypeAnnotationNode,
TypeParameterListNode,
UnaryOperationNode,
WhileNode,
WithNode,
YieldFromNode,
YieldNode,
} from '../parser/parseNodes';
import { KeywordType, OperatorType } from '../parser/tokenizerTypes';
import { AnalyzerFileInfo } from './analyzerFileInfo';
import * as AnalyzerNodeInfo from './analyzerNodeInfo';
import {
CodeFlowReferenceExpressionNode,
FlowAssignment,
FlowBranchLabel,
FlowCall,
FlowCondition,
FlowExhaustedMatch,
FlowFlags,
FlowLabel,
FlowNarrowForPattern,
FlowNode,
FlowPostContextManagerLabel,
FlowPostFinally,
FlowPreFinallyGate,
FlowVariableAnnotation,
FlowWildcardImport,
createKeyForReference,
getUniqueFlowNodeId,
isCodeFlowSupportedForReference,
wildcardImportReferenceKey,
} from './codeFlowTypes';
import {
AliasDeclaration,
ClassDeclaration,
DeclarationType,
FunctionDeclaration,
IntrinsicType,
ModuleLoaderActions,
ParamDeclaration,
SpecialBuiltInClassDeclaration,
TypeAliasDeclaration,
TypeParamDeclaration,
UnresolvedModuleMarker,
VariableDeclaration,
} from './declaration';
import { ImplicitImport, ImportResult, ImportType } from './importResult';
import { getWildcardImportNames } from './importStatementUtils';
import * as ParseTreeUtils from './parseTreeUtils';
import { ParseTreeWalker } from './parseTreeWalker';
import { moduleIsInList } from './pythonPathUtils';
import { NameBindingType, Scope, ScopeType } from './scope';
import { IPythonMode } from './sourceFile';
import * as StaticExpressions from './staticExpressions';
import { Symbol, SymbolFlags, indeterminateSymbolId } from './symbol';
import { isConstantName, isPrivateName, isPrivateOrProtectedName } from './symbolNameUtils';
interface MemberAccessInfo {
classNode: ClassNode;
methodNode: FunctionNode;
classScope: Scope;
isInstanceMember: boolean;
}
interface DeferredBindingTask {
scope: Scope;
codeFlowExpressions: Set<string>;
callback: () => void;
}
interface FinalInfo {
isFinal: boolean;
finalTypeNode: ExpressionNode | undefined;
}
interface ClassVarInfo {
isClassVar: boolean;
classVarTypeNode: ExpressionNode | undefined;
}
interface NarrowExprOptions {
filterForNeverNarrowing?: boolean;
isComplexExpression?: boolean;
allowDiscriminatedNarrowing?: boolean;
}
// For each flow node within an execution context, we'll add a small
// amount to the complexity factor. Without this, the complexity
// calculation fails to take into account large numbers of non-cyclical
// flow nodes. This number is somewhat arbitrary and is tuned empirically.
const flowNodeComplexityContribution = 0.025;
export class Binder extends ParseTreeWalker {
private readonly _fileInfo: AnalyzerFileInfo;
// A queue of deferred analysis operations.
private _deferredBindingTasks: DeferredBindingTask[] = [];
// The current scope in effect.
private _currentScope!: Scope;
// Current control-flow node.
private _currentFlowNode: FlowNode | undefined;
// Current target function declaration, if currently binding
// a function. This allows return and yield statements to be
// added to the function declaration.
private _targetFunctionDeclaration: FunctionDeclaration | undefined;
// Flow node label that is the target of a "break" statement.
private _currentBreakTarget: FlowLabel | undefined;
// Flow node label that is the target of a "continue" statement.
private _currentContinueTarget: FlowLabel | undefined;
// Flow nodes used for if/else and while/else statements.
private _currentTrueTarget: FlowLabel | undefined;
private _currentFalseTarget: FlowLabel | undefined;
// Flow nodes used within try blocks.
private _currentExceptTargets: FlowLabel[] = [];
// Flow nodes used within try/finally flows.
private _finallyTargets: FlowLabel[] = [];
// Flow nodes used for return statements.
private _currentReturnTarget: FlowLabel | undefined;
// Set of expressions within the current execution scope
// and require code flow analysis to resolve.
private _currentScopeCodeFlowExpressions: Set<string> | undefined;
// If we're actively binding a match statement, this is the current
// match expression.
private _currentMatchSubjExpr: ExpressionNode | undefined;
// Aliases of "typing" and "typing_extensions".
private _typingImportAliases: string[] = [];
// Aliases of "sys".
private _sysImportAliases: string[] = [];
// Aliases of "dataclasses".
private _dataclassesImportAliases: string[] = [];
// Map of imports of specific symbols imported from "typing" and "typing_extensions"
// and the names they alias to.
private _typingSymbolAliases: Map<string, string> = new Map<string, string>();
// Map of imports of specific symbols imported from "dataclasses"
// and the names they alias to.
private _dataclassesSymbolAliases: Map<string, string> = new Map<string, string>();
// List of names statically assigned to __all__ symbol.
private _dunderAllNames: string[] | undefined;
// List of string nodes associated with the "__all__" symbol.
private _dunderAllStringNodes: StringNode[] = [];
// One or more statements are manipulating __all__ in a manner that a
// static analyzer doesn't understand.
private _usesUnsupportedDunderAllForm = false;
// Are we currently binding code located within an except block?
private _isInExceptSuite = false;
// Are we currently walking the type arguments to an Annotated type annotation?
private _isInAnnotatedAnnotation = false;
// A list of names assigned to __slots__ within a class.
private _dunderSlotsEntries: StringListNode[] | undefined;
// Flow node that is used for unreachable code.
private static _unreachableFlowNode: FlowNode = {
flags: FlowFlags.Unreachable,
id: getUniqueFlowNodeId(),
};
// Map of symbols at the module level that may be externally
// hidden depending on whether they are listed in the __all__ list.
private _potentialHiddenSymbols = new Map<string, Symbol>();
// Map of symbols at the module level that may be private depending
// on whether they are listed in the __all__ list.
private _potentialPrivateSymbols = new Map<string, Symbol>();
// Estimates the overall complexity of the code flow graph for
// the current function.
private _codeFlowComplexity = 0;
constructor(fileInfo: AnalyzerFileInfo, private _moduleSymbolOnly = false) {
super();
this._fileInfo = fileInfo;
}
bindModule(node: ModuleNode): void {
// We'll assume that if there is no builtins scope provided, we must be
// binding the builtins module itself.
const isBuiltInModule = this._fileInfo.builtinsScope === undefined;
this._addTypingImportAliasesFromBuiltinsScope();
this._createNewScope(
isBuiltInModule ? ScopeType.Builtin : ScopeType.Module,
this._fileInfo.builtinsScope,
/* proxyScope */ undefined,
() => {
AnalyzerNodeInfo.setScope(node, this._currentScope);
AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode!);
// Bind implicit names.
// List taken from https://docs.python.org/3/reference/import.html#__name__
this._addImplicitSymbolToCurrentScope('__name__', node, 'str');
this._addImplicitSymbolToCurrentScope('__loader__', node, 'Any');
this._addImplicitSymbolToCurrentScope('__package__', node, 'str | None');
this._addImplicitSymbolToCurrentScope('__spec__', node, 'Any');
this._addImplicitSymbolToCurrentScope('__path__', node, 'MutableSequence[str]');
this._addImplicitSymbolToCurrentScope('__file__', node, 'str');
this._addImplicitSymbolToCurrentScope('__cached__', node, 'str');
this._addImplicitSymbolToCurrentScope('__annotations__', node, 'dict[str, Any]');
this._addImplicitSymbolToCurrentScope('__dict__', node, 'dict[str, Any]');
this._addImplicitSymbolToCurrentScope('__builtins__', node, 'Any');
this._addImplicitSymbolToCurrentScope('__doc__', node, 'str | None');
if (this._fileInfo.ipythonMode === IPythonMode.CellDocs) {
// this function is automatically available globally inside notebooks.
// https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.display
this._addImplicitSymbolToCurrentScope('display', node, 'IPython.display.display');
}
// Create a start node for the module.
this._currentFlowNode = this._createStartFlowNode();
this._walkStatementsAndReportUnreachable(node.d.statements);
// Associate the code flow node at the end of the module with the module.
AnalyzerNodeInfo.setAfterFlowNode(node, this._currentFlowNode);
AnalyzerNodeInfo.setCodeFlowExpressions(node, this._currentScopeCodeFlowExpressions!);
AnalyzerNodeInfo.setCodeFlowComplexity(node, this._codeFlowComplexity);
}
);
// Perform all analysis that was deferred during the first pass.
this._bindDeferred();
// Use the __all__ list to determine whether any potential private
// symbols should be made externally hidden or private.
this._potentialHiddenSymbols.forEach((symbol, name) => {
if (!this._dunderAllNames?.some((sym) => sym === name)) {
if (this._fileInfo.isStubFile) {
symbol.setIsExternallyHidden();
} else if (this._fileInfo.isInPyTypedPackage) {
symbol.setPrivatePyTypedImport();
} else if (!this._fileInfo.isThirdParty) {
symbol.setPrivateLocalImport();
}
}
});
this._potentialPrivateSymbols.forEach((symbol, name) => {
if (!this._dunderAllNames?.some((sym) => sym === name)) {
symbol.setIsPrivateMember();
}
});
if (this._dunderAllNames) {
AnalyzerNodeInfo.setDunderAllInfo(node, {
names: this._dunderAllNames,
stringNodes: this._dunderAllStringNodes,
usesUnsupportedDunderAllForm: this._usesUnsupportedDunderAllForm,
});
} else {
AnalyzerNodeInfo.setDunderAllInfo(node, /* names */ undefined);
}
// Set __all__ flags on the module symbols.
const scope = AnalyzerNodeInfo.getScope(node);
if (scope && this._dunderAllNames) {
for (const name of this._dunderAllNames) {
scope.symbolTable.get(name)?.setIsInDunderAll();
}
}
}
override visitModule(node: ModuleNode): boolean {
// Tree walking should start with the children of
// the node, so we should never get here.
fail('We should never get here');
return false;
}
override visitSuite(node: SuiteNode): boolean {
this._walkStatementsAndReportUnreachable(node.d.statements);
return false;
}
override visitModuleName(node: ModuleNameNode): boolean {
const importResult = AnalyzerNodeInfo.getImportInfo(node);
assert(importResult !== undefined);
if (importResult.isNativeLib) {
return true;
}
if (!importResult.isImportFound && importResult.importName) {
this._addDiagnostic(
DiagnosticRule.reportMissingImports,
LocMessage.importResolveFailure().format({
importName: importResult.importName,
venv: this._fileInfo.executionEnvironment.name,
}),
node
);
return true;
} else if (importResult.isImplicitlyRelative) {
const diagAddendum = new DiagnosticAddendum();
diagAddendum.addMessage(
LocAddendum.explicitRelativeImportSuggestion().format({ importName: importResult.importName })
);
// TODO: is there a better way to get the package name here? i think this would always match but idk for sure
const currentModuleRegex = /\.[^.]*$/;
if (this._fileInfo.moduleName.match(currentModuleRegex)) {
const fullModuleName = `${this._fileInfo.moduleName.replace(currentModuleRegex, '')}.${
importResult.importName
}`;
diagAddendum.addMessage(LocAddendum.fullPathImportSuggestion().format({ importName: fullModuleName }));
}
this._addDiagnostic(
DiagnosticRule.reportImplicitRelativeImport,
LocMessage.implicitRelativeImport().format({
importName: importResult.importName,
}) + diagAddendum.getString(),
node
);
}
// See if a source file was found but it's not part of a py.typed
// library and no type stub is found.
let reportStubMissing = false;
if (
!importResult.isStubFile &&
importResult.importType === ImportType.ThirdParty &&
!importResult.pyTypedInfo &&
// If the module is allowed as an untyped library, we don't need the stub
!moduleIsInList(this._fileInfo.diagnosticRuleSet.allowedUntypedLibraries, importResult.importName)
) {
reportStubMissing = true;
// If the import is a namespace package, it's possible that all of
// the targeted import symbols are py.typed submodules. In this case,
// suppress the missing stub diagnostic.
if (importResult.isNamespacePackage && node.parent?.nodeType === ParseNodeType.ImportFrom) {
if (
node.parent.d.imports.every((importAs) => {
const implicitImport = importResult.filteredImplicitImports?.get(importAs.d.name.d.value);
return !!implicitImport?.pyTypedInfo;
})
) {
reportStubMissing = false;
}
}
}
if (reportStubMissing) {
/** taken from https://github.com/python/mypy/blob/master/mypy/stubinfo.py */
const packagesWithStubsNotInTypeshed = ['lxml', 'pandas', 'scipy'];
const packageName = importResult.importName.split('.')[0];
const addendum = new DiagnosticAddendum();
if (packagesWithStubsNotInTypeshed.includes(packageName)) {
addendum.addMessage(LocAddendum.installStubs().format({ packageName }));
}
const diagnostic = this._addDiagnostic(
DiagnosticRule.reportMissingTypeStubs,
LocMessage.stubFileMissing().format({ importName: importResult.importName }) + addendum.getString(),
node
);
if (diagnostic) {
// Add a diagnostic action for resolving this diagnostic.
const createTypeStubAction: CreateTypeStubFileAction = {
action: Commands.createTypeStub,
moduleName: importResult.importName,
};
diagnostic.addAction(createTypeStubAction);
}
}
return true;
}
override visitClass(node: ClassNode): boolean {
this.walkMultiple(node.d.decorators);
const classDeclaration: ClassDeclaration = {
type: DeclarationType.Class,
node,
uri: this._fileInfo.fileUri,
range: convertTextRangeToRange(node.d.name, this._fileInfo.lines),
moduleName: this._fileInfo.moduleName,
isInExceptSuite: this._isInExceptSuite,
};
const symbol = this._bindNameToScope(this._currentScope, node.d.name);
if (symbol) {
symbol.addDeclaration(classDeclaration);
}
// Stash the declaration in the parse node for later access.
AnalyzerNodeInfo.setDeclaration(node, classDeclaration);
let typeParamScope: Scope | undefined;
if (node.d.typeParams) {
this.walk(node.d.typeParams);
typeParamScope = AnalyzerNodeInfo.getScope(node.d.typeParams);
}
this.walkMultiple(node.d.arguments);
this._createNewScope(
ScopeType.Class,
typeParamScope ?? this._getNonClassParentScope(),
/* proxyScope */ undefined,
() => {
AnalyzerNodeInfo.setScope(node, this._currentScope);
this._addImplicitSymbolToCurrentScope('__doc__', node, 'str | None');
this._addImplicitSymbolToCurrentScope('__module__', node, 'str');
this._addImplicitSymbolToCurrentScope('__qualname__', node, 'str');
this._dunderSlotsEntries = undefined;
if (!this._moduleSymbolOnly) {
// Analyze the suite.
this.walk(node.d.suite);
}
if (this._dunderSlotsEntries) {
this._addSlotsToCurrentScope(this._dunderSlotsEntries);
}
this._dunderSlotsEntries = undefined;
}
);
this._createAssignmentTargetFlowNodes(node.d.name, /* walkTargets */ false, /* unbound */ false);
return false;
}
override visitFunction(node: FunctionNode): boolean {
this._createVariableAnnotationFlowNode();
AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode!);
const symbol = this._bindNameToScope(this._currentScope, node.d.name);
const containingClassNode = ParseTreeUtils.getEnclosingClass(node, /* stopAtFunction */ true);
const functionDeclaration: FunctionDeclaration = {
type: DeclarationType.Function,
node,
isMethod: !!containingClassNode,
isGenerator: false,
uri: this._fileInfo.fileUri,
range: convertTextRangeToRange(node.d.name, this._fileInfo.lines),
moduleName: this._fileInfo.moduleName,
isInExceptSuite: this._isInExceptSuite,
};
if (symbol) {
symbol.addDeclaration(functionDeclaration);
}
// Stash the declaration in the parse node for later access.
AnalyzerNodeInfo.setDeclaration(node, functionDeclaration);
// Walk the default values prior to the type parameters.
node.d.params.forEach((param) => {
if (param.d.defaultValue) {
this.walk(param.d.defaultValue);
}
});
let typeParamScope: Scope | undefined;
if (node.d.typeParams) {
this.walk(node.d.typeParams);
typeParamScope = AnalyzerNodeInfo.getScope(node.d.typeParams);
}
this.walkMultiple(node.d.decorators);
node.d.params.forEach((param) => {
if (param.d.annotation) {
this.walk(param.d.annotation);
}
if (param.d.annotationComment) {
this.walk(param.d.annotationComment);
}
});
if (node.d.returnAnnotation) {
this.walk(node.d.returnAnnotation);
}
if (node.d.funcAnnotationComment) {
this.walk(node.d.funcAnnotationComment);
}
// Don't walk the body of the function until we're done analyzing
// the current scope.
this._createNewScope(
ScopeType.Function,
typeParamScope ?? this._getNonClassParentScope(),
/* proxyScope */ undefined,
() => {
AnalyzerNodeInfo.setScope(node, this._currentScope);
const enclosingClass = ParseTreeUtils.getEnclosingClass(node);
if (enclosingClass) {
// Add the implicit "__class__" symbol described in PEP 3135.
this._addImplicitSymbolToCurrentScope('__class__', node, '__class__');
}
this._deferBinding(() => {
// Create a start node for the function.
this._currentFlowNode = this._createStartFlowNode();
this._codeFlowComplexity = 0;
node.d.params.forEach((paramNode) => {
if (paramNode.d.name) {
const symbol = this._bindNameToScope(this._currentScope, paramNode.d.name);
if (symbol) {
const paramDeclaration: ParamDeclaration = {
type: DeclarationType.Param,
node: paramNode,
uri: this._fileInfo.fileUri,
range: convertTextRangeToRange(paramNode, this._fileInfo.lines),
moduleName: this._fileInfo.moduleName,
isInExceptSuite: this._isInExceptSuite,
};
symbol.addDeclaration(paramDeclaration);
AnalyzerNodeInfo.setDeclaration(paramNode.d.name, paramDeclaration);
}
this._createFlowAssignment(paramNode.d.name);
}
});
this._targetFunctionDeclaration = functionDeclaration;
this._currentReturnTarget = this._createBranchLabel();
// Walk the statements that make up the function.
this.walk(node.d.suite);
this._targetFunctionDeclaration = undefined;
// Associate the code flow node at the end of the suite with
// the suite.
AnalyzerNodeInfo.setAfterFlowNode(node.d.suite, this._currentFlowNode);
// Compute the final return flow node and associate it with
// the function's parse node. If this node is unreachable, then
// the function never returns.
this._addAntecedent(this._currentReturnTarget, this._currentFlowNode);
const returnFlowNode = this._finishFlowLabel(this._currentReturnTarget);
AnalyzerNodeInfo.setAfterFlowNode(node, returnFlowNode);
AnalyzerNodeInfo.setCodeFlowExpressions(node, this._currentScopeCodeFlowExpressions!);
AnalyzerNodeInfo.setCodeFlowComplexity(node, this._codeFlowComplexity);
});
}
);
this._createAssignmentTargetFlowNodes(node.d.name, /* walkTargets */ false, /* unbound */ false);
// We'll walk the child nodes in a deferred manner, so don't walk them now.
return false;
}
override visitLambda(node: LambdaNode): boolean {
this._createVariableAnnotationFlowNode();
AnalyzerNodeInfo.setFlowNode(node, this._currentFlowNode!);
// Analyze the parameter defaults in the context of the parent's scope
// before we add any names from the function's scope.
node.d.params.forEach((param) => {
if (param.d.defaultValue) {
this.walk(param.d.defaultValue);
}
});
this._createNewScope(ScopeType.Function, this._getNonClassParentScope(), /* proxyScope */ undefined, () => {
AnalyzerNodeInfo.setScope(node, this._currentScope);
this._deferBinding(() => {
// Create a start node for the lambda.
this._currentFlowNode = this._createStartFlowNode();
node.d.params.forEach((paramNode) => {
if (paramNode.d.name) {
const symbol = this._bindNameToScope(this._currentScope, paramNode.d.name);
if (symbol) {
const paramDeclaration: ParamDeclaration = {
type: DeclarationType.Param,
node: paramNode,
uri: this._fileInfo.fileUri,
range: convertTextRangeToRange(paramNode, this._fileInfo.lines),
moduleName: this._fileInfo.moduleName,
isInExceptSuite: this._isInExceptSuite,
};
symbol.addDeclaration(paramDeclaration);
AnalyzerNodeInfo.setDeclaration(paramNode.d.name, paramDeclaration);
}
this._createFlowAssignment(paramNode.d.name);
this.walk(paramNode.d.name);
AnalyzerNodeInfo.setFlowNode(paramNode, this._currentFlowNode!);
}
});
// Walk the expression that make up the lambda body.
this.walk(node.d.expr);
AnalyzerNodeInfo.setCodeFlowExpressions(node, this._currentScopeCodeFlowExpressions!);
});
});
// We'll walk the child nodes in a deferred manner.
return false;
}
override visitCall(node: CallNode): boolean {
this._disableTrueFalseTargets(() => {
this.walk(node.d.leftExpr);
const sortedArgs = ParseTreeUtils.getArgsByRuntimeOrder(node);
sortedArgs.forEach((argNode) => {
if (this._currentFlowNode) {
AnalyzerNodeInfo.setFlowNode(argNode, this._currentFlowNode);
}
this.walk(argNode);
});
});
// Create a call flow node. We'll skip this if the call is part of
// a decorator. We assume that decorators are not NoReturn functions.
// There are libraries that make extensive use of unannotated decorators,
// and this can lead to a performance issue when walking the control
// flow graph if we need to evaluate every decorator.
if (!ParseTreeUtils.isNodeContainedWithinNodeType(node, ParseNodeType.Decorator)) {
// Skip if we're in an 'Annotated' annotation because this creates
// problems for "No Return" return type analysis when annotation
// evaluation is deferred.
if (!this._isInAnnotatedAnnotation) {
this._createCallFlowNode(node);
}
}
// Is this an manipulation of dunder all?
if (
this._currentScope.type === ScopeType.Module &&
node.d.leftExpr.nodeType === ParseNodeType.MemberAccess &&
node.d.leftExpr.d.leftExpr.nodeType === ParseNodeType.Name &&
node.d.leftExpr.d.leftExpr.d.value === '__all__'
) {
let emitDunderAllWarning = true;
// Is this a call to "__all__.extend()"?
if (node.d.leftExpr.d.member.d.value === 'extend' && node.d.args.length === 1) {
const argExpr = node.d.args[0].d.valueExpr;
// Is this a call to "__all__.extend([<list>])"?
if (argExpr.nodeType === ParseNodeType.List) {
if (
argExpr.d.items.every((listEntryNode) => {
if (
listEntryNode.nodeType === ParseNodeType.StringList &&
listEntryNode.d.strings.length === 1 &&
listEntryNode.d.strings[0].nodeType === ParseNodeType.String
) {
this._dunderAllNames?.push(listEntryNode.d.strings[0].d.value);
this._dunderAllStringNodes?.push(listEntryNode.d.strings[0]);
return true;
}
return false;
})
) {
emitDunderAllWarning = false;
}
} else if (
argExpr.nodeType === ParseNodeType.MemberAccess &&
argExpr.d.leftExpr.nodeType === ParseNodeType.Name &&
argExpr.d.member.d.value === '__all__'
) {
// Is this a call to "__all__.extend(<mod>.__all__)"?
const namesToAdd = this._getDunderAllNamesFromImport(argExpr.d.leftExpr.d.value);
if (namesToAdd && namesToAdd.length > 0) {
namesToAdd.forEach((name) => {
this._dunderAllNames?.push(name);
});
}
emitDunderAllWarning = false;
}
} else if (node.d.leftExpr.d.member.d.value === 'remove' && node.d.args.length === 1) {
// Is this a call to "__all__.remove()"?
const argExpr = node.d.args[0].d.valueExpr;
if (
argExpr.nodeType === ParseNodeType.StringList &&
argExpr.d.strings.length === 1 &&
argExpr.d.strings[0].nodeType === ParseNodeType.String &&
this._dunderAllNames
) {
this._dunderAllNames = this._dunderAllNames.filter((name) => name !== argExpr.d.strings[0].d.value);
this._dunderAllStringNodes = this._dunderAllStringNodes.filter(
(node) => node.d.value !== argExpr.d.strings[0].d.value
);
emitDunderAllWarning = false;
}
} else if (node.d.leftExpr.d.member.d.value === 'append' && node.d.args.length === 1) {
// Is this a call to "__all__.append()"?
const argExpr = node.d.args[0].d.valueExpr;
if (
argExpr.nodeType === ParseNodeType.StringList &&
argExpr.d.strings.length === 1 &&
argExpr.d.strings[0].nodeType === ParseNodeType.String
) {
this._dunderAllNames?.push(argExpr.d.strings[0].d.value);
this._dunderAllStringNodes?.push(argExpr.d.strings[0]);
emitDunderAllWarning = false;
}
}
if (emitDunderAllWarning) {
this._usesUnsupportedDunderAllForm = true;
this._addDiagnostic(
DiagnosticRule.reportUnsupportedDunderAll,
LocMessage.unsupportedDunderAllOperation(),
node
);
}
}
return false;
}
override visitTypeParameterList(node: TypeParameterListNode): boolean {
const typeParamScope = new Scope(ScopeType.TypeParameter, this._getNonClassParentScope(), this._currentScope);
node.d.params.forEach((param) => {
if (param.d.boundExpr) {
this.walk(param.d.boundExpr);
}
});
const typeParamsSeen = new Set<string>();
node.d.params.forEach((param) => {
const name = param.d.name;
const symbol = typeParamScope.addSymbol(name.d.value, SymbolFlags.None);
const paramDeclaration: TypeParamDeclaration = {
type: DeclarationType.TypeParam,
node: param,
uri: this._fileInfo.fileUri,
range: convertTextRangeToRange(node, this._fileInfo.lines),
moduleName: this._fileInfo.moduleName,
isInExceptSuite: this._isInExceptSuite,
};
symbol.addDeclaration(paramDeclaration);
AnalyzerNodeInfo.setDeclaration(name, paramDeclaration);
if (typeParamsSeen.has(name.d.value)) {
this._addSyntaxError(
LocMessage.typeParameterExistingTypeParameter().format({ name: name.d.value }),
name
);
} else {
typeParamsSeen.add(name.d.value);
}
});
node.d.params.forEach((param) => {
if (param.d.defaultExpr) {
this.walk(param.d.defaultExpr);
}
});
AnalyzerNodeInfo.setScope(node, typeParamScope);
return false;
}
override visitTypeAlias(node: TypeAliasNode): boolean {
this._bindNameToScope(this._currentScope, node.d.name);
this.walk(node.d.name);
let typeParamScope: Scope | undefined;
if (node.d.typeParams) {
this.walk(node.d.typeParams);
typeParamScope = AnalyzerNodeInfo.getScope(node.d.typeParams);
}
const typeAliasDeclaration: TypeAliasDeclaration = {
type: DeclarationType.TypeAlias,
node,
uri: this._fileInfo.fileUri,
range: convertTextRangeToRange(node.d.name, this._fileInfo.lines),
moduleName: this._fileInfo.moduleName,
isInExceptSuite: this._isInExceptSuite,
docString: this._getVariableDocString(node.d.expr),
};
const symbol = this._bindNameToScope(this._currentScope, node.d.name);
if (symbol) {
symbol.addDeclaration(typeAliasDeclaration);
}
// Stash the declaration in the parse node for later access.
AnalyzerNodeInfo.setDeclaration(node, typeAliasDeclaration);
this._createAssignmentTargetFlowNodes(node.d.name, /* walkTargets */ true, /* unbound */ false);
const prevScope = this._currentScope;
this._currentScope = typeParamScope ?? this._currentScope;
this.walk(node.d.expr);
this._currentScope = prevScope;
return false;
}
override visitAssignment(node: AssignmentNode): boolean {
if (this._handleTypingStubAssignmentOrAnnotation(node)) {
return false;
}
this._bindPossibleTupleNamedTarget(node.d.leftExpr);
if (node.d.annotationComment) {
this.walk(node.d.annotationComment);
this._addTypeDeclarationForVariable(node.d.leftExpr, node.d.annotationComment);
}
if (node.d.chainedAnnotationComment) {
this._addDiagnostic(
DiagnosticRule.reportInvalidTypeForm,
LocMessage.annotationNotSupported(),
node.d.chainedAnnotationComment
);
}
// If the assignment target base expression is potentially a
// TypedDict, add the base expression to the flow expressions set
// to accommodate TypedDict type narrowing.
if (node.d.leftExpr.nodeType === ParseNodeType.Index) {
const target = node.d.leftExpr;
if (
target.d.items.length === 1 &&
!target.d.trailingComma &&
target.d.items[0].d.valueExpr.nodeType === ParseNodeType.StringList
) {
if (isCodeFlowSupportedForReference(target.d.leftExpr)) {
const baseExprReferenceKey = createKeyForReference(target.d.leftExpr);
this._currentScopeCodeFlowExpressions!.add(baseExprReferenceKey);
}
}
}
this.walk(node.d.rightExpr);
let isPossibleTypeAlias = true;
if (ParseTreeUtils.getEnclosingFunction(node)) {
// We will assume that type aliases are defined only at the module level
// or as class variables, not as local variables within a function.
isPossibleTypeAlias = false;
} else if (node.d.rightExpr.nodeType === ParseNodeType.Call && this._fileInfo.isTypingStubFile) {
// Some special built-in types defined in typing.pyi use
// assignments of the form List = _Alias(). We don't want to
// treat these as type aliases.
isPossibleTypeAlias = false;
} else if (ParseTreeUtils.isWithinLoop(node)) {
// Assume that it's not a type alias if it's within a loop.
isPossibleTypeAlias = false;
}
this._addInferredTypeAssignmentForVariable(node.d.leftExpr, node.d.rightExpr, isPossibleTypeAlias);
// If we didn't create assignment target flow nodes above, do so now.
this._createAssignmentTargetFlowNodes(node.d.leftExpr, /* walkTargets */ true, /* unbound */ false);
// Is this an assignment to dunder all?
if (this._currentScope.type === ScopeType.Module) {
if (
(node.d.leftExpr.nodeType === ParseNodeType.Name && node.d.leftExpr.d.value === '__all__') ||
(node.d.leftExpr.nodeType === ParseNodeType.TypeAnnotation &&
node.d.leftExpr.d.valueExpr.nodeType === ParseNodeType.Name &&
node.d.leftExpr.d.valueExpr.d.value === '__all__')
) {
const expr = node.d.rightExpr;
this._dunderAllNames = [];
let emitDunderAllWarning = false;
if (expr.nodeType === ParseNodeType.List) {
expr.d.items.forEach((listEntryNode) => {
if (
listEntryNode.nodeType === ParseNodeType.StringList &&
listEntryNode.d.strings.length === 1 &&
listEntryNode.d.strings[0].nodeType === ParseNodeType.String
) {
this._dunderAllNames!.push(listEntryNode.d.strings[0].d.value);
this._dunderAllStringNodes.push(listEntryNode.d.strings[0]);
} else {
emitDunderAllWarning = true;
}
});
} else if (expr.nodeType === ParseNodeType.Tuple) {
expr.d.items.forEach((tupleEntryNode) => {
if (
tupleEntryNode.nodeType === ParseNodeType.StringList &&
tupleEntryNode.d.strings.length === 1 &&
tupleEntryNode.d.strings[0].nodeType === ParseNodeType.String
) {