-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathprogram.ts
More file actions
3447 lines (2973 loc) · 136 KB
/
program.ts
File metadata and controls
3447 lines (2973 loc) · 136 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
/*
* program.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* An object that tracks all of the source files being analyzed
* and all of their recursive imports.
*/
import { CancellationToken, CompletionItem, DocumentSymbol } from 'vscode-languageserver';
import { TextDocumentContentChangeEvent } from 'vscode-languageserver-textdocument';
import {
CallHierarchyIncomingCall,
CallHierarchyItem,
CallHierarchyOutgoingCall,
CompletionList,
DocumentHighlight,
MarkupKind,
} from 'vscode-languageserver-types';
import { Commands } from '../commands/commands';
import { OperationCanceledException, throwIfCancellationRequested } from '../common/cancellationUtils';
import { appendArray, arrayEquals } from '../common/collectionUtils';
import { ConfigOptions, ExecutionEnvironment, matchFileSpecs } from '../common/configOptions';
import { ConsoleInterface, StandardConsole } from '../common/console';
import { assert, assertNever } from '../common/debug';
import { Diagnostic, DiagnosticCategory } from '../common/diagnostic';
import { FileDiagnostics } from '../common/diagnosticSink';
import { FileEditAction, FileEditActions, FileOperations, TextEditAction } from '../common/editAction';
import { Extensions } from '../common/extensibility';
import { LogTracker } from '../common/logTracker';
import {
combinePaths,
getDirectoryPath,
getFileExtension,
getFileName,
getRelativePath,
isFile,
makeDirectories,
normalizePath,
normalizePathCase,
stripFileExtension,
} from '../common/pathUtils';
import { convertPositionToOffset, convertRangeToTextRange, convertTextRangeToRange } from '../common/positionUtils';
import { computeCompletionSimilarity } from '../common/stringUtils';
import { TextEditTracker } from '../common/textEditTracker';
import {
DocumentRange,
doesRangeContain,
doRangesIntersect,
getEmptyRange,
Position,
Range,
TextRange,
} from '../common/textRange';
import { TextRangeCollection } from '../common/textRangeCollection';
import { Duration, timingStats } from '../common/timing';
import { applyTextEditsToString } from '../common/workspaceEditUtils';
import {
AutoImporter,
AutoImportOptions,
AutoImportResult,
buildModuleSymbolsMap,
ImportFormat,
ModuleSymbolMap,
} from '../languageService/autoImporter';
import { CallHierarchyProvider } from '../languageService/callHierarchyProvider';
import {
AbbreviationMap,
CompletionMap,
CompletionOptions,
CompletionResultsList,
} from '../languageService/completionProvider';
import { DefinitionFilter } from '../languageService/definitionProvider';
import { DocumentSymbolCollector, DocumentSymbolCollectorUseCase } from '../languageService/documentSymbolCollector';
import { IndexOptions, IndexResults, WorkspaceSymbolCallback } from '../languageService/documentSymbolProvider';
import { HoverResults } from '../languageService/hoverProvider';
import { ImportAdder, ImportData } from '../languageService/importAdder';
import { getModuleStatementIndentation, reindentSpan } from '../languageService/indentationUtils';
import { getInsertionPointForSymbolUnderModule } from '../languageService/insertionPointUtils';
import { ReferenceCallback, ReferencesResult } from '../languageService/referencesProvider';
import { RenameModuleProvider } from '../languageService/renameModuleProvider';
import { SignatureHelpResults } from '../languageService/signatureHelpProvider';
import { ParseNodeType } from '../parser/parseNodes';
import { ParseResults } from '../parser/parser';
import { AbsoluteModuleDescriptor, ImportLookupResult } from './analyzerFileInfo';
import * as AnalyzerNodeInfo from './analyzerNodeInfo';
import { CacheManager } from './cacheManager';
import { CircularDependency } from './circularDependency';
import { Declaration, DeclarationType } from './declaration';
import { ImportResolver } from './importResolver';
import { ImportResult, ImportType } from './importResult';
import {
findNodeByOffset,
findNodeByPosition,
getDocString,
getDottedName,
getDottedNameWithGivenNodeAsLastName,
isBlankLine,
} from './parseTreeUtils';
import { Scope } from './scope';
import { getScopeForNode } from './scopeUtils';
import { IPythonMode, SourceFile } from './sourceFile';
import { collectImportedByFiles, isUserCode } from './sourceFileInfoUtils';
import { isStubFile, SourceMapper } from './sourceMapper';
import { Symbol } from './symbol';
import { isPrivateOrProtectedName } from './symbolNameUtils';
import { createTracePrinter } from './tracePrinter';
import { PrintTypeOptions, TypeEvaluator } from './typeEvaluatorTypes';
import { createTypeEvaluatorWithTracker } from './typeEvaluatorWithTracker';
import { PrintTypeFlags } from './typePrinter';
import { Type } from './types';
import { TypeStubWriter } from './typeStubWriter';
const _maxImportDepth = 256;
const _isScipMode = true;
export const MaxWorkspaceIndexFileCount = 2000;
// Tracks information about each source file in a program,
// including the reason it was added to the program and any
// dependencies that it has on other files in the program.
export interface SourceFileInfo {
// Reference to the source file
sourceFile: SourceFile;
// Information about the source file
isTypeshedFile: boolean;
isThirdPartyImport: boolean;
isThirdPartyPyTypedPresent: boolean;
diagnosticsVersion?: number | undefined;
builtinsImport?: SourceFileInfo | undefined;
ipythonDisplayImport?: SourceFileInfo | undefined;
// Information about the chained source file
// Chained source file is not supposed to exist on file system but
// must exist in the program's source file list. Module level
// scope of the chained source file will be inserted before
// current file's scope.
chainedSourceFile?: SourceFileInfo | undefined;
effectiveFutureImports?: Set<string>;
// Information about why the file is included in the program
// and its relation to other source files in the program.
isTracked: boolean;
isOpenByClient: boolean;
imports: SourceFileInfo[];
importedBy: SourceFileInfo[];
shadows: SourceFileInfo[];
shadowedBy: SourceFileInfo[];
}
export interface MaxAnalysisTime {
// Maximum number of ms to analyze when there are open files
// that require analysis. This number is usually kept relatively
// small to guarantee responsiveness during typing.
openFilesTimeInMs: number;
// Maximum number of ms to analyze when all open files and their
// dependencies have been analyzed. This number can be higher
// to reduce overall analysis time but needs to be short enough
// to remain responsive if an open file is modified.
noOpenFilesTimeInMs: number;
}
export interface Indices {
setWorkspaceIndex(path: string, indexResults: IndexResults): void;
getIndex(execEnv: string | undefined): Map<string, IndexResults> | undefined;
}
interface UpdateImportInfo {
path: string;
isTypeshedFile: boolean;
isThirdPartyImport: boolean;
isPyTypedPresent: boolean;
}
export type PreCheckCallback = (parseResults: ParseResults, evaluator: TypeEvaluator) => void;
export interface OpenFileOptions {
isTracked: boolean;
ipythonMode: IPythonMode;
chainedFilePath: string | undefined;
realFilePath: string | undefined;
}
// Container for all of the files that are being analyzed. Files
// can fall into one or more of the following categories:
// Tracked - specified by the config options
// Referenced - part of the transitive closure
// Opened - temporarily opened in the editor
// Shadowed - implementation file that shadows a type stub file
export class Program {
private _console: ConsoleInterface;
private _sourceFileList: SourceFileInfo[] = [];
private _sourceFileMap = new Map<string, SourceFileInfo>();
private _allowedThirdPartyImports: string[] | undefined;
private _evaluator: TypeEvaluator | undefined;
private _configOptions: ConfigOptions;
private _importResolver: ImportResolver;
private _logTracker: LogTracker;
private _parsedFileCount = 0;
private _preCheckCallback: PreCheckCallback | undefined;
private _cacheManager: CacheManager;
private _id: number;
private static _nextId = 0;
constructor(
initialImportResolver: ImportResolver,
initialConfigOptions: ConfigOptions,
console?: ConsoleInterface,
logTracker?: LogTracker,
private _disableChecker?: boolean,
cacheManager?: CacheManager
) {
this._console = console || new StandardConsole();
this._logTracker = logTracker ?? new LogTracker(console, 'FG');
this._importResolver = initialImportResolver;
this._configOptions = initialConfigOptions;
this._cacheManager = cacheManager ?? new CacheManager();
this._cacheManager.registerCacheOwner(this);
this._createNewEvaluator();
this._id = Program._nextId;
Program._nextId += 1;
}
dispose() {
this._cacheManager.unregisterCacheOwner(this);
}
get evaluator(): TypeEvaluator | undefined {
return this._evaluator;
}
get console(): ConsoleInterface {
return this._console;
}
get id() {
return this._id;
}
setConfigOptions(configOptions: ConfigOptions) {
this._configOptions = configOptions;
this._importResolver.setConfigOptions(configOptions);
// Create a new evaluator with the updated config options.
this._createNewEvaluator();
}
get rootPath(): string {
return this._configOptions.projectRoot;
}
getConfigOptions(): ConfigOptions {
return this._configOptions;
}
setImportResolver(importResolver: ImportResolver) {
this._importResolver = importResolver;
// Create a new evaluator with the updated import resolver.
// Otherwise, lookup import passed to type evaluator might use
// older import resolver when resolving imports after parsing.
this._createNewEvaluator();
}
getImportResolver() {
return this._importResolver;
}
// Sets the list of tracked files that make up the program.
setTrackedFiles(filePaths: string[]): FileDiagnostics[] {
if (this._sourceFileList.length > 0) {
// We need to determine which files to remove from the existing file list.
const newFileMap = new Map<string, string>();
filePaths.forEach((path) => {
newFileMap.set(normalizePathCase(this._fs, path), path);
});
// Files that are not in the tracked file list are
// marked as no longer tracked.
this._sourceFileList.forEach((oldFile) => {
const filePath = normalizePathCase(this._fs, oldFile.sourceFile.getFilePath());
if (!newFileMap.has(filePath)) {
oldFile.isTracked = false;
}
});
}
// Add the new files. Only the new items will be added.
this.addTrackedFiles(filePaths);
return this._removeUnneededFiles();
}
// Allows a caller to set a callback that is called right before
// a source file is type checked. It is intended for testing only.
setPreCheckCallback(preCheckCallback: PreCheckCallback) {
this._preCheckCallback = preCheckCallback;
}
// By default, no third-party imports are allowed. This enables
// third-party imports for a specified import and its children.
// For example, if importNames is ['tensorflow'], then third-party
// (absolute) imports are allowed for 'import tensorflow',
// 'import tensorflow.optimizers', etc.
setAllowedThirdPartyImports(importNames: string[]) {
this._allowedThirdPartyImports = importNames;
}
addTrackedFiles(filePaths: string[], isThirdPartyImport = false, isInPyTypedPackage = false) {
filePaths.forEach((filePath) => {
this.addTrackedFile(filePath, isThirdPartyImport, isInPyTypedPackage);
});
}
addInterimFile(filePath: string): SourceFileInfo {
// Double check not already there.
let fileInfo = this.getSourceFileInfo(filePath);
if (!fileInfo) {
fileInfo = this._createInterimFileInfo(filePath);
this._addToSourceFileListAndMap(fileInfo);
}
return fileInfo;
}
addTrackedFile(filePath: string, isThirdPartyImport = false, isInPyTypedPackage = false): SourceFile {
let sourceFileInfo = this.getSourceFileInfo(filePath);
let importName = this._getImportNameForFile(filePath);
// HACK(scip-python): When adding tracked files for imports, we end up passing
// normalized paths as the argument. However, _getImportNameForFile seemingly
// needs a non-normalized path, which cannot be recovered directly from a
// normalized path. However, in practice, the non-normalized path seems to
// be stored on the sourceFileInfo, so attempt to use that instead.
if (importName === '' && sourceFileInfo) {
importName = this._getImportNameForFile(sourceFileInfo.sourceFile.getFilePath());
}
if (sourceFileInfo) {
// The module name may have changed based on updates to the
// search paths, so update it here.
sourceFileInfo.sourceFile.setModuleName(importName);
sourceFileInfo.isTracked = true;
return sourceFileInfo.sourceFile;
}
const sourceFile = new SourceFile(
this._fs,
filePath,
importName,
isThirdPartyImport,
isInPyTypedPackage,
this._console,
this._logTracker
);
sourceFileInfo = {
sourceFile,
isTracked: true,
isOpenByClient: false,
isTypeshedFile: false,
isThirdPartyImport,
isThirdPartyPyTypedPresent: isInPyTypedPackage,
diagnosticsVersion: undefined,
imports: [],
importedBy: [],
shadows: [],
shadowedBy: [],
};
this._addToSourceFileListAndMap(sourceFileInfo);
return sourceFile;
}
setFileOpened(
filePath: string,
version: number | null,
contents: TextDocumentContentChangeEvent[],
options?: OpenFileOptions
) {
let sourceFileInfo = this.getSourceFileInfo(filePath);
if (!sourceFileInfo) {
const importName = this._getImportNameForFile(filePath);
const sourceFile = new SourceFile(
this._fs,
filePath,
importName,
/* isThirdPartyImport */ false,
/* isInPyTypedPackage */ false,
this._console,
this._logTracker,
options?.realFilePath,
options?.ipythonMode ?? IPythonMode.None
);
const chainedFilePath = options?.chainedFilePath;
sourceFileInfo = {
sourceFile,
isTracked: options?.isTracked ?? false,
chainedSourceFile: chainedFilePath ? this.getSourceFileInfo(chainedFilePath) : undefined,
isOpenByClient: true,
isTypeshedFile: false,
isThirdPartyImport: false,
isThirdPartyPyTypedPresent: false,
diagnosticsVersion: undefined,
imports: [],
importedBy: [],
shadows: [],
shadowedBy: [],
};
this._addToSourceFileListAndMap(sourceFileInfo);
} else {
sourceFileInfo.isOpenByClient = true;
// Reset the diagnostic version so we force an update to the
// diagnostics, which can change based on whether the file is open.
// We do not set the version to undefined here because that implies
// there are no diagnostics currently reported for this file.
sourceFileInfo.diagnosticsVersion = 0;
}
sourceFileInfo.sourceFile.setClientVersion(version, contents);
}
getChainedFilePath(filePath: string): string | undefined {
const sourceFileInfo = this.getSourceFileInfo(filePath);
return sourceFileInfo?.chainedSourceFile?.sourceFile.getFilePath();
}
updateChainedFilePath(filePath: string, chainedFilePath: string | undefined) {
const sourceFileInfo = this.getSourceFileInfo(filePath);
if (sourceFileInfo) {
sourceFileInfo.chainedSourceFile = chainedFilePath ? this.getSourceFileInfo(chainedFilePath) : undefined;
sourceFileInfo.sourceFile.markDirty();
this._markFileDirtyRecursive(sourceFileInfo, new Set<string>());
}
}
setFileClosed(filePath: string, isTracked?: boolean): FileDiagnostics[] {
const sourceFileInfo = this.getSourceFileInfo(filePath);
if (sourceFileInfo) {
sourceFileInfo.isOpenByClient = false;
sourceFileInfo.isTracked = isTracked ?? sourceFileInfo.isTracked;
sourceFileInfo.sourceFile.setClientVersion(null, []);
// There is no guarantee that content is saved before the file is closed.
// We need to mark the file dirty so we can re-analyze next time.
// This won't matter much for OpenFileOnly users, but it will matter for
// people who use diagnosticMode Workspace.
if (sourceFileInfo.sourceFile.didContentsChangeOnDisk()) {
sourceFileInfo.sourceFile.markDirty();
this._markFileDirtyRecursive(sourceFileInfo, new Set<string>());
}
}
return this._removeUnneededFiles();
}
markAllFilesDirty(evenIfContentsAreSame: boolean, indexingNeeded = true) {
const markDirtySet = new Set<string>();
this._sourceFileList.forEach((sourceFileInfo) => {
if (evenIfContentsAreSame) {
sourceFileInfo.sourceFile.markDirty(indexingNeeded);
} else if (sourceFileInfo.sourceFile.didContentsChangeOnDisk()) {
sourceFileInfo.sourceFile.markDirty(indexingNeeded);
// Mark any files that depend on this file as dirty
// also. This will retrigger analysis of these other files.
this._markFileDirtyRecursive(sourceFileInfo, markDirtySet);
}
});
if (markDirtySet.size > 0) {
this._createNewEvaluator();
}
}
markFilesDirty(filePaths: string[], evenIfContentsAreSame: boolean, indexingNeeded = true) {
const markDirtySet = new Set<string>();
filePaths.forEach((filePath) => {
const sourceFileInfo = this.getSourceFileInfo(filePath);
if (sourceFileInfo) {
const fileName = getFileName(filePath);
// Handle builtins and __builtins__ specially. They are implicitly
// included by all source files.
if (fileName === 'builtins.pyi' || fileName === '__builtins__.pyi') {
this.markAllFilesDirty(evenIfContentsAreSame, indexingNeeded);
return;
}
// If !evenIfContentsAreSame, see if the on-disk contents have
// changed. If the file is open, the on-disk contents don't matter
// because we'll receive updates directly from the client.
if (
evenIfContentsAreSame ||
(!sourceFileInfo.isOpenByClient && sourceFileInfo.sourceFile.didContentsChangeOnDisk())
) {
sourceFileInfo.sourceFile.markDirty(indexingNeeded);
// Mark any files that depend on this file as dirty
// also. This will retrigger analysis of these other files.
this._markFileDirtyRecursive(sourceFileInfo, markDirtySet);
}
}
});
if (markDirtySet.size > 0) {
this._createNewEvaluator();
}
}
getFileCount(userFileOnly = true) {
if (userFileOnly) {
return this._sourceFileList.filter((f) => isUserCode(f)).length;
}
return this._sourceFileList.length;
}
// Returns the number of files that are considered "user" files and therefore
// are checked.
getUserFileCount() {
return this._sourceFileList.filter((s) => isUserCode(s)).length;
}
getUserFiles(): SourceFileInfo[] {
return this._sourceFileList.filter((s) => isUserCode(s));
}
getOpened(): SourceFileInfo[] {
return this._sourceFileList.filter((s) => s.isOpenByClient);
}
getFilesToAnalyzeCount() {
let sourceFileCount = 0;
if (this._disableChecker) {
return sourceFileCount;
}
this._sourceFileList.forEach((fileInfo) => {
if (fileInfo.sourceFile.isCheckingRequired()) {
if (this._shouldCheckFile(fileInfo)) {
sourceFileCount++;
}
}
});
return sourceFileCount;
}
isCheckingOnlyOpenFiles() {
return this._configOptions.checkOnlyOpenFiles || false;
}
functionSignatureDisplay() {
return this._configOptions.functionSignatureDisplay;
}
containsSourceFileIn(folder: string): boolean {
const normalized = normalizePathCase(this._fs, folder);
return this._sourceFileList.some((i) => i.sourceFile.getFilePath().startsWith(normalized));
}
owns(filePath: string) {
const fileInfo = this.getSourceFileInfo(filePath);
if (fileInfo) {
// If we already determined whether the file is tracked or not, don't do it again.
// This will make sure we have consistent look at the state once it is loaded to the memory.
return fileInfo.isTracked;
}
return matchFileSpecs(this._configOptions, filePath);
}
getSourceFile(filePath: string): SourceFile | undefined {
const sourceFileInfo = this.getSourceFileInfo(filePath);
if (!sourceFileInfo) {
return undefined;
}
return sourceFileInfo.sourceFile;
}
getBoundSourceFile(filePath: string): SourceFile | undefined {
return this.getBoundSourceFileInfo(filePath)?.sourceFile;
}
getSourceFileInfo(filePath: string): SourceFileInfo | undefined {
return this._sourceFileMap.get(normalizePathCase(this._fs, filePath));
}
getBoundSourceFileInfo(filePath: string, content?: string, force?: boolean): SourceFileInfo | undefined {
const sourceFileInfo = this.getSourceFileInfo(filePath);
if (!sourceFileInfo) {
return undefined;
}
this._bindFile(sourceFileInfo, content, force);
return sourceFileInfo;
}
// Performs parsing and analysis of any source files in the program
// that require it. If a limit time is specified, the operation
// is interrupted when the time expires. The return value indicates
// whether the method needs to be called again to complete the
// analysis. In interactive mode, the timeout is always limited
// to the smaller value to maintain responsiveness.
analyze(maxTime?: MaxAnalysisTime, token: CancellationToken = CancellationToken.None): boolean {
return this._runEvaluatorWithCancellationToken(token, () => {
const elapsedTime = new Duration();
const openFiles = this._sourceFileList.filter(
(sf) => sf.isOpenByClient && sf.sourceFile.isCheckingRequired()
);
if (openFiles.length > 0) {
const effectiveMaxTime = maxTime ? maxTime.openFilesTimeInMs : Number.MAX_VALUE;
// Check the open files.
for (const sourceFileInfo of openFiles) {
if (this._checkTypes(sourceFileInfo, token)) {
if (elapsedTime.getDurationInMilliseconds() > effectiveMaxTime) {
return true;
}
}
}
// If the caller specified a maxTime, return at this point
// since we've finalized all open files. We want to get
// the results to the user as quickly as possible.
if (maxTime !== undefined) {
return true;
}
}
if (!this._configOptions.checkOnlyOpenFiles) {
const effectiveMaxTime = maxTime ? maxTime.noOpenFilesTimeInMs : Number.MAX_VALUE;
// Now do type parsing and analysis of the remaining.
for (const sourceFileInfo of this._sourceFileList) {
if (!isUserCode(sourceFileInfo)) {
continue;
}
if (this._checkTypes(sourceFileInfo, token)) {
if (elapsedTime.getDurationInMilliseconds() > effectiveMaxTime) {
return true;
}
}
}
}
return false;
});
}
// Performs parsing and analysis of a single file in the program. If the file is not part of
// the program returns false to indicate analysis was not performed.
analyzeFile(filePath: string, token: CancellationToken = CancellationToken.None): boolean {
return this._runEvaluatorWithCancellationToken(token, () => {
const sourceFileInfo = this.getSourceFileInfo(filePath);
if (sourceFileInfo && this._checkTypes(sourceFileInfo, token)) {
return true;
}
return false;
});
}
indexWorkspace(callback: (path: string, results: IndexResults) => void, token: CancellationToken): number {
if (!this._configOptions.indexing) {
return 0;
}
return this._runEvaluatorWithCancellationToken(token, () => {
// Go through all workspace files to create indexing data.
// This will cause all files in the workspace to be parsed and bound. But
// _handleMemoryHighUsage will make sure we don't OOM and
// at the end of this method, we will drop all trees and symbol tables
// created due to indexing.
const initiallyParsedSet = new Set<SourceFileInfo>();
for (const sourceFileInfo of this._sourceFileList) {
if (!sourceFileInfo.sourceFile.isParseRequired()) {
initiallyParsedSet.add(sourceFileInfo);
}
}
let count = 0;
for (const sourceFileInfo of this._sourceFileList) {
if (!isUserCode(sourceFileInfo) || !sourceFileInfo.sourceFile.isIndexingRequired()) {
continue;
}
this._bindFile(sourceFileInfo);
const results = sourceFileInfo.sourceFile.index({ indexingForAutoImportMode: false }, token);
if (results) {
count++;
// TODO(tjdevries): Probably just want to remove this entirely.
// if (++count > MaxWorkspaceIndexFileCount) {
// this._console.warn(`Workspace indexing has hit its upper limit: 2000 files`);
//
// dropParseAndBindInfoCreatedForIndexing(this._sourceFileList, initiallyParsedSet);
// return count;
// }
callback(sourceFileInfo.sourceFile.getFilePath(), results);
}
this._handleMemoryHighUsage();
}
dropParseAndBindInfoCreatedForIndexing(this._sourceFileList, initiallyParsedSet);
return count;
});
function dropParseAndBindInfoCreatedForIndexing(
sourceFiles: SourceFileInfo[],
initiallyParsedSet: Set<SourceFileInfo>
) {
for (const sourceFileInfo of sourceFiles) {
if (sourceFileInfo.sourceFile.isParseRequired() || initiallyParsedSet.has(sourceFileInfo)) {
continue;
}
// Drop parse and bind info created during indexing.
sourceFileInfo.sourceFile.dropParseAndBindInfo();
}
}
}
// Prints a detailed list of files that have been checked and the times associated
// with each of them, sorted greatest to least.
printDetailedAnalysisTimes() {
const sortedFiles = this._sourceFileList
.filter((s) => s.sourceFile.getCheckTime() !== undefined)
.sort((a, b) => {
return b.sourceFile.getCheckTime()! - a.sourceFile.getCheckTime()!;
});
this._console.info('');
this._console.info('Analysis time by file');
sortedFiles.forEach((sfInfo) => {
const checkTimeInMs = sfInfo.sourceFile.getCheckTime()!;
this._console.info(`${checkTimeInMs}ms: ${sfInfo.sourceFile.getFilePath()}`);
});
}
// Prints import dependency information for each of the files in
// the program, skipping any typeshed files.
printDependencies(projectRootDir: string, verbose: boolean) {
const fs = this._importResolver.fileSystem;
const sortedFiles = this._sourceFileList
.filter((s) => !s.isTypeshedFile)
.sort((a, b) => {
return fs.getOriginalFilePath(a.sourceFile.getFilePath()) <
fs.getOriginalFilePath(b.sourceFile.getFilePath())
? 1
: -1;
});
const zeroImportFiles: SourceFile[] = [];
sortedFiles.forEach((sfInfo) => {
this._console.info('');
let filePath = fs.getOriginalFilePath(sfInfo.sourceFile.getFilePath());
const relPath = getRelativePath(filePath, projectRootDir);
if (relPath) {
filePath = relPath;
}
this._console.info(`${filePath}`);
this._console.info(
` Imports ${sfInfo.imports.length} ` + `file${sfInfo.imports.length === 1 ? '' : 's'}`
);
if (verbose) {
sfInfo.imports.forEach((importInfo) => {
this._console.info(` ${fs.getOriginalFilePath(importInfo.sourceFile.getFilePath())}`);
});
}
this._console.info(
` Imported by ${sfInfo.importedBy.length} ` + `file${sfInfo.importedBy.length === 1 ? '' : 's'}`
);
if (verbose) {
sfInfo.importedBy.forEach((importInfo) => {
this._console.info(` ${fs.getOriginalFilePath(importInfo.sourceFile.getFilePath())}`);
});
}
if (sfInfo.importedBy.length === 0) {
zeroImportFiles.push(sfInfo.sourceFile);
}
});
if (zeroImportFiles.length > 0) {
this._console.info('');
this._console.info(
`${zeroImportFiles.length} file${zeroImportFiles.length === 1 ? '' : 's'}` + ` not explicitly imported`
);
zeroImportFiles.forEach((importFile) => {
this._console.info(` ${fs.getOriginalFilePath(importFile.getFilePath())}`);
});
}
}
writeTypeStub(targetImportPath: string, targetIsSingleFile: boolean, stubPath: string, token: CancellationToken) {
for (const sourceFileInfo of this._sourceFileList) {
throwIfCancellationRequested(token);
const filePath = sourceFileInfo.sourceFile.getFilePath();
// Generate type stubs only for the files within the target path,
// not any files that the target module happened to import.
const relativePath = getRelativePath(filePath, targetImportPath);
if (relativePath !== undefined) {
let typeStubPath = normalizePath(combinePaths(stubPath, relativePath));
// If the target is a single file implementation, as opposed to
// a package in a directory, transform the name of the type stub
// to __init__.pyi because we're placing it in a directory.
if (targetIsSingleFile) {
typeStubPath = combinePaths(getDirectoryPath(typeStubPath), '__init__.pyi');
} else {
typeStubPath = stripFileExtension(typeStubPath) + '.pyi';
}
const typeStubDir = getDirectoryPath(typeStubPath);
try {
makeDirectories(this._fs, typeStubDir, stubPath);
} catch (e: any) {
const errMsg = `Could not create directory for '${typeStubDir}'`;
throw new Error(errMsg);
}
this._bindFile(sourceFileInfo);
this._runEvaluatorWithCancellationToken(token, () => {
const writer = new TypeStubWriter(typeStubPath, sourceFileInfo.sourceFile, this._evaluator!);
writer.write();
});
// This operation can consume significant memory, so check
// for situations where we need to discard the type cache.
this._handleMemoryHighUsage();
}
}
}
getTypeOfSymbol(symbol: Symbol) {
this._handleMemoryHighUsage();
const evaluator = this._evaluator || this._createNewEvaluator();
return evaluator.getEffectiveTypeOfSymbol(symbol);
}
printType(type: Type, options?: PrintTypeOptions): string {
this._handleMemoryHighUsage();
const evaluator = this._evaluator || this._createNewEvaluator();
return evaluator.printType(type, options);
}
private static _getPrintTypeFlags(configOptions: ConfigOptions): PrintTypeFlags {
let flags = PrintTypeFlags.None;
if (configOptions.diagnosticRuleSet.printUnknownAsAny) {
flags |= PrintTypeFlags.PrintUnknownWithAny;
}
if (configOptions.diagnosticRuleSet.omitConditionalConstraint) {
flags |= PrintTypeFlags.OmitConditionalConstraint;
}
if (configOptions.diagnosticRuleSet.omitTypeArgsIfAny) {
flags |= PrintTypeFlags.OmitTypeArgumentsIfAny;
}
if (configOptions.diagnosticRuleSet.omitUnannotatedParamType) {
flags |= PrintTypeFlags.OmitUnannotatedParamType;
}
if (configOptions.diagnosticRuleSet.pep604Printing) {
flags |= PrintTypeFlags.PEP604;
}
return flags;
}
private get _fs() {
return this._importResolver.fileSystem;
}
public _getImportNameForFile(filePath: string) {
// We allow illegal module names (e.g. names that include "-" in them)
// because we want a unique name for each module even if it cannot be
// imported through an "import" statement. It's important to have a
// unique name in case two modules declare types with the same local
// name. The type checker uses the fully-qualified (unique) module name
// to differentiate between such types.
const moduleNameAndType = this._importResolver.getModuleNameForImport(
filePath,
this._configOptions.getDefaultExecEnvironment(),
/* allowIllegalModuleName */ true
);
return moduleNameAndType.moduleName;
}
// A "shadowed" file is a python source file that has been added to the program because
// it "shadows" a type stub file for purposes of finding doc strings and definitions.
// We need to track the relationship so if the original type stub is removed from the
// program, we can remove the corresponding shadowed file and any files it imports.
private _addShadowedFile(stubFile: SourceFileInfo, shadowImplPath: string): SourceFile {
let shadowFileInfo = this.getSourceFileInfo(shadowImplPath);
if (!shadowFileInfo) {
shadowFileInfo = this.addInterimFile(shadowImplPath);
}
if (!shadowFileInfo.shadows.includes(stubFile)) {
shadowFileInfo.shadows.push(stubFile);
}
if (!stubFile.shadowedBy.includes(shadowFileInfo)) {
stubFile.shadowedBy.push(shadowFileInfo);
}
return shadowFileInfo.sourceFile;
}
private _createInterimFileInfo(filePath: string) {
const importName = this._getImportNameForFile(filePath);
const sourceFile = new SourceFile(
this._fs,
filePath,
importName,
/* isThirdPartyImport */ false,
/* isInPyTypedPackage */ false,
this._console,
this._logTracker
);
const sourceFileInfo = {
sourceFile,
isTracked: false,
isOpenByClient: false,
isTypeshedFile: false,
isThirdPartyImport: false,
isThirdPartyPyTypedPresent: false,
diagnosticsVersion: undefined,
imports: [],
importedBy: [],
shadows: [],
shadowedBy: [],
};
return sourceFileInfo;
}
private _createNewEvaluator() {
if (this._evaluator) {
// We shouldn't need to call this, but there appears to be a bug
// in the v8 garbage collector where it's unable to resolve orphaned
// objects without us giving it some assistance.
this._evaluator.disposeEvaluator();
}
this._evaluator = createTypeEvaluatorWithTracker(
this._lookUpImport,
{
printTypeFlags: Program._getPrintTypeFlags(this._configOptions),
logCalls: this._configOptions.logTypeEvaluationTime,
minimumLoggingThreshold: this._configOptions.typeEvaluationTimeThreshold,
evaluateUnknownImportsAsAny: !!this._configOptions.evaluateUnknownImportsAsAny,
verifyTypeCacheEvaluatorFlags: !!this._configOptions.internalTestMode,
},
this._logTracker,
this._configOptions.logTypeEvaluationTime
? createTracePrinter(
this._importResolver.getImportRoots(
this._configOptions.findExecEnvironment(this._configOptions.projectRoot)
)
)
: undefined
);
return this._evaluator;
}
private _parseFile(fileToParse: SourceFileInfo, content?: string, force?: boolean) {
if (!force && (!this._isFileNeeded(fileToParse) || !fileToParse.sourceFile.isParseRequired())) {
return;
}