-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
sourceFile.ts
1398 lines (1196 loc) · 56.9 KB
/
sourceFile.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
/*
* sourceFile.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* Class that represents a single Python source or stub file.
*/
import { isMainThread } from 'worker_threads';
import { OperationCanceledException } from '../common/cancellationUtils';
import { appendArray } from '../common/collectionUtils';
import { ConfigOptions, ExecutionEnvironment, getBasicDiagnosticRuleSet } from '../common/configOptions';
import { ConsoleInterface, StandardConsole } from '../common/console';
import { assert } from '../common/debug';
import { Diagnostic, DiagnosticCategory, TaskListToken, convertLevelToCategory } from '../common/diagnostic';
import { DiagnosticRule } from '../common/diagnosticRules';
import { DiagnosticSink, TextRangeDiagnosticSink } from '../common/diagnosticSink';
import { ServiceProvider } from '../common/extensibility';
import { FileSystem } from '../common/fileSystem';
import { LogTracker, getPathForLogging } from '../common/logTracker';
import { stripFileExtension } from '../common/pathUtils';
import { convertOffsetsToRange, convertTextRangeToRange } from '../common/positionUtils';
import { ServiceKeys } from '../common/serviceProviderExtensions';
import * as StringUtils from '../common/stringUtils';
import { Range, TextRange, getEmptyRange } from '../common/textRange';
import { TextRangeCollection } from '../common/textRangeCollection';
import { Duration, timingStats } from '../common/timing';
import { Uri } from '../common/uri/uri';
import { Localizer } from '../localization/localize';
import { ModuleNode } from '../parser/parseNodes';
import { IParser, ModuleImport, ParseOptions, ParseResults, Parser } from '../parser/parser';
import { IgnoreComment } from '../parser/tokenizer';
import { Token } from '../parser/tokenizerTypes';
import { AnalyzerFileInfo, ImportLookup } from './analyzerFileInfo';
import * as AnalyzerNodeInfo from './analyzerNodeInfo';
import { Binder } from './binder';
import { Checker } from './checker';
import { CircularDependency } from './circularDependency';
import * as CommentUtils from './commentUtils';
import { ImportResolver } from './importResolver';
import { ImportResult } from './importResult';
import { ParseTreeCleanerWalker } from './parseTreeCleaner';
import { Scope } from './scope';
import { SourceMapper } from './sourceMapper';
import { SymbolTable } from './symbol';
import { TestWalker } from './testWalker';
import { TypeEvaluator } from './typeEvaluatorTypes';
// Limit the number of import cycles tracked per source file.
const _maxImportCyclesPerFile = 4;
// Allow files up to 50MB in length, same as VS Code.
// https://github.com/microsoft/vscode/blob/1e750a7514f365585d8dab1a7a82e0938481ea2f/src/vs/editor/common/model/textModel.ts#L194
const _maxSourceFileSize = 50 * 1024 * 1024;
interface ResolveImportResult {
imports: ImportResult[];
builtinsImportResult?: ImportResult | undefined;
}
// Indicates whether IPython syntax is supported and if so, what
// type of notebook support is in use.
export enum IPythonMode {
// Not a notebook. This is the only falsy enum value, so you
// can test if IPython is supported via "if (ipythonMode)"
None = 0,
// Each cell is its own document.
CellDocs,
}
class WriteableData {
// Number that is incremented every time the diagnostics
// are updated.
diagnosticVersion = 0;
// Generation count of the file contents. When the contents
// change, this is incremented.
fileContentsVersion = 0;
// Length and hash of the file the last time it was read from disk.
lastFileContentLength: number | undefined = undefined;
lastFileContentHash: number | undefined = undefined;
// Client's version of the file. Undefined implies that contents
// need to be read from disk.
clientDocumentContents: string | undefined;
clientDocumentVersion: number | undefined;
// Version of file contents that have been analyzed.
analyzedFileContentsVersion = -1;
// Do we need to walk the parse tree and clean
// the binder information hanging from it?
parseTreeNeedsCleaning = false;
parseResults: ParseResults | undefined;
moduleSymbolTable: SymbolTable | undefined;
// Reentrancy check for binding.
isBindingInProgress = false;
// Diagnostics generated during different phases of analysis.
parseDiagnostics: Diagnostic[] = [];
commentDiagnostics: Diagnostic[] = [];
bindDiagnostics: Diagnostic[] = [];
checkerDiagnostics: Diagnostic[] = [];
typeIgnoreLines = new Map<number, IgnoreComment>();
typeIgnoreAll: IgnoreComment | undefined;
pyrightIgnoreLines = new Map<number, IgnoreComment>();
// Accumulated and filtered diagnostics that combines all of the
// above information. This needs to be recomputed any time the
// above change.
accumulatedDiagnostics: Diagnostic[] = [];
// Circular dependencies that have been reported in this file.
circularDependencies: CircularDependency[] = [];
noCircularDependencyConfirmed = false;
// Did we hit the maximum import depth?
hitMaxImportDepth: number | undefined;
// Do we need to perform a binding step?
isBindingNeeded = true;
// Do we have valid diagnostic results from a checking pass?
isCheckingNeeded = true;
// Time (in ms) that the last check() call required for this file.
checkTime: number | undefined;
// Information about implicit and explicit imports from this file.
imports: ImportResult[] | undefined;
builtinsImport: ImportResult | undefined;
// True if the file appears to have been deleted.
isFileDeleted = false;
debugPrint() {
return `WritableData:
diagnosticVersion=${this.diagnosticVersion},
noCircularDependencyConfirmed=${this.noCircularDependencyConfirmed},
isBindingNeeded=${this.isBindingNeeded},
isBindingInProgress=${this.isBindingInProgress},
isCheckingNeeded=${this.isCheckingNeeded},
isFileDeleted=${this.isFileDeleted},
hitMaxImportDepth=${this.hitMaxImportDepth},
parseTreeNeedsCleaning=${this.parseTreeNeedsCleaning},
fileContentsVersion=${this.fileContentsVersion},
analyzedFileContentsVersion=${this.analyzedFileContentsVersion},
clientDocumentVersion=${this.clientDocumentVersion},
lastFileContentLength=${this.lastFileContentLength},
lastFileContentHash=${this.lastFileContentHash},
typeIgnoreAll=${this.typeIgnoreAll},
imports=${this.imports?.length},
builtinsImport=${this.builtinsImport?.importName},
circularDependencies=${this.circularDependencies?.length},
parseDiagnostics=${this.parseDiagnostics?.length},
commentDiagnostics=${this.commentDiagnostics?.length},
bindDiagnostics=${this.bindDiagnostics?.length},
checkerDiagnostics=${this.checkerDiagnostics?.length},
accumulatedDiagnostics=${this.accumulatedDiagnostics?.length},
typeIgnoreLines=${this.typeIgnoreLines?.size},
pyrightIgnoreLines=${this.pyrightIgnoreLines?.size},
checkTime=${this.checkTime},
clientDocumentContents=${this.clientDocumentContents?.length},
parseResults=${this.parseResults?.parseTree.length}`;
}
}
export interface SourceFileEditMode {
readonly isEditMode: boolean;
}
export class SourceFile {
// Data that changes when the source file changes.
private _writableData = new WriteableData();
// Console interface to use for debugging.
private _console: ConsoleInterface;
// Uri unique to this file within the workspace. May not represent
// a real file on disk.
private readonly _uri: Uri;
// Period-delimited import path for the module.
private _moduleName: string;
// True if file is a type-hint (.pyi) file versus a python
// (.py) file.
private readonly _isStubFile: boolean;
// True if the file was imported as a third-party import.
private readonly _isThirdPartyImport: boolean;
// True if the file is the "typing.pyi" file, which needs
// special-case handling.
private readonly _isTypingStubFile: boolean;
// True if the file is the "typing_extensions.pyi" file, which needs
// special-case handling.
private readonly _isTypingExtensionsStubFile: boolean;
// True if the file is the "_typeshed.pyi" file, which needs special-
// case handling.
private readonly _isTypeshedStubFile: boolean;
// True if the file one of the other built-in stub files
// that require special-case handling: "collections.pyi",
// "dataclasses.pyi", "abc.pyi", "asyncio/coroutines.pyi".
private readonly _isBuiltInStubFile: boolean;
// True if the file is part of a package that contains a
// "py.typed" file.
private readonly _isThirdPartyPyTypedPresent: boolean;
private readonly _editMode: SourceFileEditMode;
// Settings that control which diagnostics should be output. The rules
// are initialized to the basic set. They should be updated after the
// the file is parsed.
private _diagnosticRuleSet = getBasicDiagnosticRuleSet();
// Indicate whether this file is for ipython or not.
private _ipythonMode = IPythonMode.None;
private _logTracker: LogTracker;
private _preEditData: WriteableData | undefined;
readonly fileSystem: FileSystem;
constructor(
readonly serviceProvider: ServiceProvider,
uri: Uri,
moduleName: string,
isThirdPartyImport: boolean,
isThirdPartyPyTypedPresent: boolean,
editMode: SourceFileEditMode,
console?: ConsoleInterface,
logTracker?: LogTracker,
ipythonMode?: IPythonMode
) {
this.fileSystem = serviceProvider.get(ServiceKeys.fs);
this._console = console || new StandardConsole();
this._editMode = editMode;
this._uri = uri;
this._moduleName = moduleName;
this._isStubFile = uri.hasExtension('.pyi');
this._isThirdPartyImport = isThirdPartyImport;
this._isThirdPartyPyTypedPresent = isThirdPartyPyTypedPresent;
const fileName = uri.fileName;
this._isTypingStubFile =
this._isStubFile && (this._uri.pathEndsWith('stdlib/typing.pyi') || fileName === 'typing_extensions.pyi');
this._isTypingExtensionsStubFile = this._isStubFile && fileName === 'typing_extensions.pyi';
this._isTypeshedStubFile = this._isStubFile && this._uri.pathEndsWith('stdlib/_typeshed/__init__.pyi');
this._isBuiltInStubFile = false;
if (this._isStubFile) {
if (
this._uri.pathEndsWith('stdlib/collections/__init__.pyi') ||
this._uri.pathEndsWith('stdlib/asyncio/futures.pyi') ||
this._uri.pathEndsWith('stdlib/asyncio/tasks.pyi') ||
this._uri.pathEndsWith('stdlib/builtins.pyi') ||
this._uri.pathEndsWith('stdlib/_importlib_modulespec.pyi') ||
this._uri.pathEndsWith('stdlib/dataclasses.pyi') ||
this._uri.pathEndsWith('stdlib/abc.pyi') ||
this._uri.pathEndsWith('stdlib/enum.pyi') ||
this._uri.pathEndsWith('stdlib/queue.pyi') ||
this._uri.pathEndsWith('stdlib/types.pyi')
) {
this._isBuiltInStubFile = true;
}
}
// 'FG' or 'BG' based on current thread.
this._logTracker = logTracker ?? new LogTracker(console, isMainThread ? 'FG' : 'BG');
this._ipythonMode = ipythonMode ?? IPythonMode.None;
}
getIPythonMode(): IPythonMode {
return this._ipythonMode;
}
getUri(): Uri {
return this._uri;
}
getModuleName(): string {
if (this._moduleName) {
return this._moduleName;
}
// Synthesize a module name using the file path.
return stripFileExtension(this._uri.fileName);
}
setModuleName(name: string) {
this._moduleName = name;
}
getDiagnosticVersion(): number {
return this._writableData.diagnosticVersion;
}
isStubFile() {
return this._isStubFile;
}
isThirdPartyPyTypedPresent() {
return this._isThirdPartyPyTypedPresent;
}
// Returns a list of cached diagnostics from the latest analysis job.
// If the prevVersion is specified, the method returns undefined if
// the diagnostics haven't changed.
getDiagnostics(options: ConfigOptions, prevDiagnosticVersion?: number): Diagnostic[] | undefined {
if (this._writableData.diagnosticVersion === prevDiagnosticVersion) {
return undefined;
}
return this._writableData.accumulatedDiagnostics;
}
getImports(): ImportResult[] {
return this._writableData.imports || [];
}
getBuiltinsImport(): ImportResult | undefined {
return this._writableData.builtinsImport;
}
getModuleSymbolTable(): SymbolTable | undefined {
return this._writableData.moduleSymbolTable;
}
getCheckTime() {
return this._writableData.checkTime;
}
restore(): string | undefined {
// If we had an edit, return our text.
if (this._preEditData) {
const text = this._writableData.clientDocumentContents!;
this._writableData = this._preEditData;
this._preEditData = undefined;
return text;
}
return undefined;
}
// Indicates whether the contents of the file have changed since
// the last analysis was performed.
didContentsChangeOnDisk(): boolean {
// If this is an open file any content changes will be
// provided through the editor. We can assume contents
// didn't change without us knowing about them.
if (this._writableData.clientDocumentContents) {
return false;
}
// If the file was never read previously, no need to check for a change.
if (this._writableData.lastFileContentLength === undefined) {
return false;
}
// Read in the latest file contents and see if the hash matches
// that of the previous contents.
try {
// Read the file's contents.
if (this.fileSystem.existsSync(this._uri)) {
const fileContents = this.fileSystem.readFileSync(this._uri, 'utf8');
if (fileContents.length !== this._writableData.lastFileContentLength) {
return true;
}
if (StringUtils.hashString(fileContents) !== this._writableData.lastFileContentHash) {
return true;
}
} else {
// No longer exists, so yes it has changed.
return true;
}
} catch (error) {
return true;
}
return false;
}
// Drop parse and binding info to save memory. It is used
// in cases where memory is low. When info is needed, the file
// will be re-parsed and rebound.
dropParseAndBindInfo(): void {
this._fireFileDirtyEvent();
this._writableData.parseResults = undefined;
this._writableData.moduleSymbolTable = undefined;
this._writableData.isBindingNeeded = true;
}
markDirty(): void {
this._writableData.fileContentsVersion++;
this._writableData.noCircularDependencyConfirmed = false;
this._writableData.isCheckingNeeded = true;
this._writableData.isBindingNeeded = true;
this._writableData.moduleSymbolTable = undefined;
this._fireFileDirtyEvent();
}
markReanalysisRequired(forceRebinding: boolean): void {
// Keep the parse info, but reset the analysis to the beginning.
this._writableData.isCheckingNeeded = true;
this._writableData.noCircularDependencyConfirmed = false;
// If the file contains a wildcard import or __all__ symbols,
// we need to rebind because a dependent import may have changed.
if (this._writableData.parseResults) {
if (
this._writableData.parseResults.containsWildcardImport ||
AnalyzerNodeInfo.getDunderAllInfo(this._writableData.parseResults.parseTree) !== undefined ||
forceRebinding
) {
// We don't need to rebuild index data since wildcard
// won't affect user file indices. User file indices
// don't contain import alias info.
this._writableData.parseTreeNeedsCleaning = true;
this._writableData.isBindingNeeded = true;
this._writableData.moduleSymbolTable = undefined;
}
}
}
getFileContentsVersion() {
return this._writableData.fileContentsVersion;
}
getClientVersion() {
return this._writableData.clientDocumentVersion;
}
getOpenFileContents() {
return this._writableData.clientDocumentContents;
}
getFileContent(): string | undefined {
// Get current buffer content if the file is opened.
const openFileContent = this.getOpenFileContents();
if (openFileContent !== undefined) {
return openFileContent;
}
// Otherwise, get content from file system.
try {
// Check the file's length before attempting to read its full contents.
const fileStat = this.fileSystem.statSync(this._uri);
if (fileStat.size > _maxSourceFileSize) {
this._console.error(
`File length of "${this._uri}" is ${fileStat.size} ` +
`which exceeds the maximum supported file size of ${_maxSourceFileSize}`
);
throw new Error('File larger than max');
}
return this.fileSystem.readFileSync(this._uri, 'utf8');
} catch (error) {
return undefined;
}
}
setClientVersion(version: number | null, contents: string): void {
// Save pre edit state if in edit mode.
this._cachePreEditState();
if (version === null) {
this._writableData.clientDocumentVersion = undefined;
this._writableData.clientDocumentContents = undefined;
} else {
this._writableData.clientDocumentVersion = version;
this._writableData.clientDocumentContents = contents;
const contentsHash = StringUtils.hashString(contents);
// Have the contents of the file changed?
if (
contents.length !== this._writableData.lastFileContentLength ||
contentsHash !== this._writableData.lastFileContentHash
) {
this.markDirty();
}
this._writableData.lastFileContentLength = contents.length;
this._writableData.lastFileContentHash = contentsHash;
this._writableData.isFileDeleted = false;
}
}
prepareForClose() {
this._fireFileDirtyEvent();
}
isFileDeleted() {
return this._writableData.isFileDeleted;
}
isParseRequired() {
return (
!this._writableData.parseResults ||
this._writableData.analyzedFileContentsVersion !== this._writableData.fileContentsVersion
);
}
isBindingRequired() {
if (this._writableData.isBindingInProgress) {
return false;
}
if (this.isParseRequired()) {
return true;
}
return this._writableData.isBindingNeeded;
}
isCheckingRequired() {
return this._writableData.isCheckingNeeded;
}
getParseResults(): ParseResults | undefined {
if (!this.isParseRequired()) {
return this._writableData.parseResults;
}
return undefined;
}
// Adds a new circular dependency for this file but only if
// it hasn't already been added.
addCircularDependency(configOptions: ConfigOptions, circDependency: CircularDependency) {
let updatedDependencyList = false;
// Some topologies can result in a massive number of cycles. We'll cut it off.
if (this._writableData.circularDependencies.length < _maxImportCyclesPerFile) {
if (!this._writableData.circularDependencies.some((dep) => dep.isEqual(circDependency))) {
this._writableData.circularDependencies.push(circDependency);
updatedDependencyList = true;
}
}
if (updatedDependencyList) {
this._recomputeDiagnostics(configOptions);
}
}
setNoCircularDependencyConfirmed() {
this._writableData.noCircularDependencyConfirmed = true;
}
isNoCircularDependencyConfirmed() {
return !this.isParseRequired() && this._writableData.noCircularDependencyConfirmed;
}
setHitMaxImportDepth(maxImportDepth: number) {
this._writableData.hitMaxImportDepth = maxImportDepth;
}
// Parse the file and update the state. Callers should wait for completion
// (or at least cancel) prior to calling again. It returns true if a parse
// was required and false if the parse information was up to date already.
parse(configOptions: ConfigOptions, importResolver: ImportResolver, content?: string): boolean {
return this._logTracker.log(`parsing: ${this._getPathForLogging(this._uri)}`, (logState) => {
// If the file is already parsed, we can skip.
if (!this.isParseRequired()) {
logState.suppress();
return false;
}
const diagSink = this.createDiagnosticSink();
let fileContents = this.getOpenFileContents();
if (fileContents === undefined) {
try {
const startTime = timingStats.readFileTime.totalTime;
timingStats.readFileTime.timeOperation(() => {
// Read the file's contents.
fileContents = content ?? this.getFileContent();
if (fileContents === undefined) {
throw new Error("Can't get file content");
}
// Remember the length and hash for comparison purposes.
this._writableData.lastFileContentLength = fileContents.length;
this._writableData.lastFileContentHash = StringUtils.hashString(fileContents);
});
logState.add(`fs read ${timingStats.readFileTime.totalTime - startTime}ms`);
} catch (error) {
diagSink.addError(`Source file could not be read`, getEmptyRange());
fileContents = '';
if (!this.fileSystem.existsSync(this._uri)) {
this._writableData.isFileDeleted = true;
}
}
}
try {
// Parse the token stream, building the abstract syntax tree.
const parseResults = this._parseFile(
configOptions,
this._uri,
fileContents!,
this._ipythonMode,
diagSink
);
assert(parseResults !== undefined && parseResults.tokenizerOutput !== undefined);
this._writableData.parseResults = parseResults;
this._writableData.typeIgnoreLines = this._writableData.parseResults.tokenizerOutput.typeIgnoreLines;
this._writableData.typeIgnoreAll = this._writableData.parseResults.tokenizerOutput.typeIgnoreAll;
this._writableData.pyrightIgnoreLines =
this._writableData.parseResults.tokenizerOutput.pyrightIgnoreLines;
// Resolve imports.
const execEnvironment = configOptions.findExecEnvironment(this._uri);
timingStats.resolveImportsTime.timeOperation(() => {
const importResult = this._resolveImports(
importResolver,
parseResults.importedModules,
execEnvironment
);
this._writableData.imports = importResult.imports;
this._writableData.builtinsImport = importResult.builtinsImportResult;
this._writableData.parseDiagnostics = diagSink.fetchAndClear();
});
// Is this file in a "strict" path?
const useStrict =
configOptions.strict.find((strictFileSpec) => this._uri.matchesRegex(strictFileSpec.regExp)) !==
undefined;
const commentDiags: CommentUtils.CommentDiagnostic[] = [];
this._diagnosticRuleSet = CommentUtils.getFileLevelDirectives(
this._writableData.parseResults.tokenizerOutput.tokens,
this._writableData.parseResults.tokenizerOutput.lines,
configOptions.diagnosticRuleSet,
useStrict,
commentDiags
);
this._writableData.commentDiagnostics = [];
commentDiags.forEach((commentDiag) => {
this._writableData.commentDiagnostics.push(
new Diagnostic(
DiagnosticCategory.Error,
commentDiag.message,
convertTextRangeToRange(
commentDiag.range,
this._writableData.parseResults!.tokenizerOutput.lines
)
)
);
});
} catch (e: any) {
const message: string =
(e.stack ? e.stack.toString() : undefined) ||
(typeof e.message === 'string' ? e.message : undefined) ||
JSON.stringify(e);
this._console.error(
Localizer.Diagnostic.internalParseError().format({
file: this.getUri().toUserVisibleString(),
message,
})
);
// Create dummy parse results.
this._writableData.parseResults = {
text: '',
parseTree: ModuleNode.create({ start: 0, length: 0 }),
importedModules: [],
futureImports: new Set<string>(),
tokenizerOutput: {
tokens: new TextRangeCollection<Token>([]),
lines: new TextRangeCollection<TextRange>([]),
typeIgnoreAll: undefined,
typeIgnoreLines: new Map<number, IgnoreComment>(),
pyrightIgnoreLines: new Map<number, IgnoreComment>(),
predominantEndOfLineSequence: '\n',
hasPredominantTabSequence: false,
predominantTabSequence: ' ',
predominantSingleQuoteCharacter: "'",
},
containsWildcardImport: false,
typingSymbolAliases: new Map<string, string>(),
};
this._writableData.imports = undefined;
this._writableData.builtinsImport = undefined;
const diagSink = this.createDiagnosticSink();
diagSink.addError(
Localizer.Diagnostic.internalParseError().format({
file: this.getUri().toUserVisibleString(),
message,
}),
getEmptyRange()
);
this._writableData.parseDiagnostics = diagSink.fetchAndClear();
// Do not rethrow the exception, swallow it here. Callers are not
// prepared to handle an exception.
}
this._writableData.analyzedFileContentsVersion = this._writableData.fileContentsVersion;
this._writableData.isBindingNeeded = true;
this._writableData.isCheckingNeeded = true;
this._writableData.parseTreeNeedsCleaning = false;
this._writableData.hitMaxImportDepth = undefined;
this._recomputeDiagnostics(configOptions);
return true;
});
}
bind(
configOptions: ConfigOptions,
importLookup: ImportLookup,
builtinsScope: Scope | undefined,
futureImports: Set<string>
) {
assert(!this.isParseRequired(), 'Bind called before parsing');
assert(this.isBindingRequired(), 'Bind called unnecessarily');
assert(!this._writableData.isBindingInProgress, 'Bind called while binding in progress');
assert(this._writableData.parseResults !== undefined, 'Parse results not available');
return this._logTracker.log(`binding: ${this._getPathForLogging(this._uri)}`, () => {
try {
// Perform name binding.
timingStats.bindTime.timeOperation(() => {
this._cleanParseTreeIfRequired();
const fileInfo = this._buildFileInfo(
configOptions,
this._writableData.parseResults!.text,
importLookup,
builtinsScope,
futureImports
);
AnalyzerNodeInfo.setFileInfo(this._writableData.parseResults!.parseTree, fileInfo);
const binder = new Binder(fileInfo, configOptions.indexGenerationMode);
this._writableData.isBindingInProgress = true;
binder.bindModule(this._writableData.parseResults!.parseTree);
// If we're in "test mode" (used for unit testing), run an additional
// "test walker" over the parse tree to validate its internal consistency.
if (configOptions.internalTestMode) {
const testWalker = new TestWalker();
testWalker.walk(this._writableData.parseResults!.parseTree);
}
this._writableData.bindDiagnostics = fileInfo.diagnosticSink.fetchAndClear();
const moduleScope = AnalyzerNodeInfo.getScope(this._writableData.parseResults!.parseTree);
assert(moduleScope !== undefined, 'Module scope not returned by binder');
this._writableData.moduleSymbolTable = moduleScope!.symbolTable;
});
} catch (e: any) {
const message: string =
(e.stack ? e.stack.toString() : undefined) ||
(typeof e.message === 'string' ? e.message : undefined) ||
JSON.stringify(e);
this._console.error(
Localizer.Diagnostic.internalBindError().format({
file: this.getUri().toUserVisibleString(),
message,
})
);
const diagSink = this.createDiagnosticSink();
diagSink.addError(
Localizer.Diagnostic.internalBindError().format({
file: this.getUri().toUserVisibleString(),
message,
}),
getEmptyRange()
);
this._writableData.bindDiagnostics = diagSink.fetchAndClear();
// Do not rethrow the exception, swallow it here. Callers are not
// prepared to handle an exception.
} finally {
this._writableData.isBindingInProgress = false;
}
// Prepare for the next stage of the analysis.
this._writableData.isCheckingNeeded = true;
this._writableData.isBindingNeeded = false;
this._recomputeDiagnostics(configOptions);
});
}
check(
configOptions: ConfigOptions,
importResolver: ImportResolver,
evaluator: TypeEvaluator,
sourceMapper: SourceMapper,
dependentFiles?: ParseResults[]
) {
assert(!this.isParseRequired(), 'Check called before parsing');
assert(!this.isBindingRequired(), `Check called before binding: state=${this._writableData.debugPrint()}`);
assert(!this._writableData.isBindingInProgress, 'Check called while binding in progress');
assert(this.isCheckingRequired(), 'Check called unnecessarily');
assert(this._writableData.parseResults !== undefined, 'Parse results not available');
return this._logTracker.log(`checking: ${this._getPathForLogging(this._uri)}`, () => {
try {
timingStats.typeCheckerTime.timeOperation(() => {
const checkDuration = new Duration();
const checker = new Checker(
importResolver,
evaluator,
this._writableData.parseResults!,
sourceMapper,
dependentFiles
);
checker.check();
this._writableData.isCheckingNeeded = false;
const fileInfo = AnalyzerNodeInfo.getFileInfo(this._writableData.parseResults!.parseTree)!;
this._writableData.checkerDiagnostics = fileInfo.diagnosticSink.fetchAndClear();
this._writableData.checkTime = checkDuration.getDurationInMilliseconds();
});
} catch (e: any) {
const isCancellation = OperationCanceledException.is(e);
if (!isCancellation) {
const message: string =
(e.stack ? e.stack.toString() : undefined) ||
(typeof e.message === 'string' ? e.message : undefined) ||
JSON.stringify(e);
this._console.error(
Localizer.Diagnostic.internalTypeCheckingError().format({
file: this.getUri().toUserVisibleString(),
message,
})
);
const diagSink = this.createDiagnosticSink();
diagSink.addError(
Localizer.Diagnostic.internalTypeCheckingError().format({
file: this.getUri().toUserVisibleString(),
message,
}),
getEmptyRange()
);
this._writableData.checkerDiagnostics = diagSink.fetchAndClear();
// Mark the file as complete so we don't get into an infinite loop.
this._writableData.isCheckingNeeded = false;
}
throw e;
} finally {
// Clear any circular dependencies associated with this file.
// These will be detected by the program module and associated
// with the source file right before it is finalized.
this._writableData.circularDependencies = [];
this._recomputeDiagnostics(configOptions);
}
});
}
test_enableIPythonMode(enable: boolean) {
this._ipythonMode = enable ? IPythonMode.CellDocs : IPythonMode.None;
}
protected createParser(): IParser {
return new Parser();
}
protected createDiagnosticSink(): DiagnosticSink {
return new DiagnosticSink();
}
protected createTextRangeDiagnosticSink(lines: TextRangeCollection<TextRange>): TextRangeDiagnosticSink {
return new TextRangeDiagnosticSink(lines);
}
// Computes an updated set of accumulated diagnostics for the file
// based on the partial diagnostics from various analysis stages.
private _recomputeDiagnostics(configOptions: ConfigOptions) {
this._writableData.diagnosticVersion++;
let includeWarningsAndErrors = true;
// If a file was imported as a third-party file, don't report
// any errors for it. The user can't fix them anyway.
if (this._isThirdPartyImport) {
includeWarningsAndErrors = false;
}
let diagList: Diagnostic[] = [];
appendArray(diagList, this._writableData.parseDiagnostics);
appendArray(diagList, this._writableData.commentDiagnostics);
appendArray(diagList, this._writableData.bindDiagnostics);
appendArray(diagList, this._writableData.checkerDiagnostics);
const prefilteredDiagList = diagList;
const typeIgnoreLinesClone = new Map(this._writableData.typeIgnoreLines);
const pyrightIgnoreLinesClone = new Map(this._writableData.pyrightIgnoreLines);
// Filter the diagnostics based on "type: ignore" lines.
if (this._diagnosticRuleSet.enableTypeIgnoreComments) {
if (this._writableData.typeIgnoreLines.size > 0) {
diagList = diagList.filter((d) => {
if (
d.category !== DiagnosticCategory.UnusedCode &&
d.category !== DiagnosticCategory.UnreachableCode &&
d.category !== DiagnosticCategory.Deprecated
) {
for (let line = d.range.start.line; line <= d.range.end.line; line++) {
if (this._writableData.typeIgnoreLines.has(line)) {
typeIgnoreLinesClone.delete(line);
return false;
}
}
}
return true;
});
}
}
// Filter the diagnostics based on "pyright: ignore" lines.
if (this._writableData.pyrightIgnoreLines.size > 0) {
diagList = diagList.filter((d) => {
if (
d.category !== DiagnosticCategory.UnusedCode &&
d.category !== DiagnosticCategory.UnreachableCode &&
d.category !== DiagnosticCategory.Deprecated
) {
for (let line = d.range.start.line; line <= d.range.end.line; line++) {
const pyrightIgnoreComment = this._writableData.pyrightIgnoreLines.get(line);
if (pyrightIgnoreComment) {
if (!pyrightIgnoreComment.rulesList) {
pyrightIgnoreLinesClone.delete(line);
return false;
}
const diagRule = d.getRule();
if (!diagRule) {
// If there's no diagnostic rule, it won't match
// against a rules list.
return true;
}
// Did we find this rule in the list?
if (pyrightIgnoreComment.rulesList.find((rule) => rule.text === diagRule)) {
// Update the pyrightIgnoreLinesClone to remove this rule.
const oldClone = pyrightIgnoreLinesClone.get(line);
if (oldClone?.rulesList) {
const filteredRulesList = oldClone.rulesList.filter(
(rule) => rule.text !== diagRule
);
if (filteredRulesList.length === 0) {
pyrightIgnoreLinesClone.delete(line);
} else {
pyrightIgnoreLinesClone.set(line, {
range: oldClone.range,
rulesList: filteredRulesList,
});
}
}
return false;
}
return true;
}
}
}
return true;
});
}
const unnecessaryTypeIgnoreDiags: Diagnostic[] = [];
// Skip this step if type checking is needed. Otherwise we'll likely produce
// incorrect (false positive) reportUnnecessaryTypeIgnoreComment diagnostics
// until checking is performed on this file.
if (
this._diagnosticRuleSet.reportUnnecessaryTypeIgnoreComment !== 'none' &&
!this._writableData.isCheckingNeeded
) {
const diagCategory = convertLevelToCategory(this._diagnosticRuleSet.reportUnnecessaryTypeIgnoreComment);