@zzzen/pyright-internal 1.2.0-dev.20230423 → 1.2.0-dev.20230430

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/dist/analyzer/analyzerFileInfo.d.ts +4 -1
  2. package/dist/analyzer/analyzerFileInfo.js.map +1 -1
  3. package/dist/analyzer/backgroundAnalysisProgram.d.ts +4 -4
  4. package/dist/analyzer/backgroundAnalysisProgram.js +10 -7
  5. package/dist/analyzer/backgroundAnalysisProgram.js.map +1 -1
  6. package/dist/analyzer/binder.js +12 -7
  7. package/dist/analyzer/binder.js.map +1 -1
  8. package/dist/analyzer/checker.js +6 -3
  9. package/dist/analyzer/checker.js.map +1 -1
  10. package/dist/analyzer/dataClasses.js +5 -2
  11. package/dist/analyzer/dataClasses.js.map +1 -1
  12. package/dist/analyzer/declarationUtils.d.ts +6 -1
  13. package/dist/analyzer/declarationUtils.js +10 -8
  14. package/dist/analyzer/declarationUtils.js.map +1 -1
  15. package/dist/analyzer/importResolver.d.ts +15 -15
  16. package/dist/analyzer/importResolver.js +477 -477
  17. package/dist/analyzer/importResolver.js.map +1 -1
  18. package/dist/analyzer/namedTuples.d.ts +1 -1
  19. package/dist/analyzer/namedTuples.js +29 -41
  20. package/dist/analyzer/namedTuples.js.map +1 -1
  21. package/dist/analyzer/packageTypeReport.d.ts +2 -1
  22. package/dist/analyzer/packageTypeReport.js +2 -1
  23. package/dist/analyzer/packageTypeReport.js.map +1 -1
  24. package/dist/analyzer/packageTypeVerifier.d.ts +1 -1
  25. package/dist/analyzer/packageTypeVerifier.js +27 -13
  26. package/dist/analyzer/packageTypeVerifier.js.map +1 -1
  27. package/dist/analyzer/program.d.ts +25 -37
  28. package/dist/analyzer/program.js +1356 -1508
  29. package/dist/analyzer/program.js.map +1 -1
  30. package/dist/analyzer/protocols.js +1 -1
  31. package/dist/analyzer/protocols.js.map +1 -1
  32. package/dist/analyzer/service.d.ts +12 -25
  33. package/dist/analyzer/service.js +76 -109
  34. package/dist/analyzer/service.js.map +1 -1
  35. package/dist/analyzer/sourceFile.d.ts +6 -18
  36. package/dist/analyzer/sourceFile.js +57 -121
  37. package/dist/analyzer/sourceFile.js.map +1 -1
  38. package/dist/analyzer/sourceFileInfoUtils.d.ts +7 -1
  39. package/dist/analyzer/sourceFileInfoUtils.js.map +1 -1
  40. package/dist/analyzer/typeEvaluator.js +354 -322
  41. package/dist/analyzer/typeEvaluator.js.map +1 -1
  42. package/dist/analyzer/typeEvaluatorTypes.d.ts +6 -2
  43. package/dist/analyzer/typeGuards.js +3 -1
  44. package/dist/analyzer/typeGuards.js.map +1 -1
  45. package/dist/analyzer/typeStubWriter.js.map +1 -1
  46. package/dist/analyzer/typeUtils.d.ts +1 -0
  47. package/dist/analyzer/typeUtils.js +35 -8
  48. package/dist/analyzer/typeUtils.js.map +1 -1
  49. package/dist/backgroundAnalysisBase.d.ts +10 -11
  50. package/dist/backgroundAnalysisBase.js +87 -87
  51. package/dist/backgroundAnalysisBase.js.map +1 -1
  52. package/dist/commands/dumpFileDebugInfoCommand.js +8 -8
  53. package/dist/commands/dumpFileDebugInfoCommand.js.map +1 -1
  54. package/dist/commands/quickActionCommand.js +4 -1
  55. package/dist/commands/quickActionCommand.js.map +1 -1
  56. package/dist/common/cancellationUtils.d.ts +1 -1
  57. package/dist/common/cancellationUtils.js +9 -9
  58. package/dist/common/cancellationUtils.js.map +1 -1
  59. package/dist/common/commandLineOptions.d.ts +1 -2
  60. package/dist/common/commandLineOptions.js.map +1 -1
  61. package/dist/common/configOptions.d.ts +2 -2
  62. package/dist/common/configOptions.js.map +1 -1
  63. package/dist/common/console.d.ts +5 -9
  64. package/dist/common/console.js +46 -33
  65. package/dist/common/console.js.map +1 -1
  66. package/dist/common/deferred.js +10 -10
  67. package/dist/common/deferred.js.map +1 -1
  68. package/dist/common/extensibility.d.ts +26 -5
  69. package/dist/common/extensibility.js +1 -1
  70. package/dist/common/extensibility.js.map +1 -1
  71. package/dist/common/fileBasedCancellationUtils.js +5 -5
  72. package/dist/common/fileBasedCancellationUtils.js.map +1 -1
  73. package/dist/common/fileSystem.d.ts +12 -10
  74. package/dist/common/fileSystem.js.map +1 -1
  75. package/dist/common/fullAccessHost.d.ts +3 -3
  76. package/dist/common/fullAccessHost.js +6 -6
  77. package/dist/common/fullAccessHost.js.map +1 -1
  78. package/dist/common/pathUtils.d.ts +2 -2
  79. package/dist/common/pathUtils.js.map +1 -1
  80. package/dist/common/realFileSystem.js +12 -7
  81. package/dist/common/realFileSystem.js.map +1 -1
  82. package/dist/common/uriParser.d.ts +2 -2
  83. package/dist/common/uriParser.js +3 -3
  84. package/dist/common/uriParser.js.map +1 -1
  85. package/dist/common/workspaceEditUtils.js +7 -4
  86. package/dist/common/workspaceEditUtils.js.map +1 -1
  87. package/dist/languageServerBase.d.ts +32 -30
  88. package/dist/languageServerBase.js +274 -336
  89. package/dist/languageServerBase.js.map +1 -1
  90. package/dist/languageService/analyzerServiceExecutor.js +0 -1
  91. package/dist/languageService/analyzerServiceExecutor.js.map +1 -1
  92. package/dist/languageService/callHierarchyProvider.d.ts +16 -12
  93. package/dist/languageService/callHierarchyProvider.js +125 -41
  94. package/dist/languageService/callHierarchyProvider.js.map +1 -1
  95. package/dist/languageService/definitionProvider.d.ts +23 -9
  96. package/dist/languageService/definitionProvider.js +116 -91
  97. package/dist/languageService/definitionProvider.js.map +1 -1
  98. package/dist/languageService/documentHighlightProvider.d.ts +8 -3
  99. package/dist/languageService/documentHighlightProvider.js +17 -6
  100. package/dist/languageService/documentHighlightProvider.js.map +1 -1
  101. package/dist/languageService/documentSymbolCollector.d.ts +2 -2
  102. package/dist/languageService/documentSymbolCollector.js +4 -3
  103. package/dist/languageService/documentSymbolCollector.js.map +1 -1
  104. package/dist/languageService/documentSymbolProvider.js +5 -3
  105. package/dist/languageService/documentSymbolProvider.js.map +1 -1
  106. package/dist/languageService/hoverProvider.js +1 -1
  107. package/dist/languageService/hoverProvider.js.map +1 -1
  108. package/dist/languageService/insertionPointUtils.js +3 -3
  109. package/dist/languageService/insertionPointUtils.js.map +1 -1
  110. package/dist/languageService/navigationUtils.d.ts +6 -0
  111. package/dist/languageService/navigationUtils.js +28 -0
  112. package/dist/languageService/navigationUtils.js.map +1 -0
  113. package/dist/languageService/quickActions.d.ts +2 -2
  114. package/dist/languageService/quickActions.js +12 -1
  115. package/dist/languageService/quickActions.js.map +1 -1
  116. package/dist/languageService/referencesProvider.d.ts +8 -2
  117. package/dist/languageService/referencesProvider.js +81 -3
  118. package/dist/languageService/referencesProvider.js.map +1 -1
  119. package/dist/languageService/renameModuleProvider.d.ts +13 -13
  120. package/dist/languageService/renameModuleProvider.js +43 -43
  121. package/dist/languageService/renameModuleProvider.js.map +1 -1
  122. package/dist/languageService/signatureHelpProvider.d.ts +19 -23
  123. package/dist/languageService/signatureHelpProvider.js +111 -18
  124. package/dist/languageService/signatureHelpProvider.js.map +1 -1
  125. package/dist/parser/characterStream.d.ts +3 -3
  126. package/dist/parser/characterStream.js +12 -12
  127. package/dist/parser/characterStream.js.map +1 -1
  128. package/dist/parser/parser.d.ts +1 -1
  129. package/dist/parser/parser.js.map +1 -1
  130. package/dist/pyright.js +57 -54
  131. package/dist/pyright.js.map +1 -1
  132. package/dist/pyrightFileSystem.d.ts +1 -1
  133. package/dist/pyrightFileSystem.js +21 -21
  134. package/dist/pyrightFileSystem.js.map +1 -1
  135. package/dist/readonlyAugmentedFileSystem.d.ts +6 -6
  136. package/dist/readonlyAugmentedFileSystem.js +28 -28
  137. package/dist/readonlyAugmentedFileSystem.js.map +1 -1
  138. package/dist/server.js +6 -6
  139. package/dist/server.js.map +1 -1
  140. package/dist/tests/chainedSourceFiles.test.js +1 -1
  141. package/dist/tests/chainedSourceFiles.test.js.map +1 -1
  142. package/dist/tests/checker.test.js +1 -1
  143. package/dist/tests/harness/fourslash/testLanguageService.d.ts +3 -3
  144. package/dist/tests/harness/fourslash/testLanguageService.js.map +1 -1
  145. package/dist/tests/harness/fourslash/testState.d.ts +8 -8
  146. package/dist/tests/harness/fourslash/testState.js +109 -99
  147. package/dist/tests/harness/fourslash/testState.js.map +1 -1
  148. package/dist/tests/harness/vfs/filesystem.d.ts +8 -8
  149. package/dist/tests/harness/vfs/filesystem.js +68 -68
  150. package/dist/tests/harness/vfs/filesystem.js.map +1 -1
  151. package/dist/tests/importStatementUtils.test.js +34 -0
  152. package/dist/tests/importStatementUtils.test.js.map +1 -1
  153. package/dist/tests/moveSymbol.updateReference.test.js +14 -0
  154. package/dist/tests/moveSymbol.updateReference.test.js.map +1 -1
  155. package/dist/tests/signatureHelp.test.js +5 -1
  156. package/dist/tests/signatureHelp.test.js.map +1 -1
  157. package/dist/tests/sourceFile.test.js +1 -1
  158. package/dist/tests/sourceFile.test.js.map +1 -1
  159. package/dist/tests/testStateUtils.js +1 -1
  160. package/dist/tests/testStateUtils.js.map +1 -1
  161. package/dist/tests/typeEvaluator1.test.js +8 -0
  162. package/dist/tests/typeEvaluator1.test.js.map +1 -1
  163. package/dist/tests/typeEvaluator2.test.js +12 -0
  164. package/dist/tests/typeEvaluator2.test.js.map +1 -1
  165. package/dist/tests/typeEvaluator3.test.js +1 -1
  166. package/package.json +1 -1
@@ -48,7 +48,6 @@ const textRangeCollection_1 = require("../common/textRangeCollection");
48
48
  const timing_1 = require("../common/timing");
49
49
  const workspaceEditUtils_1 = require("../common/workspaceEditUtils");
50
50
  const autoImporter_1 = require("../languageService/autoImporter");
51
- const callHierarchyProvider_1 = require("../languageService/callHierarchyProvider");
52
51
  const completionProvider_1 = require("../languageService/completionProvider");
53
52
  const documentSymbolCollector_1 = require("../languageService/documentSymbolCollector");
54
53
  const importAdder_1 = require("../languageService/importAdder");
@@ -83,7 +82,7 @@ class Program {
83
82
  this._sourceFileList = [];
84
83
  this._sourceFileMap = new Map();
85
84
  this._parsedFileCount = 0;
86
- this._lookUpImport = (filePathOrModule) => {
85
+ this._lookUpImport = (filePathOrModule, options) => {
87
86
  var _a;
88
87
  let sourceFileInfo;
89
88
  if (typeof filePathOrModule === 'string') {
@@ -102,7 +101,7 @@ class Program {
102
101
  // See if the source file already exists in the program.
103
102
  sourceFileInfo = this.getSourceFileInfo(resolvedPath);
104
103
  if (!sourceFileInfo) {
105
- resolvedPath = (0, pathUtils_1.normalizePathCase)(this._fs, resolvedPath);
104
+ resolvedPath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, resolvedPath);
106
105
  // Start tracking the source file.
107
106
  this.addTrackedFile(resolvedPath);
108
107
  sourceFileInfo = this.getSourceFileInfo(resolvedPath);
@@ -117,7 +116,7 @@ class Program {
117
116
  // Bind the file if it's not already bound. Don't count this time
118
117
  // against the type checker.
119
118
  timing_1.timingStats.typeCheckerTime.subtractFromTime(() => {
120
- this._bindFile(sourceFileInfo);
119
+ this._bindFile(sourceFileInfo, /* content */ undefined, options === null || options === void 0 ? void 0 : options.skipFileNeededCheck);
121
120
  });
122
121
  }
123
122
  const symbolTable = sourceFileInfo.sourceFile.getModuleSymbolTable();
@@ -148,9 +147,6 @@ class Program {
148
147
  this._id = Program._nextId;
149
148
  Program._nextId += 1;
150
149
  }
151
- dispose() {
152
- this._cacheManager.unregisterCacheOwner(this);
153
- }
154
150
  get id() {
155
151
  return this._id;
156
152
  }
@@ -169,6 +165,12 @@ class Program {
169
165
  get importResolver() {
170
166
  return this._importResolver;
171
167
  }
168
+ get fileSystem() {
169
+ return this._importResolver.fileSystem;
170
+ }
171
+ dispose() {
172
+ this._cacheManager.unregisterCacheOwner(this);
173
+ }
172
174
  setConfigOptions(configOptions) {
173
175
  this._configOptions = configOptions;
174
176
  this._importResolver.setConfigOptions(configOptions);
@@ -188,12 +190,12 @@ class Program {
188
190
  // We need to determine which files to remove from the existing file list.
189
191
  const newFileMap = new Map();
190
192
  filePaths.forEach((path) => {
191
- newFileMap.set((0, pathUtils_1.normalizePathCase)(this._fs, path), path);
193
+ newFileMap.set((0, pathUtils_1.normalizePathCase)(this.fileSystem, path), path);
192
194
  });
193
195
  // Files that are not in the tracked file list are
194
196
  // marked as no longer tracked.
195
197
  this._sourceFileList.forEach((oldFile) => {
196
- const filePath = (0, pathUtils_1.normalizePathCase)(this._fs, oldFile.sourceFile.getFilePath());
198
+ const filePath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, oldFile.sourceFile.getFilePath());
197
199
  if (!newFileMap.has(filePath)) {
198
200
  oldFile.isTracked = false;
199
201
  }
@@ -240,7 +242,7 @@ class Program {
240
242
  sourceFileInfo.isTracked = true;
241
243
  return sourceFileInfo.sourceFile;
242
244
  }
243
- const sourceFile = new sourceFile_1.SourceFile(this._fs, filePath, importName, isThirdPartyImport, isInPyTypedPackage, this._console, this._logTracker);
245
+ const sourceFile = new sourceFile_1.SourceFile(this.fileSystem, filePath, importName, isThirdPartyImport, isInPyTypedPackage, this._console, this._logTracker);
244
246
  sourceFileInfo = {
245
247
  sourceFile,
246
248
  isTracked: true,
@@ -262,7 +264,7 @@ class Program {
262
264
  let sourceFileInfo = this.getSourceFileInfo(filePath);
263
265
  if (!sourceFileInfo) {
264
266
  const importName = this._getImportNameForFile(filePath);
265
- const sourceFile = new sourceFile_1.SourceFile(this._fs, filePath, importName,
267
+ const sourceFile = new sourceFile_1.SourceFile(this.fileSystem, filePath, importName,
266
268
  /* isThirdPartyImport */ false,
267
269
  /* isInPyTypedPackage */ false, this._console, this._logTracker, options === null || options === void 0 ? void 0 : options.realFilePath, (_a = options === null || options === void 0 ? void 0 : options.ipythonMode) !== null && _a !== void 0 ? _a : sourceFile_1.IPythonMode.None);
268
270
  const chainedFilePath = options === null || options === void 0 ? void 0 : options.chainedFilePath;
@@ -310,7 +312,7 @@ class Program {
310
312
  if (sourceFileInfo) {
311
313
  sourceFileInfo.isOpenByClient = false;
312
314
  sourceFileInfo.isTracked = isTracked !== null && isTracked !== void 0 ? isTracked : sourceFileInfo.isTracked;
313
- sourceFileInfo.sourceFile.setClientVersion(null, []);
315
+ sourceFileInfo.sourceFile.setClientVersion(null, '');
314
316
  // There is no guarantee that content is saved before the file is closed.
315
317
  // We need to mark the file dirty so we can re-analyze next time.
316
318
  // This won't matter much for OpenFileOnly users, but it will matter for
@@ -405,7 +407,7 @@ class Program {
405
407
  return this._configOptions.functionSignatureDisplay;
406
408
  }
407
409
  containsSourceFileIn(folder) {
408
- const normalized = (0, pathUtils_1.normalizePathCase)(this._fs, folder);
410
+ const normalized = (0, pathUtils_1.normalizePathCase)(this.fileSystem, folder);
409
411
  return this._sourceFileList.some((i) => i.sourceFile.getFilePath().startsWith(normalized));
410
412
  }
411
413
  owns(filePath) {
@@ -428,8 +430,11 @@ class Program {
428
430
  var _a;
429
431
  return (_a = this.getBoundSourceFileInfo(filePath)) === null || _a === void 0 ? void 0 : _a.sourceFile;
430
432
  }
433
+ getSourceFileInfoList() {
434
+ return this._sourceFileList;
435
+ }
431
436
  getSourceFileInfo(filePath) {
432
- return this._sourceFileMap.get((0, pathUtils_1.normalizePathCase)(this._fs, filePath));
437
+ return this._sourceFileMap.get((0, pathUtils_1.normalizePathCase)(this.fileSystem, filePath));
433
438
  }
434
439
  getBoundSourceFileInfo(filePath, content, force) {
435
440
  const sourceFileInfo = this.getSourceFileInfo(filePath);
@@ -504,13 +509,20 @@ class Program {
504
509
  // _handleMemoryHighUsage will make sure we don't OOM and
505
510
  // at the end of this method, we will drop all trees and symbol tables
506
511
  // created due to indexing.
512
+ let count = 0;
507
513
  const initiallyParsedSet = new Set();
508
514
  for (const sourceFileInfo of this._sourceFileList) {
509
515
  if (!sourceFileInfo.sourceFile.isParseRequired()) {
510
516
  initiallyParsedSet.add(sourceFileInfo);
511
517
  }
518
+ if ((0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo) && !sourceFileInfo.sourceFile.isIndexingRequired()) {
519
+ count++;
520
+ }
521
+ }
522
+ if (count >= exports.MaxWorkspaceIndexFileCount) {
523
+ // Already processed max files.
524
+ return 0;
512
525
  }
513
- let count = 0;
514
526
  for (const sourceFileInfo of this._sourceFileList) {
515
527
  if (!(0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo) || !sourceFileInfo.sourceFile.isIndexingRequired()) {
516
528
  continue;
@@ -556,6 +568,9 @@ class Program {
556
568
  var _a;
557
569
  return (_a = this.getBoundSourceFile(filePath)) === null || _a === void 0 ? void 0 : _a.getParseResults();
558
570
  }
571
+ handleMemoryHighUsage() {
572
+ this._handleMemoryHighUsage();
573
+ }
559
574
  // Prints a detailed list of files that have been checked and the times associated
560
575
  // with each of them, sorted greatest to least.
561
576
  printDetailedAnalysisTimes() {
@@ -636,7 +651,7 @@ class Program {
636
651
  }
637
652
  const typeStubDir = (0, pathUtils_1.getDirectoryPath)(typeStubPath);
638
653
  try {
639
- (0, pathUtils_1.makeDirectories)(this._fs, typeStubDir, stubPath);
654
+ (0, pathUtils_1.makeDirectories)(this.fileSystem, typeStubDir, stubPath);
640
655
  }
641
656
  catch (e) {
642
657
  const errMsg = `Could not create directory for '${typeStubDir}'`;
@@ -663,826 +678,273 @@ class Program {
663
678
  const evaluator = this._evaluator || this._createNewEvaluator();
664
679
  return evaluator.printType(type, options);
665
680
  }
666
- static _getPrintTypeFlags(configOptions) {
667
- let flags = 0 /* None */;
668
- if (configOptions.diagnosticRuleSet.printUnknownAsAny) {
669
- flags |= 1 /* PrintUnknownWithAny */;
670
- }
671
- if (configOptions.diagnosticRuleSet.omitConditionalConstraint) {
672
- flags |= 64 /* OmitConditionalConstraint */;
673
- }
674
- if (configOptions.diagnosticRuleSet.omitTypeArgsIfUnknown) {
675
- flags |= 2 /* OmitTypeArgumentsIfUnknown */;
676
- }
677
- if (configOptions.diagnosticRuleSet.omitUnannotatedParamType) {
678
- flags |= 4 /* OmitUnannotatedParamType */;
681
+ getTextOnRange(filePath, range, token) {
682
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
683
+ if (!sourceFileInfo) {
684
+ return undefined;
679
685
  }
680
- if (configOptions.diagnosticRuleSet.pep604Printing) {
681
- flags |= 8 /* PEP604 */;
686
+ const sourceFile = sourceFileInfo.sourceFile;
687
+ const fileContents = sourceFile.getOpenFileContents();
688
+ if (fileContents === undefined) {
689
+ // this only works with opened file
690
+ return undefined;
682
691
  }
683
- return flags;
684
- }
685
- get _fs() {
686
- return this._importResolver.fileSystem;
687
- }
688
- _getImportNameForFile(filePath) {
689
- // We allow illegal module names (e.g. names that include "-" in them)
690
- // because we want a unique name for each module even if it cannot be
691
- // imported through an "import" statement. It's important to have a
692
- // unique name in case two modules declare types with the same local
693
- // name. The type checker uses the fully-qualified (unique) module name
694
- // to differentiate between such types.
695
- const moduleNameAndType = this._importResolver.getModuleNameForImport(filePath, this._configOptions.getDefaultExecEnvironment(),
696
- /* allowIllegalModuleName */ true);
697
- return moduleNameAndType.moduleName;
692
+ return this._runEvaluatorWithCancellationToken(token, () => {
693
+ this._parseFile(sourceFileInfo);
694
+ const parseTree = sourceFile.getParseResults();
695
+ const textRange = (0, positionUtils_1.convertRangeToTextRange)(range, parseTree.tokenizerOutput.lines);
696
+ if (!textRange) {
697
+ return undefined;
698
+ }
699
+ return fileContents.substr(textRange.start, textRange.length);
700
+ });
698
701
  }
699
- // A "shadowed" file is a python source file that has been added to the program because
700
- // it "shadows" a type stub file for purposes of finding doc strings and definitions.
701
- // We need to track the relationship so if the original type stub is removed from the
702
- // program, we can remove the corresponding shadowed file and any files it imports.
703
- _addShadowedFile(stubFile, shadowImplPath) {
704
- let shadowFileInfo = this.getSourceFileInfo(shadowImplPath);
705
- if (!shadowFileInfo) {
706
- shadowFileInfo = this.addInterimFile(shadowImplPath);
707
- }
708
- if (!shadowFileInfo.shadows.includes(stubFile)) {
709
- shadowFileInfo.shadows.push(stubFile);
702
+ getAutoImports(filePath, range, similarityLimit, nameMap, options, token) {
703
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
704
+ if (!sourceFileInfo) {
705
+ return [];
710
706
  }
711
- if (!stubFile.shadowedBy.includes(shadowFileInfo)) {
712
- stubFile.shadowedBy.push(shadowFileInfo);
707
+ const sourceFile = sourceFileInfo.sourceFile;
708
+ const fileContents = sourceFile.getOpenFileContents();
709
+ if (fileContents === undefined) {
710
+ // this only works with opened file
711
+ return [];
713
712
  }
714
- return shadowFileInfo.sourceFile;
715
- }
716
- _createInterimFileInfo(filePath) {
717
- const importName = this._getImportNameForFile(filePath);
718
- const sourceFile = new sourceFile_1.SourceFile(this._fs, filePath, importName,
719
- /* isThirdPartyImport */ false,
720
- /* isInPyTypedPackage */ false, this._console, this._logTracker);
721
- const sourceFileInfo = {
722
- sourceFile,
723
- isTracked: false,
724
- isOpenByClient: false,
725
- isTypeshedFile: false,
726
- isThirdPartyImport: false,
727
- isThirdPartyPyTypedPresent: false,
728
- diagnosticsVersion: undefined,
729
- imports: [],
730
- importedBy: [],
731
- shadows: [],
732
- shadowedBy: [],
733
- };
734
- return sourceFileInfo;
713
+ return this._runEvaluatorWithCancellationToken(token, () => {
714
+ var _a;
715
+ this._bindFile(sourceFileInfo);
716
+ const parseTree = sourceFile.getParseResults();
717
+ const textRange = (0, positionUtils_1.convertRangeToTextRange)(range, parseTree.tokenizerOutput.lines);
718
+ if (!textRange) {
719
+ return [];
720
+ }
721
+ const currentNode = (0, parseTreeUtils_1.findNodeByOffset)(parseTree.parseTree, textRange.start);
722
+ if (!currentNode) {
723
+ return [];
724
+ }
725
+ const writtenWord = fileContents.substr(textRange.start, textRange.length);
726
+ const map = this._buildModuleSymbolsMap(sourceFileInfo, options.libraryMap,
727
+ /* includeSymbolsFromIndices */ true, token);
728
+ options.patternMatcher =
729
+ (_a = options.patternMatcher) !== null && _a !== void 0 ? _a : ((p, t) => (0, stringUtils_1.computeCompletionSimilarity)(p, t) > similarityLimit);
730
+ const autoImporter = new autoImporter_1.AutoImporter(this._configOptions.findExecEnvironment(filePath), this._importResolver, parseTree, range.start, new completionProvider_1.CompletionMap(), map, options);
731
+ // Filter out any name that is already defined in the current scope.
732
+ const results = [];
733
+ const currentScope = (0, scopeUtils_1.getScopeForNode)(currentNode);
734
+ if (currentScope) {
735
+ const info = nameMap === null || nameMap === void 0 ? void 0 : nameMap.get(writtenWord);
736
+ if (info) {
737
+ // No scope filter is needed since we only do exact match.
738
+ (0, collectionUtils_1.appendArray)(results, autoImporter.getAutoImportCandidatesForAbbr(writtenWord, info, token));
739
+ }
740
+ results.push(...autoImporter
741
+ .getAutoImportCandidates(writtenWord, similarityLimit, /* abbrFromUsers */ undefined, token)
742
+ .filter((r) => !currentScope.lookUpSymbolRecursive(r.name)));
743
+ }
744
+ return results;
745
+ });
735
746
  }
736
- _createNewEvaluator() {
737
- if (this._evaluator) {
738
- // We shouldn't need to call this, but there appears to be a bug
739
- // in the v8 garbage collector where it's unable to resolve orphaned
740
- // objects without us giving it some assistance.
741
- this._evaluator.disposeEvaluator();
742
- }
743
- this._evaluator = (0, typeEvaluatorWithTracker_1.createTypeEvaluatorWithTracker)(this._lookUpImport, {
744
- printTypeFlags: Program._getPrintTypeFlags(this._configOptions),
745
- logCalls: this._configOptions.logTypeEvaluationTime,
746
- minimumLoggingThreshold: this._configOptions.typeEvaluationTimeThreshold,
747
- evaluateUnknownImportsAsAny: !!this._configOptions.evaluateUnknownImportsAsAny,
748
- verifyTypeCacheEvaluatorFlags: !!this._configOptions.internalTestMode,
749
- }, this._logTracker, this._configOptions.logTypeEvaluationTime
750
- ? (0, tracePrinter_1.createTracePrinter)(this._importResolver.getImportRoots(this._configOptions.findExecEnvironment(this._configOptions.projectRoot)))
751
- : undefined);
752
- return this._evaluator;
747
+ getDiagnostics(options) {
748
+ const fileDiagnostics = this._removeUnneededFiles();
749
+ this._sourceFileList.forEach((sourceFileInfo) => {
750
+ if (this._shouldCheckFile(sourceFileInfo)) {
751
+ const diagnostics = sourceFileInfo.sourceFile.getDiagnostics(options, sourceFileInfo.diagnosticsVersion);
752
+ if (diagnostics !== undefined) {
753
+ fileDiagnostics.push({
754
+ filePath: sourceFileInfo.sourceFile.getFilePath(),
755
+ version: sourceFileInfo.sourceFile.getClientVersion(),
756
+ diagnostics,
757
+ });
758
+ // Update the cached diagnosticsVersion so we can determine
759
+ // whether there are any updates next time we call getDiagnostics.
760
+ sourceFileInfo.diagnosticsVersion = sourceFileInfo.sourceFile.getDiagnosticVersion();
761
+ }
762
+ }
763
+ else if (!sourceFileInfo.isOpenByClient &&
764
+ options.checkOnlyOpenFiles &&
765
+ sourceFileInfo.diagnosticsVersion !== undefined) {
766
+ // This condition occurs when the user switches from workspace to
767
+ // "open files only" mode. Clear all diagnostics for this file.
768
+ fileDiagnostics.push({
769
+ filePath: sourceFileInfo.sourceFile.getFilePath(),
770
+ version: sourceFileInfo.sourceFile.getClientVersion(),
771
+ diagnostics: [],
772
+ });
773
+ sourceFileInfo.diagnosticsVersion = undefined;
774
+ }
775
+ });
776
+ return fileDiagnostics;
753
777
  }
754
- _parseFile(fileToParse, content, force) {
755
- if (!force && (!this._isFileNeeded(fileToParse) || !fileToParse.sourceFile.isParseRequired())) {
756
- return;
757
- }
758
- // SourceFile.parse should only be called here in the program, as calling it
759
- // elsewhere could break the entire dependency graph maintained by the program.
760
- // Other parts of the program should use _parseFile to create ParseResults from
761
- // the sourceFile. For standalone parseResults, use parseFile or the Parser directly.
762
- if (fileToParse.sourceFile.parse(this._configOptions, this._importResolver, content)) {
763
- this._parsedFileCount++;
764
- this._updateSourceFileImports(fileToParse, this._configOptions);
778
+ getDiagnosticsForRange(filePath, range) {
779
+ const sourceFile = this.getSourceFile(filePath);
780
+ if (!sourceFile) {
781
+ return [];
765
782
  }
766
- if (fileToParse.sourceFile.isFileDeleted()) {
767
- fileToParse.isTracked = false;
768
- // Mark any files that depend on this file as dirty
769
- // also. This will retrigger analysis of these other files.
770
- const markDirtySet = new Set();
771
- this._markFileDirtyRecursive(fileToParse, markDirtySet);
772
- // Invalidate the import resolver's cache as well.
773
- this._importResolver.invalidateCache();
783
+ const unfilteredDiagnostics = sourceFile.getDiagnostics(this._configOptions);
784
+ if (!unfilteredDiagnostics) {
785
+ return [];
774
786
  }
787
+ return unfilteredDiagnostics.filter((diag) => {
788
+ return (0, textRange_1.doRangesIntersect)(diag.range, range);
789
+ });
775
790
  }
776
- _getImplicitImports(file) {
777
- var _a, _b;
778
- // If file is not parsed, then chainedSourceFile, ipythonDisplayImport,
779
- // builtinsImport might not exist or incorrect.
780
- // They will be added when _parseFile is called and _updateSourceFileImports ran.
781
- if (file.builtinsImport === file) {
782
- return undefined;
791
+ getFileIndex(filePath, options, token) {
792
+ if (options.indexingForAutoImportMode) {
793
+ // Memory optimization. We only want to hold onto symbols
794
+ // usable outside when importSymbolsOnly is on.
795
+ const name = (0, pathUtils_1.stripFileExtension)((0, pathUtils_1.getFileName)(filePath));
796
+ if ((0, symbolNameUtils_1.isPrivateOrProtectedName)(name)) {
797
+ return undefined;
798
+ }
783
799
  }
784
- const tryReturn = (input) => {
785
- if (!input || input.sourceFile.isFileDeleted()) {
800
+ this._handleMemoryHighUsage();
801
+ return this._runEvaluatorWithCancellationToken(token, () => {
802
+ var _a;
803
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
804
+ if (!sourceFileInfo) {
786
805
  return undefined;
787
806
  }
788
- return input;
789
- };
790
- return (_b = (_a = tryReturn(file.chainedSourceFile)) !== null && _a !== void 0 ? _a : tryReturn(file.ipythonDisplayImport)) !== null && _b !== void 0 ? _b : file.builtinsImport;
807
+ const content = (_a = sourceFileInfo.sourceFile.getFileContent()) !== null && _a !== void 0 ? _a : '';
808
+ if (options.indexingForAutoImportMode &&
809
+ !options.includeAllSymbols &&
810
+ !sourceFileInfo.sourceFile.isStubFile() &&
811
+ !sourceFileInfo.sourceFile.isThirdPartyPyTypedPresent()) {
812
+ // Perf optimization. if py file doesn't contain __all__
813
+ // No need to parse and bind.
814
+ if (content.indexOf('__all__') < 0) {
815
+ return undefined;
816
+ }
817
+ }
818
+ this._bindFile(sourceFileInfo, content);
819
+ return sourceFileInfo.sourceFile.index(options, token);
820
+ });
791
821
  }
792
- _bindImplicitImports(fileToAnalyze) {
793
- // Get all of the potential imports for this file.
794
- const implicitImports = [];
795
- const implicitSet = new Set();
796
- let nextImplicitImport = this._getImplicitImports(fileToAnalyze);
797
- while (nextImplicitImport) {
798
- const implicitPath = nextImplicitImport.sourceFile.getFilePath();
799
- if (implicitSet.has(implicitPath)) {
800
- // We've found a cycle. Break out of the loop.
801
- debug.fail(`Found a cycle in implicit imports files for ${implicitPath}`);
822
+ addSymbolsForDocument(filePath, symbolList, token) {
823
+ return this._runEvaluatorWithCancellationToken(token, () => {
824
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
825
+ if (sourceFileInfo) {
826
+ if (!sourceFileInfo.sourceFile.getCachedIndexResults()) {
827
+ // If we already have cached index for this file, no need to bind this file.
828
+ this._bindFile(sourceFileInfo);
829
+ }
830
+ sourceFileInfo.sourceFile.addHierarchicalSymbolsForDocument(symbolList, token);
802
831
  }
803
- implicitSet.add(implicitPath);
804
- implicitImports.push(nextImplicitImport);
805
- this._parseFile(nextImplicitImport);
806
- nextImplicitImport = this._getImplicitImports(nextImplicitImport);
807
- }
808
- if (implicitImports.length === 0) {
809
- return;
810
- }
811
- // Go in reverse order (so top of chain is first).
812
- let implicitImport = implicitImports.pop();
813
- while (implicitImport) {
814
- // Bind this file, but don't recurse into its imports.
815
- this._bindFile(implicitImport, undefined, undefined, /* isImplicitImport */ true);
816
- implicitImport = implicitImports.pop();
817
- }
832
+ });
818
833
  }
819
- // Binds the specified file and all of its dependencies, recursively. If
820
- // it runs out of time, it returns true. If it completes, it returns false.
821
- _bindFile(fileToAnalyze, content, force, isImplicitImport) {
822
- var _a, _b;
823
- if (!force && (!this._isFileNeeded(fileToAnalyze) || !fileToAnalyze.sourceFile.isBindingRequired())) {
824
- return;
825
- }
826
- this._parseFile(fileToAnalyze, content, force);
827
- // Create a function to get the scope info.
828
- const getScopeIfAvailable = (fileInfo) => {
829
- if (!fileInfo || fileInfo === fileToAnalyze) {
830
- return undefined;
831
- }
832
- // If the file was deleted, there's no scope to return.
833
- if (fileInfo.sourceFile.isFileDeleted()) {
834
- return undefined;
834
+ reportSymbolsForWorkspace(query, reporter, token) {
835
+ this._runEvaluatorWithCancellationToken(token, () => {
836
+ // Don't do a search if the query is empty. We'll return
837
+ // too many results in this case.
838
+ if (!query) {
839
+ return;
835
840
  }
836
- const parseResults = fileInfo.sourceFile.getParseResults();
837
- if (!parseResults) {
838
- return undefined;
841
+ // "Workspace symbols" searches symbols only from user code.
842
+ for (const sourceFileInfo of this._sourceFileList) {
843
+ if (!(0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo)) {
844
+ continue;
845
+ }
846
+ if (!sourceFileInfo.sourceFile.getCachedIndexResults()) {
847
+ // If we already have cached index for this file, no need to bind this file.
848
+ this._bindFile(sourceFileInfo);
849
+ }
850
+ const symbolList = sourceFileInfo.sourceFile.getSymbolsForDocument(query, token);
851
+ if (symbolList.length > 0) {
852
+ reporter(symbolList);
853
+ }
854
+ // This operation can consume significant memory, so check
855
+ // for situations where we need to discard the type cache.
856
+ this._handleMemoryHighUsage();
839
857
  }
840
- // File should already be bound because of the chained file binding above.
841
- const scope = AnalyzerNodeInfo.getScope(parseResults.parseTree);
842
- return scope;
858
+ });
859
+ }
860
+ async getCompletionsForPosition(filePath, position, workspacePath, options, nameMap, libraryMap, token) {
861
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
862
+ if (!sourceFileInfo) {
863
+ return undefined;
864
+ }
865
+ let sourceMapper;
866
+ const completionResult = this._logTracker.log(`completion at ${filePath}:${position.line}:${position.character}`, (ls) => {
867
+ var _a;
868
+ const result = this._runEvaluatorWithCancellationToken(token, () => {
869
+ this._bindFile(sourceFileInfo);
870
+ const execEnv = this._configOptions.findExecEnvironment(filePath);
871
+ sourceMapper = this._createSourceMapper(execEnv, token, sourceFileInfo, /* mapCompiled */ true);
872
+ return sourceFileInfo.sourceFile.getCompletionsForPosition(position, workspacePath, this._configOptions, this._importResolver, this._lookUpImport, this._evaluator, options, sourceMapper, nameMap, libraryMap, () => this._buildModuleSymbolsMap(sourceFileInfo, libraryMap, options.includeUserSymbolsInAutoImport, token), token);
873
+ });
874
+ ls.add(`found ${(_a = result === null || result === void 0 ? void 0 : result.completionMap.size) !== null && _a !== void 0 ? _a : 'null'} items`);
875
+ return result;
876
+ });
877
+ const completionResultsList = {
878
+ completionList: vscode_languageserver_types_1.CompletionList.create(completionResult === null || completionResult === void 0 ? void 0 : completionResult.completionMap.toArray()),
879
+ memberAccessInfo: completionResult === null || completionResult === void 0 ? void 0 : completionResult.memberAccessInfo,
880
+ autoImportInfo: completionResult === null || completionResult === void 0 ? void 0 : completionResult.autoImportInfo,
881
+ extensionInfo: completionResult === null || completionResult === void 0 ? void 0 : completionResult.extensionInfo,
843
882
  };
844
- let builtinsScope;
845
- if (fileToAnalyze.builtinsImport && fileToAnalyze.builtinsImport !== fileToAnalyze) {
846
- // Bind all of the implicit imports first. So we don't recurse into them.
847
- if (!isImplicitImport) {
848
- this._bindImplicitImports(fileToAnalyze);
883
+ const parseResults = sourceFileInfo.sourceFile.getParseResults();
884
+ if ((parseResults === null || parseResults === void 0 ? void 0 : parseResults.parseTree) && (parseResults === null || parseResults === void 0 ? void 0 : parseResults.text)) {
885
+ const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
886
+ if (offset !== undefined && sourceMapper) {
887
+ await Promise.all(extensibility_1.Extensions.getProgramExtensions(parseResults.parseTree).map((e) => {
888
+ var _a;
889
+ return (_a = e.completionListExtension) === null || _a === void 0 ? void 0 : _a.updateCompletionResults(this.evaluator, sourceMapper, options, completionResultsList, parseResults, offset, this._configOptions.functionSignatureDisplay, token);
890
+ }));
849
891
  }
850
- // If it is not builtin module itself, we need to parse and bind
851
- // the ipython display import if required. Otherwise, get builtin module.
852
- builtinsScope =
853
- (_b = (_a = getScopeIfAvailable(fileToAnalyze.chainedSourceFile)) !== null && _a !== void 0 ? _a : getScopeIfAvailable(fileToAnalyze.ipythonDisplayImport)) !== null && _b !== void 0 ? _b : getScopeIfAvailable(fileToAnalyze.builtinsImport);
854
- }
855
- let futureImports = fileToAnalyze.sourceFile.getParseResults().futureImports;
856
- if (fileToAnalyze.chainedSourceFile) {
857
- futureImports = this._getEffectiveFutureImports(futureImports, fileToAnalyze.chainedSourceFile);
858
892
  }
859
- fileToAnalyze.effectiveFutureImports = futureImports.size > 0 ? futureImports : undefined;
860
- fileToAnalyze.sourceFile.bind(this._configOptions, this._lookUpImport, builtinsScope, futureImports);
893
+ return completionResultsList;
861
894
  }
862
- _getEffectiveFutureImports(futureImports, chainedSourceFile) {
863
- var _a;
864
- const effectiveFutureImports = new Set(futureImports);
865
- (_a = chainedSourceFile.effectiveFutureImports) === null || _a === void 0 ? void 0 : _a.forEach((value) => {
866
- effectiveFutureImports.add(value);
895
+ resolveCompletionItem(filePath, completionItem, options, nameMap, libraryMap, token) {
896
+ return this._runEvaluatorWithCancellationToken(token, () => {
897
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
898
+ if (!sourceFileInfo) {
899
+ return;
900
+ }
901
+ this._bindFile(sourceFileInfo);
902
+ const execEnv = this._configOptions.findExecEnvironment(filePath);
903
+ sourceFileInfo.sourceFile.resolveCompletionItem(this._configOptions, this._importResolver, this._lookUpImport, this._evaluator, options, this._createSourceMapper(execEnv, token, sourceFileInfo, /* mapCompiled */ true), nameMap, libraryMap, () => this._buildModuleSymbolsMap(sourceFileInfo, libraryMap, options.includeUserSymbolsInAutoImport, token), completionItem, token);
867
904
  });
868
- return effectiveFutureImports;
869
905
  }
870
- // Build a map of all modules within this program and the module-
871
- // level scope that contains the symbol table for the module.
872
- _buildModuleSymbolsMap(sourceFileToExclude, libraryMap, includeSymbolsFromIndices, token) {
873
- // If we have library map, always use the map for library symbols.
874
- const predicate = (s) => {
875
- if (!libraryMap) {
876
- // We don't have any prebuilt indices, so we need to include
877
- // all files.
878
- return true;
906
+ renameModule(path, newPath, token) {
907
+ return this._runEvaluatorWithCancellationToken(token, () => {
908
+ if ((0, pathUtils_1.isFile)(this.fileSystem, path)) {
909
+ const fileInfo = this.getSourceFileInfo(path);
910
+ if (!fileInfo) {
911
+ return undefined;
912
+ }
879
913
  }
880
- if (!this._configOptions.indexing) {
881
- // We have some prebuilt indices such as stdlib, but indexing is disabled.
882
- // Include files we don't have prebuilt indices.
883
- return libraryMap.get(s.sourceFile.getFilePath()) === undefined;
914
+ const renameModuleProvider = renameModuleProvider_1.RenameModuleProvider.createForModule(this._importResolver, this._configOptions, this._evaluator, path, newPath, token);
915
+ if (!renameModuleProvider) {
916
+ return undefined;
884
917
  }
885
- // We have prebuilt indices for third party libraries. Include only
886
- // user files.
887
- return (0, sourceFileInfoUtils_1.isUserCode)(s);
888
- };
889
- // Only include import alias from user files if indexing is off for now.
890
- // Currently, when indexing is off, we don't do import alias deduplication, so
891
- // adding import alias is cheap. But when indexing is on, we do deduplication, which
892
- // require resolveAliasDeclaration that can cause more files to be parsed and bound.
893
- return (0, autoImporter_1.buildModuleSymbolsMap)(this._sourceFileList.filter((s) => s !== sourceFileToExclude && predicate(s)), includeSymbolsFromIndices, token);
894
- }
895
- _shouldCheckFile(fileInfo) {
896
- // Always do a full checking for a file that's open in the editor.
897
- if (fileInfo.isOpenByClient) {
898
- return true;
899
- }
900
- // If the file isn't currently open, only perform full checking for
901
- // files that are tracked, and only if the checkOnlyOpenFiles is disabled.
902
- if (!this._configOptions.checkOnlyOpenFiles && fileInfo.isTracked) {
903
- return true;
904
- }
905
- return false;
918
+ this._processModuleReferences(renameModuleProvider, renameModuleProvider.lastModuleName, path);
919
+ return { edits: renameModuleProvider.getEdits(), fileOperations: [] };
920
+ });
906
921
  }
907
- _checkTypes(fileToCheck, token) {
908
- return this._logTracker.log(`analyzing: ${fileToCheck.sourceFile.getFilePath()}`, (logState) => {
909
- // If the file isn't needed because it was eliminated from the
910
- // transitive closure or deleted, skip the file rather than wasting
911
- // time on it.
912
- if (!this._isFileNeeded(fileToCheck)) {
913
- logState.suppress();
914
- return false;
922
+ moveSymbolAtPosition(filePath, newFilePath, position, options, token) {
923
+ return this._runEvaluatorWithCancellationToken(token, () => {
924
+ var _a, _b;
925
+ const sourceFileExt = (0, pathUtils_1.getFileExtension)(filePath);
926
+ const destFileExt = (0, pathUtils_1.getFileExtension)(newFilePath);
927
+ if (sourceFileExt.toLowerCase() !== destFileExt.toLowerCase()) {
928
+ // Don't allow moving a symbol from py to pyi or vice versa.
929
+ return undefined;
915
930
  }
916
- if (!fileToCheck.sourceFile.isCheckingRequired()) {
917
- logState.suppress();
918
- return false;
931
+ const fileInfo = this.getSourceFileInfo(filePath);
932
+ if (!fileInfo) {
933
+ return undefined;
919
934
  }
920
- if (!this._shouldCheckFile(fileToCheck)) {
921
- logState.suppress();
922
- return false;
935
+ const newFileInfo = this.getBoundSourceFileInfo(newFilePath);
936
+ if (fileInfo === newFileInfo) {
937
+ // Can't move symbol to the same file.
938
+ return undefined;
923
939
  }
924
- this._bindFile(fileToCheck);
925
- if (this._preCheckCallback) {
926
- const parseResults = fileToCheck.sourceFile.getParseResults();
927
- if (parseResults) {
928
- this._preCheckCallback(parseResults, this._evaluator);
929
- }
940
+ this._bindFile(fileInfo);
941
+ const parseResults = fileInfo.sourceFile.getParseResults();
942
+ if (!parseResults) {
943
+ return undefined;
930
944
  }
931
- if (!this._disableChecker) {
932
- // For ipython, make sure we check all its dependent files first since
933
- // their results can affect this file's result.
934
- let dependentFiles = undefined;
935
- if (fileToCheck.sourceFile.getIPythonMode() === sourceFile_1.IPythonMode.CellDocs) {
936
- dependentFiles = [];
937
- const importedByFiles = (0, sourceFileInfoUtils_1.collectImportedByFiles)(fileToCheck);
938
- for (const file of importedByFiles) {
939
- if (!(0, sourceFileInfoUtils_1.isUserCode)(file)) {
940
- continue;
941
- }
942
- // If the file is already analyzed, it will be no op.
943
- // And make sure we don't dump parse tree and etc while
944
- // recursively calling checker. Otherwise, inner check
945
- // can dump parse tree required by outer check.
946
- const handle = this._cacheManager.pauseTracking();
947
- try {
948
- this._checkTypes(file, token);
949
- }
950
- finally {
951
- handle.dispose();
952
- }
953
- const parseResults = file.sourceFile.getParseResults();
954
- if (parseResults) {
955
- dependentFiles.push(parseResults);
956
- }
957
- }
958
- }
959
- const execEnv = this._configOptions.findExecEnvironment(fileToCheck.sourceFile.getFilePath());
960
- fileToCheck.sourceFile.check(this._importResolver, this._evaluator, this._createSourceMapper(execEnv, token, fileToCheck), dependentFiles);
961
- }
962
- // For very large programs, we may need to discard the evaluator and
963
- // its cached types to avoid running out of heap space.
964
- this._handleMemoryHighUsage();
965
- // Detect import cycles that involve the file.
966
- if (this._configOptions.diagnosticRuleSet.reportImportCycles !== 'none') {
967
- // Don't detect import cycles when doing type stub generation. Some
968
- // third-party modules are pretty convoluted.
969
- if (!this._allowedThirdPartyImports) {
970
- // We need to force all of the files to be parsed and build
971
- // a closure map for the files.
972
- const closureMap = new Map();
973
- this._getImportsRecursive(fileToCheck, closureMap, 0);
974
- closureMap.forEach((file) => {
975
- timing_1.timingStats.cycleDetectionTime.timeOperation(() => {
976
- const filesVisitedMap = new Map();
977
- if (!this._detectAndReportImportCycles(file, filesVisitedMap)) {
978
- // If no cycles were found in any of the files we visited,
979
- // set a flag to indicates that we don't need to visit them again
980
- // on subsequent cycle checks.
981
- filesVisitedMap.forEach((sourceFileInfo) => {
982
- sourceFileInfo.sourceFile.setNoCircularDependencyConfirmed();
983
- });
984
- }
985
- });
986
- });
987
- }
988
- }
989
- return true;
990
- });
991
- }
992
- // Builds a map of files that includes the specified file and all of the files
993
- // it imports (recursively) and ensures that all such files. If any of these files
994
- // have already been checked (they and their recursive imports have completed the
995
- // check phase), they are not included in the results.
996
- _getImportsRecursive(file, closureMap, recursionCount) {
997
- // If the file is already in the closure map, we found a cyclical
998
- // dependency. Don't recur further.
999
- const filePath = (0, pathUtils_1.normalizePathCase)(this._fs, file.sourceFile.getFilePath());
1000
- if (closureMap.has(filePath)) {
1001
- return;
1002
- }
1003
- // If the import chain is too long, emit an error. Otherwise we
1004
- // risk blowing the stack.
1005
- if (recursionCount > _maxImportDepth) {
1006
- file.sourceFile.setHitMaxImportDepth(_maxImportDepth);
1007
- return;
1008
- }
1009
- // Add the file to the closure map.
1010
- closureMap.set(filePath, file);
1011
- // If this file hasn't already been parsed, parse it now. This will
1012
- // discover any files it imports. Skip this if the file is part
1013
- // of a library. We'll assume that no cycles will be generated from
1014
- // library code or typeshed stubs.
1015
- if ((0, sourceFileInfoUtils_1.isUserCode)(file)) {
1016
- this._parseFile(file);
1017
- }
1018
- // Recursively add the file's imports.
1019
- for (const importedFileInfo of file.imports) {
1020
- this._getImportsRecursive(importedFileInfo, closureMap, recursionCount + 1);
1021
- }
1022
- }
1023
- _detectAndReportImportCycles(sourceFileInfo, filesVisited, dependencyChain = [], dependencyMap = new Map()) {
1024
- // Don't bother checking for typestub files or third-party files.
1025
- if (sourceFileInfo.sourceFile.isStubFile() || sourceFileInfo.isThirdPartyImport) {
1026
- return false;
1027
- }
1028
- // If we've already confirmed that this source file isn't part of a
1029
- // cycle, we can skip it entirely.
1030
- if (sourceFileInfo.sourceFile.isNoCircularDependencyConfirmed()) {
1031
- return false;
1032
- }
1033
- const filePath = (0, pathUtils_1.normalizePathCase)(this._fs, sourceFileInfo.sourceFile.getFilePath());
1034
- filesVisited.set(filePath, sourceFileInfo);
1035
- let detectedCycle = false;
1036
- if (dependencyMap.has(filePath)) {
1037
- // We detect a cycle (partial or full). A full cycle is one that is
1038
- // rooted in the file at the start of our dependency chain. A partial
1039
- // cycle loops back on some other file in the dependency chain. We
1040
- // will report only full cycles here and leave the reporting of
1041
- // partial cycles to other passes.
1042
- detectedCycle = true;
1043
- // Look for chains at least two in length. A file that contains
1044
- // an "import . from X" will technically create a cycle with
1045
- // itself, but those are not interesting to report.
1046
- if (dependencyChain.length > 1 && sourceFileInfo === dependencyChain[0]) {
1047
- this._logImportCycle(dependencyChain);
1048
- }
1049
- }
1050
- else {
1051
- // If we've already checked this dependency along
1052
- // some other path, we can skip it.
1053
- if (dependencyMap.has(filePath)) {
1054
- return false;
1055
- }
1056
- // We use both a map (for fast lookups) and a list
1057
- // (for ordering information). Set the dependency map
1058
- // entry to true to indicate that we're actively exploring
1059
- // that dependency.
1060
- dependencyMap.set(filePath, true);
1061
- dependencyChain.push(sourceFileInfo);
1062
- for (const imp of sourceFileInfo.imports) {
1063
- if (this._detectAndReportImportCycles(imp, filesVisited, dependencyChain, dependencyMap)) {
1064
- detectedCycle = true;
1065
- }
1066
- }
1067
- // Set the dependencyMap entry to false to indicate that we have
1068
- // already explored this file and don't need to explore it again.
1069
- dependencyMap.set(filePath, false);
1070
- dependencyChain.pop();
1071
- }
1072
- return detectedCycle;
1073
- }
1074
- _logImportCycle(dependencyChain) {
1075
- const circDep = new circularDependency_1.CircularDependency();
1076
- dependencyChain.forEach((sourceFileInfo) => {
1077
- circDep.appendPath(sourceFileInfo.sourceFile.getFilePath());
1078
- });
1079
- circDep.normalizeOrder();
1080
- const firstFilePath = circDep.getPaths()[0];
1081
- const firstSourceFile = this.getSourceFileInfo(firstFilePath);
1082
- (0, debug_1.assert)(firstSourceFile !== undefined);
1083
- firstSourceFile.sourceFile.addCircularDependency(circDep);
1084
- }
1085
- _markFileDirtyRecursive(sourceFileInfo, markSet, forceRebinding = false) {
1086
- const filePath = (0, pathUtils_1.normalizePathCase)(this._fs, sourceFileInfo.sourceFile.getFilePath());
1087
- // Don't mark it again if it's already been visited.
1088
- if (markSet.has(filePath)) {
1089
- return;
1090
- }
1091
- sourceFileInfo.sourceFile.markReanalysisRequired(forceRebinding);
1092
- markSet.add(filePath);
1093
- sourceFileInfo.importedBy.forEach((dep) => {
1094
- // Changes on chained source file can change symbols in the symbol table and
1095
- // dependencies on the dependent file. Force rebinding.
1096
- const forceRebinding = dep.chainedSourceFile === sourceFileInfo;
1097
- this._markFileDirtyRecursive(dep, markSet, forceRebinding);
1098
- });
1099
- // Change in the current file could impact checker result of chainedSourceFile such as unused symbols.
1100
- let chainedSourceFile = sourceFileInfo.chainedSourceFile;
1101
- while (chainedSourceFile) {
1102
- if (chainedSourceFile.sourceFile.isCheckingRequired()) {
1103
- // If the file is marked for checking, its chained one should be marked
1104
- // as well. Stop here.
1105
- return;
1106
- }
1107
- chainedSourceFile.sourceFile.markReanalysisRequired(/* forceRebinding */ false);
1108
- chainedSourceFile = chainedSourceFile.chainedSourceFile;
1109
- }
1110
- }
1111
- getTextOnRange(filePath, range, token) {
1112
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1113
- if (!sourceFileInfo) {
1114
- return undefined;
1115
- }
1116
- const sourceFile = sourceFileInfo.sourceFile;
1117
- const fileContents = sourceFile.getOpenFileContents();
1118
- if (fileContents === undefined) {
1119
- // this only works with opened file
1120
- return undefined;
1121
- }
1122
- return this._runEvaluatorWithCancellationToken(token, () => {
1123
- this._parseFile(sourceFileInfo);
1124
- const parseTree = sourceFile.getParseResults();
1125
- const textRange = (0, positionUtils_1.convertRangeToTextRange)(range, parseTree.tokenizerOutput.lines);
1126
- if (!textRange) {
1127
- return undefined;
1128
- }
1129
- return fileContents.substr(textRange.start, textRange.length);
1130
- });
1131
- }
1132
- getAutoImports(filePath, range, similarityLimit, nameMap, options, token) {
1133
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1134
- if (!sourceFileInfo) {
1135
- return [];
1136
- }
1137
- const sourceFile = sourceFileInfo.sourceFile;
1138
- const fileContents = sourceFile.getOpenFileContents();
1139
- if (fileContents === undefined) {
1140
- // this only works with opened file
1141
- return [];
1142
- }
1143
- return this._runEvaluatorWithCancellationToken(token, () => {
1144
- var _a;
1145
- this._bindFile(sourceFileInfo);
1146
- const parseTree = sourceFile.getParseResults();
1147
- const textRange = (0, positionUtils_1.convertRangeToTextRange)(range, parseTree.tokenizerOutput.lines);
1148
- if (!textRange) {
1149
- return [];
1150
- }
1151
- const currentNode = (0, parseTreeUtils_1.findNodeByOffset)(parseTree.parseTree, textRange.start);
1152
- if (!currentNode) {
1153
- return [];
1154
- }
1155
- const writtenWord = fileContents.substr(textRange.start, textRange.length);
1156
- const map = this._buildModuleSymbolsMap(sourceFileInfo, options.libraryMap,
1157
- /* includeSymbolsFromIndices */ true, token);
1158
- options.patternMatcher =
1159
- (_a = options.patternMatcher) !== null && _a !== void 0 ? _a : ((p, t) => (0, stringUtils_1.computeCompletionSimilarity)(p, t) > similarityLimit);
1160
- const autoImporter = new autoImporter_1.AutoImporter(this._configOptions.findExecEnvironment(filePath), this._importResolver, parseTree, range.start, new completionProvider_1.CompletionMap(), map, options);
1161
- // Filter out any name that is already defined in the current scope.
1162
- const results = [];
1163
- const currentScope = (0, scopeUtils_1.getScopeForNode)(currentNode);
1164
- if (currentScope) {
1165
- const info = nameMap === null || nameMap === void 0 ? void 0 : nameMap.get(writtenWord);
1166
- if (info) {
1167
- // No scope filter is needed since we only do exact match.
1168
- (0, collectionUtils_1.appendArray)(results, autoImporter.getAutoImportCandidatesForAbbr(writtenWord, info, token));
1169
- }
1170
- results.push(...autoImporter
1171
- .getAutoImportCandidates(writtenWord, similarityLimit, /* abbrFromUsers */ undefined, token)
1172
- .filter((r) => !currentScope.lookUpSymbolRecursive(r.name)));
1173
- }
1174
- return results;
1175
- });
1176
- }
1177
- getDiagnostics(options) {
1178
- const fileDiagnostics = this._removeUnneededFiles();
1179
- this._sourceFileList.forEach((sourceFileInfo) => {
1180
- if (this._shouldCheckFile(sourceFileInfo)) {
1181
- const diagnostics = sourceFileInfo.sourceFile.getDiagnostics(options, sourceFileInfo.diagnosticsVersion);
1182
- if (diagnostics !== undefined) {
1183
- fileDiagnostics.push({
1184
- filePath: sourceFileInfo.sourceFile.getFilePath(),
1185
- version: sourceFileInfo.sourceFile.getClientVersion(),
1186
- diagnostics,
1187
- });
1188
- // Update the cached diagnosticsVersion so we can determine
1189
- // whether there are any updates next time we call getDiagnostics.
1190
- sourceFileInfo.diagnosticsVersion = sourceFileInfo.sourceFile.getDiagnosticVersion();
1191
- }
1192
- }
1193
- else if (!sourceFileInfo.isOpenByClient &&
1194
- options.checkOnlyOpenFiles &&
1195
- sourceFileInfo.diagnosticsVersion !== undefined) {
1196
- // This condition occurs when the user switches from workspace to
1197
- // "open files only" mode. Clear all diagnostics for this file.
1198
- fileDiagnostics.push({
1199
- filePath: sourceFileInfo.sourceFile.getFilePath(),
1200
- version: sourceFileInfo.sourceFile.getClientVersion(),
1201
- diagnostics: [],
1202
- });
1203
- sourceFileInfo.diagnosticsVersion = undefined;
1204
- }
1205
- });
1206
- return fileDiagnostics;
1207
- }
1208
- getDiagnosticsForRange(filePath, range) {
1209
- const sourceFile = this.getSourceFile(filePath);
1210
- if (!sourceFile) {
1211
- return [];
1212
- }
1213
- const unfilteredDiagnostics = sourceFile.getDiagnostics(this._configOptions);
1214
- if (!unfilteredDiagnostics) {
1215
- return [];
1216
- }
1217
- return unfilteredDiagnostics.filter((diag) => {
1218
- return (0, textRange_1.doRangesIntersect)(diag.range, range);
1219
- });
1220
- }
1221
- getDefinitionsForPosition(filePath, position, filter, token) {
1222
- return this._runEvaluatorWithCancellationToken(token, () => {
1223
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1224
- if (!sourceFileInfo) {
1225
- return undefined;
1226
- }
1227
- this._bindFile(sourceFileInfo);
1228
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1229
- return sourceFileInfo.sourceFile.getDefinitionsForPosition(this._createSourceMapper(execEnv, token, sourceFileInfo), position, filter, this._evaluator, token);
1230
- });
1231
- }
1232
- getTypeDefinitionsForPosition(filePath, position, token) {
1233
- return this._runEvaluatorWithCancellationToken(token, () => {
1234
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1235
- if (!sourceFileInfo) {
1236
- return undefined;
1237
- }
1238
- this._bindFile(sourceFileInfo);
1239
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1240
- return sourceFileInfo.sourceFile.getTypeDefinitionsForPosition(this._createSourceMapper(execEnv, token, sourceFileInfo,
1241
- /* mapCompiled */ false,
1242
- /* preferStubs */ true), position, this._evaluator, filePath, token);
1243
- });
1244
- }
1245
- reportReferencesForPosition(filePath, position, includeDeclaration, reporter, token) {
1246
- this._runEvaluatorWithCancellationToken(token, () => {
1247
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1248
- if (!sourceFileInfo) {
1249
- return;
1250
- }
1251
- const invokedFromUserFile = (0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo);
1252
- this._bindFile(sourceFileInfo);
1253
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1254
- const referencesResult = this._getDeclarationForPosition(sourceFileInfo, position, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Reference, this._createSourceMapper(execEnv, token, sourceFileInfo), token, reporter);
1255
- if (!referencesResult) {
1256
- return;
1257
- }
1258
- // Do we need to do a global search as well?
1259
- if (referencesResult.requiresGlobalSearch) {
1260
- for (const curSourceFileInfo of this._sourceFileList) {
1261
- (0, cancellationUtils_1.throwIfCancellationRequested)(token);
1262
- // "Find all references" will only include references from user code
1263
- // unless the file is explicitly opened in the editor or it is invoked from non user files.
1264
- if (curSourceFileInfo.isOpenByClient || !invokedFromUserFile || (0, sourceFileInfoUtils_1.isUserCode)(curSourceFileInfo)) {
1265
- // See if the reference symbol's string is located somewhere within the file.
1266
- // If not, we can skip additional processing for the file.
1267
- const fileContents = curSourceFileInfo.sourceFile.getFileContent();
1268
- if (!fileContents || referencesResult.symbolNames.some((s) => fileContents.search(s) >= 0)) {
1269
- this._bindFile(curSourceFileInfo);
1270
- curSourceFileInfo.sourceFile.addReferences(referencesResult, includeDeclaration, this._evaluator, token);
1271
- }
1272
- // This operation can consume significant memory, so check
1273
- // for situations where we need to discard the type cache.
1274
- this._handleMemoryHighUsage();
1275
- }
1276
- }
1277
- // Make sure to include declarations regardless where they are defined
1278
- // if includeDeclaration is set.
1279
- if (includeDeclaration) {
1280
- for (const decl of referencesResult.declarations) {
1281
- (0, cancellationUtils_1.throwIfCancellationRequested)(token);
1282
- if (referencesResult.locations.some((l) => l.path === decl.path)) {
1283
- // Already included.
1284
- continue;
1285
- }
1286
- const declFileInfo = this.getSourceFileInfo(decl.path);
1287
- if (!declFileInfo) {
1288
- // The file the declaration belongs to doesn't belong to the program.
1289
- continue;
1290
- }
1291
- const tempResult = new referencesProvider_1.ReferencesResult(referencesResult.requiresGlobalSearch, referencesResult.nodeAtOffset, referencesResult.symbolNames, referencesResult.declarations, referencesResult.useCase);
1292
- declFileInfo.sourceFile.addReferences(tempResult, includeDeclaration, this._evaluator, token);
1293
- for (const loc of tempResult.locations) {
1294
- // Include declarations only. And throw away any references
1295
- if (loc.path === decl.path && (0, textRange_1.doesRangeContain)(decl.range, loc.range)) {
1296
- referencesResult.addLocations(loc);
1297
- }
1298
- }
1299
- }
1300
- }
1301
- }
1302
- else {
1303
- sourceFileInfo.sourceFile.addReferences(referencesResult, includeDeclaration, this._evaluator, token);
1304
- }
1305
- });
1306
- }
1307
- getFileIndex(filePath, options, token) {
1308
- if (options.indexingForAutoImportMode) {
1309
- // Memory optimization. We only want to hold onto symbols
1310
- // usable outside when importSymbolsOnly is on.
1311
- const name = (0, pathUtils_1.stripFileExtension)((0, pathUtils_1.getFileName)(filePath));
1312
- if ((0, symbolNameUtils_1.isPrivateOrProtectedName)(name)) {
1313
- return undefined;
1314
- }
1315
- }
1316
- this._handleMemoryHighUsage();
1317
- return this._runEvaluatorWithCancellationToken(token, () => {
1318
- var _a;
1319
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1320
- if (!sourceFileInfo) {
1321
- return undefined;
1322
- }
1323
- const content = (_a = sourceFileInfo.sourceFile.getFileContent()) !== null && _a !== void 0 ? _a : '';
1324
- if (options.indexingForAutoImportMode &&
1325
- !options.includeAllSymbols &&
1326
- !sourceFileInfo.sourceFile.isStubFile() &&
1327
- !sourceFileInfo.sourceFile.isThirdPartyPyTypedPresent()) {
1328
- // Perf optimization. if py file doesn't contain __all__
1329
- // No need to parse and bind.
1330
- if (content.indexOf('__all__') < 0) {
1331
- return undefined;
1332
- }
1333
- }
1334
- this._bindFile(sourceFileInfo, content);
1335
- return sourceFileInfo.sourceFile.index(options, token);
1336
- });
1337
- }
1338
- addSymbolsForDocument(filePath, symbolList, token) {
1339
- return this._runEvaluatorWithCancellationToken(token, () => {
1340
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1341
- if (sourceFileInfo) {
1342
- if (!sourceFileInfo.sourceFile.getCachedIndexResults()) {
1343
- // If we already have cached index for this file, no need to bind this file.
1344
- this._bindFile(sourceFileInfo);
1345
- }
1346
- sourceFileInfo.sourceFile.addHierarchicalSymbolsForDocument(symbolList, token);
1347
- }
1348
- });
1349
- }
1350
- reportSymbolsForWorkspace(query, reporter, token) {
1351
- this._runEvaluatorWithCancellationToken(token, () => {
1352
- // Don't do a search if the query is empty. We'll return
1353
- // too many results in this case.
1354
- if (!query) {
1355
- return;
1356
- }
1357
- // "Workspace symbols" searches symbols only from user code.
1358
- for (const sourceFileInfo of this._sourceFileList) {
1359
- if (!(0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo)) {
1360
- continue;
1361
- }
1362
- if (!sourceFileInfo.sourceFile.getCachedIndexResults()) {
1363
- // If we already have cached index for this file, no need to bind this file.
1364
- this._bindFile(sourceFileInfo);
1365
- }
1366
- const symbolList = sourceFileInfo.sourceFile.getSymbolsForDocument(query, token);
1367
- if (symbolList.length > 0) {
1368
- reporter(symbolList);
1369
- }
1370
- // This operation can consume significant memory, so check
1371
- // for situations where we need to discard the type cache.
1372
- this._handleMemoryHighUsage();
1373
- }
1374
- });
1375
- }
1376
- getDocumentHighlight(filePath, position, token) {
1377
- return this._runEvaluatorWithCancellationToken(token, () => {
1378
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1379
- if (!sourceFileInfo) {
1380
- return undefined;
1381
- }
1382
- this._bindFile(sourceFileInfo);
1383
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1384
- return sourceFileInfo.sourceFile.getDocumentHighlight(this._createSourceMapper(execEnv, token, sourceFileInfo), position, this._evaluator, token);
1385
- });
1386
- }
1387
- getSignatureHelpForPosition(filePath, position, format, token) {
1388
- return this._runEvaluatorWithCancellationToken(token, () => {
1389
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1390
- if (!sourceFileInfo) {
1391
- return undefined;
1392
- }
1393
- this._bindFile(sourceFileInfo);
1394
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1395
- return sourceFileInfo.sourceFile.getSignatureHelpForPosition(position, this._createSourceMapper(execEnv, token, sourceFileInfo, /* mapCompiled */ true), this._evaluator, format, token);
1396
- });
1397
- }
1398
- async getCompletionsForPosition(filePath, position, workspacePath, options, nameMap, libraryMap, token) {
1399
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1400
- if (!sourceFileInfo) {
1401
- return undefined;
1402
- }
1403
- let sourceMapper;
1404
- const completionResult = this._logTracker.log(`completion at ${filePath}:${position.line}:${position.character}`, (ls) => {
1405
- var _a;
1406
- const result = this._runEvaluatorWithCancellationToken(token, () => {
1407
- this._bindFile(sourceFileInfo);
1408
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1409
- sourceMapper = this._createSourceMapper(execEnv, token, sourceFileInfo, /* mapCompiled */ true);
1410
- return sourceFileInfo.sourceFile.getCompletionsForPosition(position, workspacePath, this._configOptions, this._importResolver, this._lookUpImport, this._evaluator, options, sourceMapper, nameMap, libraryMap, () => this._buildModuleSymbolsMap(sourceFileInfo, libraryMap, options.includeUserSymbolsInAutoImport, token), token);
1411
- });
1412
- ls.add(`found ${(_a = result === null || result === void 0 ? void 0 : result.completionMap.size) !== null && _a !== void 0 ? _a : 'null'} items`);
1413
- return result;
1414
- });
1415
- const completionResultsList = {
1416
- completionList: vscode_languageserver_types_1.CompletionList.create(completionResult === null || completionResult === void 0 ? void 0 : completionResult.completionMap.toArray()),
1417
- memberAccessInfo: completionResult === null || completionResult === void 0 ? void 0 : completionResult.memberAccessInfo,
1418
- autoImportInfo: completionResult === null || completionResult === void 0 ? void 0 : completionResult.autoImportInfo,
1419
- extensionInfo: completionResult === null || completionResult === void 0 ? void 0 : completionResult.extensionInfo,
1420
- };
1421
- const parseResults = sourceFileInfo.sourceFile.getParseResults();
1422
- if ((parseResults === null || parseResults === void 0 ? void 0 : parseResults.parseTree) && (parseResults === null || parseResults === void 0 ? void 0 : parseResults.text)) {
1423
- const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
1424
- if (offset !== undefined && sourceMapper) {
1425
- await Promise.all(extensibility_1.Extensions.getProgramExtensions(parseResults.parseTree).map((e) => {
1426
- var _a;
1427
- return (_a = e.completionListExtension) === null || _a === void 0 ? void 0 : _a.updateCompletionResults(this.evaluator, sourceMapper, options, completionResultsList, parseResults, offset, this._configOptions.functionSignatureDisplay, token);
1428
- }));
1429
- }
1430
- }
1431
- return completionResultsList;
1432
- }
1433
- resolveCompletionItem(filePath, completionItem, options, nameMap, libraryMap, token) {
1434
- return this._runEvaluatorWithCancellationToken(token, () => {
1435
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1436
- if (!sourceFileInfo) {
1437
- return;
1438
- }
1439
- this._bindFile(sourceFileInfo);
1440
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1441
- sourceFileInfo.sourceFile.resolveCompletionItem(this._configOptions, this._importResolver, this._lookUpImport, this._evaluator, options, this._createSourceMapper(execEnv, token, sourceFileInfo, /* mapCompiled */ true), nameMap, libraryMap, () => this._buildModuleSymbolsMap(sourceFileInfo, libraryMap, options.includeUserSymbolsInAutoImport, token), completionItem, token);
1442
- });
1443
- }
1444
- renameModule(path, newPath, token) {
1445
- return this._runEvaluatorWithCancellationToken(token, () => {
1446
- if ((0, pathUtils_1.isFile)(this._fs, path)) {
1447
- const fileInfo = this.getSourceFileInfo(path);
1448
- if (!fileInfo) {
1449
- return undefined;
1450
- }
1451
- }
1452
- const renameModuleProvider = renameModuleProvider_1.RenameModuleProvider.createForModule(this._importResolver, this._configOptions, this._evaluator, path, newPath, token);
1453
- if (!renameModuleProvider) {
1454
- return undefined;
1455
- }
1456
- this._processModuleReferences(renameModuleProvider, renameModuleProvider.lastModuleName, path);
1457
- return { edits: renameModuleProvider.getEdits(), fileOperations: [] };
1458
- });
1459
- }
1460
- moveSymbolAtPosition(filePath, newFilePath, position, options, token) {
1461
- return this._runEvaluatorWithCancellationToken(token, () => {
1462
- var _a, _b;
1463
- const sourceFileExt = (0, pathUtils_1.getFileExtension)(filePath);
1464
- const destFileExt = (0, pathUtils_1.getFileExtension)(newFilePath);
1465
- if (sourceFileExt.toLowerCase() !== destFileExt.toLowerCase()) {
1466
- // Don't allow moving a symbol from py to pyi or vice versa.
1467
- return undefined;
1468
- }
1469
- const fileInfo = this.getSourceFileInfo(filePath);
1470
- if (!fileInfo) {
1471
- return undefined;
1472
- }
1473
- const newFileInfo = this.getBoundSourceFileInfo(newFilePath);
1474
- if (fileInfo === newFileInfo) {
1475
- // Can't move symbol to the same file.
1476
- return undefined;
1477
- }
1478
- this._bindFile(fileInfo);
1479
- const parseResults = fileInfo.sourceFile.getParseResults();
1480
- if (!parseResults) {
1481
- return undefined;
1482
- }
1483
- const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
1484
- if (offset === undefined) {
1485
- return undefined;
945
+ const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
946
+ if (offset === undefined) {
947
+ return undefined;
1486
948
  }
1487
949
  const node = (0, parseTreeUtils_1.findNodeByOffset)(parseResults.parseTree, offset);
1488
950
  if (node === undefined) {
@@ -1622,804 +1084,1190 @@ class Program {
1622
1084
  if ((nameNode === null || nameNode === void 0 ? void 0 : nameNode.nodeType) !== 38 /* Name */) {
1623
1085
  continue;
1624
1086
  }
1625
- // decl is synthesized. there is no node associated with the decl.
1626
- // ex) import a or import a.b
1627
- const dottedName1 = ((_a = nameNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 37 /* ModuleName */ ? nameNode.parent.nameParts : [nameNode];
1628
- for (const [decl, names] of importData.declarations) {
1629
- if (decl.node) {
1630
- if (textRange_1.TextRange.containsRange(decl.node, nameNode)) {
1631
- tracker.removeNodes({ node: nameNode, parseResults: parseResults });
1632
- break;
1087
+ // decl is synthesized. there is no node associated with the decl.
1088
+ // ex) import a or import a.b
1089
+ const dottedName1 = ((_a = nameNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 37 /* ModuleName */ ? nameNode.parent.nameParts : [nameNode];
1090
+ for (const [decl, names] of importData.declarations) {
1091
+ if (decl.node) {
1092
+ if (textRange_1.TextRange.containsRange(decl.node, nameNode)) {
1093
+ tracker.removeNodes({ node: nameNode, parseResults: parseResults });
1094
+ break;
1095
+ }
1096
+ }
1097
+ const dottedName2 = (0, parseTreeUtils_1.getDottedName)((0, parseTreeUtils_1.getDottedNameWithGivenNodeAsLastName)(names[0]));
1098
+ if (dottedName2 && (0, collectionUtils_1.arrayEquals)(dottedName1, dottedName2, (e1, e2) => e1.value === e2.value)) {
1099
+ tracker.removeNodes({ node: nameNode, parseResults: parseResults });
1100
+ break;
1101
+ }
1102
+ }
1103
+ }
1104
+ const oldText = sourceFile.getFileContent();
1105
+ const newText = (0, workspaceEditUtils_1.applyTextEditsToString)(tracker.getEdits(token).filter((v) => v.filePath === filePath), parseResults.tokenizerOutput.lines, oldText);
1106
+ // We will attempt to remove unused imports multiple times since removing 1 unused import
1107
+ // could make another import unused. This is due to how we calculate which import is not used.
1108
+ // ex) import os, os.path, os.path.xxx
1109
+ // `os.path` and `os.path.xxx` will be marked as used due to `import os`.
1110
+ // once `os` is removed `os.path` will be marked as unused and so on.
1111
+ // We will attempt to remove those chained unused imports up to 10 chain.
1112
+ if (attempt > 10 || oldText === newText) {
1113
+ return newText;
1114
+ }
1115
+ _updateFileContent(cloned, filePath, newText);
1116
+ return _tryGetTextAfterUnusedImportsRemoved(cloned, filePath, importData, attempt + 1, token);
1117
+ }
1118
+ });
1119
+ function _updateFileContent(cloned, filePath, text) {
1120
+ var _a, _b;
1121
+ const info = cloned.getSourceFileInfo(filePath);
1122
+ const version = info ? ((_a = info.sourceFile.getClientVersion()) !== null && _a !== void 0 ? _a : 0) + 1 : 0;
1123
+ const chainedFilePath = info ? (_b = info.chainedSourceFile) === null || _b === void 0 ? void 0 : _b.sourceFile.getFilePath() : undefined;
1124
+ const ipythonMode = info ? info.sourceFile.getIPythonMode() : sourceFile_1.IPythonMode.None;
1125
+ const isTracked = info ? info.isTracked : true;
1126
+ const realFilePath = info ? info.sourceFile.getRealFilePath() : filePath;
1127
+ cloned.setFileOpened(filePath, version, text, {
1128
+ chainedFilePath,
1129
+ ipythonMode,
1130
+ isTracked,
1131
+ realFilePath,
1132
+ });
1133
+ }
1134
+ function _getNumberOfBlankLinesToInsert(parseResults, decl, position) {
1135
+ if (position.line === 0 && position.character === 0) {
1136
+ return 0;
1137
+ }
1138
+ let previousStatement;
1139
+ const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
1140
+ if (offset && parseResults.parseTree.statements.length > 0) {
1141
+ previousStatement = parseResults.parseTree.statements.reduce((prev, curr) => offset < curr.start ? prev : curr);
1142
+ }
1143
+ // This basically try to add some blank lines after the last line with text.
1144
+ let linesToAdd = 0;
1145
+ if (previousStatement) {
1146
+ if ((0, declaration_1.isVariableDeclaration)(decl)) {
1147
+ switch (previousStatement.nodeType) {
1148
+ case 47 /* StatementList */:
1149
+ // Small statement such as call, assignment, etc.
1150
+ linesToAdd = 0;
1151
+ break;
1152
+ case 10 /* Class */:
1153
+ case 28 /* Function */:
1154
+ linesToAdd = 2;
1155
+ break;
1156
+ default:
1157
+ // any other statement such as if, while, etc. we will add 1 blank line.
1158
+ linesToAdd = 1;
1159
+ }
1160
+ }
1161
+ else {
1162
+ linesToAdd = 2;
1163
+ }
1164
+ }
1165
+ // If the position is not at the beginning of the line, we need to add 1 more '\n'
1166
+ // to start from blank line.
1167
+ linesToAdd += position.character !== 0 ? 1 : 0;
1168
+ // If there are already blank lines, we only add the difference.
1169
+ const desiredBlankLines = linesToAdd;
1170
+ const startingLine = position.character !== 0 ? position.line : position.line - 1;
1171
+ for (let i = 0; i < desiredBlankLines; i++) {
1172
+ const currentLine = startingLine - i;
1173
+ if (currentLine < 0 || !(0, parseTreeUtils_1.isBlankLine)(parseResults, currentLine)) {
1174
+ break;
1175
+ }
1176
+ linesToAdd--;
1177
+ }
1178
+ return linesToAdd;
1179
+ }
1180
+ }
1181
+ clone() {
1182
+ var _a, _b;
1183
+ const program = new Program(this._importResolver, this._configOptions, this._console, new logTracker_1.LogTracker(this._console, 'Cloned'));
1184
+ // Cloned program will use whatever user files the program currently has.
1185
+ const userFiles = this.getUserFiles();
1186
+ program.setTrackedFiles(userFiles.map((i) => i.sourceFile.getFilePath()));
1187
+ program.markAllFilesDirty(true);
1188
+ // Make sure we keep editor content (open file) which could be different than one in the file system.
1189
+ for (const fileInfo of this.getOpened()) {
1190
+ const version = fileInfo.sourceFile.getClientVersion();
1191
+ if (version === undefined) {
1192
+ continue;
1193
+ }
1194
+ program.setFileOpened(fileInfo.sourceFile.getFilePath(), version, (_a = fileInfo.sourceFile.getOpenFileContents()) !== null && _a !== void 0 ? _a : '', {
1195
+ chainedFilePath: (_b = fileInfo.chainedSourceFile) === null || _b === void 0 ? void 0 : _b.sourceFile.getFilePath(),
1196
+ ipythonMode: fileInfo.sourceFile.getIPythonMode(),
1197
+ isTracked: fileInfo.isTracked,
1198
+ realFilePath: fileInfo.sourceFile.getRealFilePath(),
1199
+ });
1200
+ }
1201
+ return program;
1202
+ }
1203
+ canRenameSymbolAtPosition(filePath, position, isDefaultWorkspace, allowModuleRename, token) {
1204
+ return this._runEvaluatorWithCancellationToken(token, () => {
1205
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
1206
+ if (!sourceFileInfo) {
1207
+ return undefined;
1208
+ }
1209
+ this._bindFile(sourceFileInfo);
1210
+ const referencesResult = this._getReferenceResult(sourceFileInfo, filePath, position, allowModuleRename, token);
1211
+ if (!referencesResult) {
1212
+ return undefined;
1213
+ }
1214
+ if (referencesResult.containsOnlyImportDecls &&
1215
+ !this._supportRenameModule(referencesResult.declarations, isDefaultWorkspace)) {
1216
+ return undefined;
1217
+ }
1218
+ const renameMode = this._getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace);
1219
+ if (renameMode === 'none') {
1220
+ return undefined;
1221
+ }
1222
+ // Return the range of the symbol.
1223
+ const parseResult = sourceFileInfo.sourceFile.getParseResults();
1224
+ return {
1225
+ range: (0, positionUtils_1.convertTextRangeToRange)(referencesResult.nodeAtOffset, parseResult.tokenizerOutput.lines),
1226
+ declarations: referencesResult.declarations,
1227
+ };
1228
+ });
1229
+ }
1230
+ renameSymbolAtPosition(filePath, position, newName, isDefaultWorkspace, allowModuleRename, token) {
1231
+ return this._runEvaluatorWithCancellationToken(token, () => {
1232
+ var _a;
1233
+ const sourceFileInfo = this.getSourceFileInfo(filePath);
1234
+ if (!sourceFileInfo) {
1235
+ return undefined;
1236
+ }
1237
+ this._bindFile(sourceFileInfo);
1238
+ const referencesResult = this._getReferenceResult(sourceFileInfo, filePath, position, allowModuleRename, token);
1239
+ if (!referencesResult) {
1240
+ return undefined;
1241
+ }
1242
+ if (referencesResult.containsOnlyImportDecls) {
1243
+ // All decls must be on a user file.
1244
+ if (!this._supportRenameModule(referencesResult.declarations, isDefaultWorkspace)) {
1245
+ return undefined;
1246
+ }
1247
+ const moduleInfo = renameModuleProvider_1.RenameModuleProvider.getRenameModulePathInfo(renameModuleProvider_1.RenameModuleProvider.getRenameModulePath(referencesResult.declarations), newName);
1248
+ if (!moduleInfo) {
1249
+ // Can't figure out module to rename.
1250
+ return undefined;
1251
+ }
1252
+ const editActions = this.renameModule(moduleInfo.filePath, moduleInfo.newFilePath, token);
1253
+ // Add file system rename.
1254
+ editActions === null || editActions === void 0 ? void 0 : editActions.fileOperations.push({
1255
+ kind: 'rename',
1256
+ oldFilePath: moduleInfo.filePath,
1257
+ newFilePath: moduleInfo.newFilePath,
1258
+ });
1259
+ if ((0, sourceMapper_1.isStubFile)(moduleInfo.filePath)) {
1260
+ const matchingFiles = this._importResolver.getSourceFilesFromStub(moduleInfo.filePath, this._configOptions.findExecEnvironment(filePath),
1261
+ /* mapCompiled */ false);
1262
+ for (const matchingFile of matchingFiles) {
1263
+ const matchingFileInfo = renameModuleProvider_1.RenameModuleProvider.getRenameModulePathInfo(matchingFile, newName);
1264
+ if (matchingFileInfo) {
1265
+ editActions === null || editActions === void 0 ? void 0 : editActions.fileOperations.push({
1266
+ kind: 'rename',
1267
+ oldFilePath: matchingFileInfo.filePath,
1268
+ newFilePath: matchingFileInfo.newFilePath,
1269
+ });
1270
+ }
1271
+ }
1272
+ }
1273
+ return editActions;
1274
+ }
1275
+ const referenceProvider = new referencesProvider_1.ReferencesProvider(this, token);
1276
+ const renameMode = this._getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace);
1277
+ switch (renameMode) {
1278
+ case 'singleFileMode':
1279
+ referenceProvider.addReferencesToResult(sourceFileInfo.sourceFile.getFilePath(),
1280
+ /* includeDeclaration */ true, referencesResult);
1281
+ break;
1282
+ case 'multiFileMode': {
1283
+ for (const curSourceFileInfo of this._sourceFileList) {
1284
+ // Make sure we only add user code to the references to prevent us
1285
+ // from accidentally changing third party library or type stub.
1286
+ if ((0, sourceFileInfoUtils_1.isUserCode)(curSourceFileInfo)) {
1287
+ // Make sure searching symbol name exists in the file.
1288
+ const content = (_a = curSourceFileInfo.sourceFile.getFileContent()) !== null && _a !== void 0 ? _a : '';
1289
+ if (!referencesResult.symbolNames.some((s) => content.search(s) >= 0)) {
1290
+ continue;
1633
1291
  }
1292
+ this._bindFile(curSourceFileInfo, content);
1293
+ referenceProvider.addReferencesToResult(curSourceFileInfo.sourceFile.getFilePath(),
1294
+ /* includeDeclaration */ true, referencesResult);
1634
1295
  }
1635
- const dottedName2 = (0, parseTreeUtils_1.getDottedName)((0, parseTreeUtils_1.getDottedNameWithGivenNodeAsLastName)(names[0]));
1636
- if (dottedName2 && (0, collectionUtils_1.arrayEquals)(dottedName1, dottedName2, (e1, e2) => e1.value === e2.value)) {
1637
- tracker.removeNodes({ node: nameNode, parseResults: parseResults });
1638
- break;
1639
- }
1296
+ // This operation can consume significant memory, so check
1297
+ // for situations where we need to discard the type cache.
1298
+ this._handleMemoryHighUsage();
1640
1299
  }
1300
+ break;
1641
1301
  }
1642
- const oldText = sourceFile.getFileContent();
1643
- const newText = (0, workspaceEditUtils_1.applyTextEditsToString)(tracker.getEdits(token).filter((v) => v.filePath === filePath), parseResults.tokenizerOutput.lines, oldText);
1644
- // We will attempt to remove unused imports multiple times since removing 1 unused import
1645
- // could make another import unused. This is due to how we calculate which import is not used.
1646
- // ex) import os, os.path, os.path.xxx
1647
- // `os.path` and `os.path.xxx` will be marked as used due to `import os`.
1648
- // once `os` is removed `os.path` will be marked as unused and so on.
1649
- // We will attempt to remove those chained unused imports up to 10 chain.
1650
- if (attempt > 10 || oldText === newText) {
1651
- return newText;
1652
- }
1653
- _updateFileContent(cloned, filePath, newText);
1654
- return _tryGetTextAfterUnusedImportsRemoved(cloned, filePath, importData, attempt + 1, token);
1302
+ case 'none':
1303
+ // Rename is not allowed.
1304
+ // ex) rename symbols from libraries.
1305
+ return undefined;
1306
+ default:
1307
+ (0, debug_1.assertNever)(renameMode);
1655
1308
  }
1656
- });
1657
- function _updateFileContent(cloned, filePath, text) {
1658
- var _a, _b;
1659
- const info = cloned.getSourceFileInfo(filePath);
1660
- const version = info ? ((_a = info.sourceFile.getClientVersion()) !== null && _a !== void 0 ? _a : 0) + 1 : 0;
1661
- const chainedFilePath = info ? (_b = info.chainedSourceFile) === null || _b === void 0 ? void 0 : _b.sourceFile.getFilePath() : undefined;
1662
- const ipythonMode = info ? info.sourceFile.getIPythonMode() : sourceFile_1.IPythonMode.None;
1663
- const isTracked = info ? info.isTracked : true;
1664
- const realFilePath = info ? info.sourceFile.getRealFilePath() : filePath;
1665
- cloned.setFileOpened(filePath, version, [{ text }], {
1666
- chainedFilePath,
1667
- ipythonMode,
1668
- isTracked,
1669
- realFilePath,
1309
+ const edits = [];
1310
+ referencesResult.locations.forEach((loc) => {
1311
+ edits.push({
1312
+ filePath: loc.path,
1313
+ range: loc.range,
1314
+ replacementText: newName,
1315
+ });
1670
1316
  });
1317
+ return { edits, fileOperations: [] };
1318
+ });
1319
+ }
1320
+ // Returns a value from 0 to 1 (or more) indicating how "full" the cache is
1321
+ // relative to some predetermined high-water mark. We'll compute this value
1322
+ // based on two easy-to-compute metrics: the number of entries in the type
1323
+ // cache and the number of parsed files.
1324
+ getCacheUsage() {
1325
+ const typeCacheEntryCount = this._evaluator.getTypeCacheEntryCount();
1326
+ const entryCountRatio = typeCacheEntryCount / 750000;
1327
+ const fileCountRatio = this._parsedFileCount / 1000;
1328
+ return Math.max(entryCountRatio, fileCountRatio);
1329
+ }
1330
+ // Discards any cached information associated with this program.
1331
+ emptyCache() {
1332
+ this._createNewEvaluator();
1333
+ this._discardCachedParseResults();
1334
+ this._parsedFileCount = 0;
1335
+ extensibility_1.Extensions.getProgramExtensions(this.rootPath).forEach((e) => (e.clearCache ? e.clearCache() : null));
1336
+ }
1337
+ test_createSourceMapper(execEnv, from) {
1338
+ return this._createSourceMapper(execEnv, vscode_languageserver_1.CancellationToken.None, /* from */ from, /* mapCompiled */ false);
1339
+ }
1340
+ _getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace) {
1341
+ // We have 2 different cases
1342
+ // Single file mode.
1343
+ // 1. rename on default workspace (ex, standalone file mode).
1344
+ // 2. rename local symbols.
1345
+ // 3. rename symbols defined in the non user open file.
1346
+ //
1347
+ // and Multi file mode.
1348
+ // 1. rename public symbols defined in user files on regular workspace (ex, open folder mode).
1349
+ const userFile = (0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo);
1350
+ if (isDefaultWorkspace ||
1351
+ (userFile && !referencesResult.requiresGlobalSearch) ||
1352
+ (!userFile &&
1353
+ sourceFileInfo.isOpenByClient &&
1354
+ referencesResult.declarations.every((d) => this.getSourceFileInfo(d.path) === sourceFileInfo))) {
1355
+ return 'singleFileMode';
1671
1356
  }
1672
- function _getNumberOfBlankLinesToInsert(parseResults, decl, position) {
1673
- if (position.line === 0 && position.character === 0) {
1674
- return 0;
1357
+ if (referencesResult.declarations.every((d) => (0, sourceFileInfoUtils_1.isUserCode)(this.getSourceFileInfo(d.path)))) {
1358
+ return 'multiFileMode';
1359
+ }
1360
+ // Rename is not allowed.
1361
+ // ex) rename symbols from libraries.
1362
+ return 'none';
1363
+ }
1364
+ _supportRenameModule(declarations, isDefaultWorkspace) {
1365
+ // Rename module is not supported for standalone file and all decls must be on a user file.
1366
+ return !isDefaultWorkspace && declarations.every((d) => (0, sourceFileInfoUtils_1.isUserCode)(this.getSourceFileInfo(d.path)));
1367
+ }
1368
+ _getReferenceResult(sourceFileInfo, filePath, position, allowModuleRename, token) {
1369
+ const execEnv = this._configOptions.findExecEnvironment(filePath);
1370
+ const referencesResult = this._getDeclarationForPosition(sourceFileInfo, position, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Rename, this._createSourceMapper(execEnv, token), token);
1371
+ if (!referencesResult) {
1372
+ return undefined;
1373
+ }
1374
+ if (allowModuleRename && referencesResult.containsOnlyImportDecls) {
1375
+ return referencesResult;
1376
+ }
1377
+ if (referencesResult.nonImportDeclarations.length === 0) {
1378
+ // There is no symbol we can rename.
1379
+ return undefined;
1380
+ }
1381
+ // Use declarations that doesn't contain import decls.
1382
+ return new referencesProvider_1.ReferencesResult(referencesResult.requiresGlobalSearch, referencesResult.nodeAtOffset, referencesResult.symbolNames, referencesResult.nonImportDeclarations, referencesResult.useCase);
1383
+ }
1384
+ _getDeclarationForPosition(sourceFileInfo, position, useCase, sourceMapper, token, reporter) {
1385
+ // If we have no completed analysis job, there's nothing to do.
1386
+ const parseResults = sourceFileInfo.sourceFile.getParseResults();
1387
+ if (!parseResults) {
1388
+ return undefined;
1389
+ }
1390
+ return referencesProvider_1.ReferencesProvider.getDeclarationForPosition(sourceMapper, parseResults, sourceFileInfo.sourceFile.getFilePath(), position, this._evaluator, reporter, useCase, token, Array.from((0, sourceFileInfoUtils_1.collectImportedByFiles)(sourceFileInfo)).map((fileInfo) => fileInfo.sourceFile));
1391
+ }
1392
+ _processModuleReferences(renameModuleProvider, filteringText, currentFilePath) {
1393
+ var _a;
1394
+ // _sourceFileList contains every user files that match "include" pattern including
1395
+ // py file even if corresponding pyi exists.
1396
+ for (const currentFileInfo of this._sourceFileList) {
1397
+ // Make sure we only touch user code to prevent us
1398
+ // from accidentally changing third party library or type stub.
1399
+ if (!(0, sourceFileInfoUtils_1.isUserCode)(currentFileInfo)) {
1400
+ continue;
1675
1401
  }
1676
- let previousStatement;
1677
- const offset = (0, positionUtils_1.convertPositionToOffset)(position, parseResults.tokenizerOutput.lines);
1678
- if (offset && parseResults.parseTree.statements.length > 0) {
1679
- previousStatement = parseResults.parseTree.statements.reduce((prev, curr) => offset < curr.start ? prev : curr);
1402
+ // If module name isn't mentioned in the current file, skip the file
1403
+ // except the file that got actually renamed/moved.
1404
+ // The file that got moved might have relative import paths we need to update.
1405
+ const filePath = currentFileInfo.sourceFile.getFilePath();
1406
+ const content = (_a = currentFileInfo.sourceFile.getFileContent()) !== null && _a !== void 0 ? _a : '';
1407
+ if (filePath !== currentFilePath && content.indexOf(filteringText) < 0) {
1408
+ continue;
1680
1409
  }
1681
- // This basically try to add some blank lines after the last line with text.
1682
- let linesToAdd = 0;
1683
- if (previousStatement) {
1684
- if ((0, declaration_1.isVariableDeclaration)(decl)) {
1685
- switch (previousStatement.nodeType) {
1686
- case 47 /* StatementList */:
1687
- // Small statement such as call, assignment, etc.
1688
- linesToAdd = 0;
1689
- break;
1690
- case 10 /* Class */:
1691
- case 28 /* Function */:
1692
- linesToAdd = 2;
1693
- break;
1694
- default:
1695
- // any other statement such as if, while, etc. we will add 1 blank line.
1696
- linesToAdd = 1;
1410
+ this._bindFile(currentFileInfo, content);
1411
+ const parseResult = currentFileInfo.sourceFile.getParseResults();
1412
+ if (!parseResult) {
1413
+ continue;
1414
+ }
1415
+ renameModuleProvider.renameReferences(parseResult);
1416
+ // This operation can consume significant memory, so check
1417
+ // for situations where we need to discard the type cache.
1418
+ this._handleMemoryHighUsage();
1419
+ }
1420
+ }
1421
+ _handleMemoryHighUsage() {
1422
+ const cacheUsage = this._cacheManager.getCacheUsage();
1423
+ // If the total cache has exceeded 75%, determine whether we should empty
1424
+ // the cache.
1425
+ if (cacheUsage > 0.75) {
1426
+ const usedHeapRatio = this._cacheManager.getUsedHeapRatio(this._configOptions.verboseOutput ? this._console : undefined);
1427
+ // The type cache uses a Map, which has an absolute limit of 2^24 entries
1428
+ // before it will fail. If we cross the 95% mark, we'll empty the cache.
1429
+ const absoluteMaxCacheEntryCount = (1 << 24) * 0.9;
1430
+ const typeCacheEntryCount = this._evaluator.getTypeCacheEntryCount();
1431
+ // If we use more than 90% of the heap size limit, avoid a crash
1432
+ // by emptying the type cache.
1433
+ if (typeCacheEntryCount > absoluteMaxCacheEntryCount || usedHeapRatio > 0.9) {
1434
+ this._cacheManager.emptyCache(this._console);
1435
+ }
1436
+ }
1437
+ }
1438
+ // Discards all cached parse results and file contents to free up memory.
1439
+ // It does not discard cached index results or diagnostics for files.
1440
+ _discardCachedParseResults() {
1441
+ for (const sourceFileInfo of this._sourceFileList) {
1442
+ sourceFileInfo.sourceFile.dropParseAndBindInfo();
1443
+ }
1444
+ }
1445
+ // Wrapper function that should be used when invoking this._evaluator
1446
+ // with a cancellation token. It handles cancellation exceptions and
1447
+ // any other unexpected exceptions.
1448
+ _runEvaluatorWithCancellationToken(token, callback) {
1449
+ try {
1450
+ if (token) {
1451
+ return this._evaluator.runWithCancellationToken(token, callback);
1452
+ }
1453
+ else {
1454
+ return callback();
1455
+ }
1456
+ }
1457
+ catch (e) {
1458
+ // An unexpected exception occurred, potentially leaving the current evaluator
1459
+ // in an inconsistent state. Discard it and replace it with a fresh one. It is
1460
+ // Cancellation exceptions are known to handle this correctly.
1461
+ if (!cancellationUtils_1.OperationCanceledException.is(e)) {
1462
+ this._createNewEvaluator();
1463
+ }
1464
+ throw e;
1465
+ }
1466
+ }
1467
+ // Returns a list of empty file diagnostic entries for the files
1468
+ // that have been removed. This is needed to clear out the
1469
+ // errors for files that have been deleted or closed.
1470
+ _removeUnneededFiles() {
1471
+ const fileDiagnostics = [];
1472
+ // If a file is no longer tracked, opened or shadowed, it can
1473
+ // be removed from the program.
1474
+ for (let i = 0; i < this._sourceFileList.length;) {
1475
+ const fileInfo = this._sourceFileList[i];
1476
+ if (!this._isFileNeeded(fileInfo)) {
1477
+ fileDiagnostics.push({
1478
+ filePath: fileInfo.sourceFile.getFilePath(),
1479
+ version: fileInfo.sourceFile.getClientVersion(),
1480
+ diagnostics: [],
1481
+ });
1482
+ fileInfo.sourceFile.prepareForClose();
1483
+ this._removeSourceFileFromListAndMap(fileInfo.sourceFile.getFilePath(), i);
1484
+ // Unlink any imports and remove them from the list if
1485
+ // they are no longer referenced.
1486
+ fileInfo.imports.forEach((importedFile) => {
1487
+ const indexToRemove = importedFile.importedBy.findIndex((fi) => fi === fileInfo);
1488
+ if (indexToRemove < 0) {
1489
+ return;
1697
1490
  }
1698
- }
1699
- else {
1700
- linesToAdd = 2;
1701
- }
1491
+ importedFile.importedBy.splice(indexToRemove, 1);
1492
+ // See if we need to remove the imported file because it
1493
+ // is no longer needed. If its index is >= i, it will be
1494
+ // removed when we get to it.
1495
+ if (!this._isFileNeeded(importedFile)) {
1496
+ const indexToRemove = this._sourceFileList.findIndex((fi) => fi === importedFile);
1497
+ if (indexToRemove >= 0 && indexToRemove < i) {
1498
+ fileDiagnostics.push({
1499
+ filePath: importedFile.sourceFile.getFilePath(),
1500
+ version: importedFile.sourceFile.getClientVersion(),
1501
+ diagnostics: [],
1502
+ });
1503
+ importedFile.sourceFile.prepareForClose();
1504
+ this._removeSourceFileFromListAndMap(importedFile.sourceFile.getFilePath(), indexToRemove);
1505
+ i--;
1506
+ }
1507
+ }
1508
+ });
1509
+ // Remove any shadowed files corresponding to this file.
1510
+ fileInfo.shadowedBy.forEach((shadowedFile) => {
1511
+ shadowedFile.shadows = shadowedFile.shadows.filter((f) => f !== fileInfo);
1512
+ });
1513
+ fileInfo.shadowedBy = [];
1702
1514
  }
1703
- // If the position is not at the beginning of the line, we need to add 1 more '\n'
1704
- // to start from blank line.
1705
- linesToAdd += position.character !== 0 ? 1 : 0;
1706
- // If there are already blank lines, we only add the difference.
1707
- const desiredBlankLines = linesToAdd;
1708
- const startingLine = position.character !== 0 ? position.line : position.line - 1;
1709
- for (let i = 0; i < desiredBlankLines; i++) {
1710
- const currentLine = startingLine - i;
1711
- if (currentLine < 0 || !(0, parseTreeUtils_1.isBlankLine)(parseResults, currentLine)) {
1712
- break;
1515
+ else {
1516
+ // If we're showing the user errors only for open files, clear
1517
+ // out the errors for the now-closed file.
1518
+ if (!this._shouldCheckFile(fileInfo) && fileInfo.diagnosticsVersion !== undefined) {
1519
+ fileDiagnostics.push({
1520
+ filePath: fileInfo.sourceFile.getFilePath(),
1521
+ version: fileInfo.sourceFile.getClientVersion(),
1522
+ diagnostics: [],
1523
+ });
1524
+ fileInfo.diagnosticsVersion = undefined;
1713
1525
  }
1714
- linesToAdd--;
1526
+ i++;
1715
1527
  }
1716
- return linesToAdd;
1717
1528
  }
1529
+ return fileDiagnostics;
1718
1530
  }
1719
- clone() {
1720
- var _a;
1721
- const program = new Program(this._importResolver, this._configOptions, this._console, new logTracker_1.LogTracker(this._console, 'Cloned'));
1722
- // Cloned program will use whatever user files the program currently has.
1723
- const userFiles = this.getUserFiles();
1724
- program.setTrackedFiles(userFiles.map((i) => i.sourceFile.getFilePath()));
1725
- program.markAllFilesDirty(true);
1726
- // Make sure we keep editor content (open file) which could be different than one in the file system.
1727
- for (const fileInfo of this.getOpened()) {
1728
- const version = fileInfo.sourceFile.getClientVersion();
1729
- if (version === undefined) {
1730
- continue;
1531
+ _isFileNeeded(fileInfo, skipFileNeededCheck) {
1532
+ if (fileInfo.sourceFile.isFileDeleted()) {
1533
+ return false;
1534
+ }
1535
+ if (!!skipFileNeededCheck || fileInfo.isTracked || fileInfo.isOpenByClient) {
1536
+ return true;
1537
+ }
1538
+ if (fileInfo.shadows.length > 0) {
1539
+ return true;
1540
+ }
1541
+ if (fileInfo.importedBy.length === 0) {
1542
+ return false;
1543
+ }
1544
+ // It's possible for a cycle of files to be imported
1545
+ // by a tracked file but then abandoned. The import cycle
1546
+ // will keep the entire group "alive" if we don't detect
1547
+ // the condition and garbage collect them.
1548
+ return this._isImportNeededRecursive(fileInfo, new Set());
1549
+ }
1550
+ _isImportNeededRecursive(fileInfo, recursionSet) {
1551
+ if (fileInfo.isTracked || fileInfo.isOpenByClient || fileInfo.shadows.length > 0) {
1552
+ return true;
1553
+ }
1554
+ const filePath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, fileInfo.sourceFile.getFilePath());
1555
+ // Avoid infinite recursion.
1556
+ if (recursionSet.has(filePath)) {
1557
+ return false;
1558
+ }
1559
+ recursionSet.add(filePath);
1560
+ for (const importerInfo of fileInfo.importedBy) {
1561
+ if (this._isImportNeededRecursive(importerInfo, recursionSet)) {
1562
+ return true;
1731
1563
  }
1732
- program.setFileOpened(fileInfo.sourceFile.getFilePath(), version, [{ text: fileInfo.sourceFile.getOpenFileContents() }], {
1733
- chainedFilePath: (_a = fileInfo.chainedSourceFile) === null || _a === void 0 ? void 0 : _a.sourceFile.getFilePath(),
1734
- ipythonMode: fileInfo.sourceFile.getIPythonMode(),
1735
- isTracked: fileInfo.isTracked,
1736
- realFilePath: fileInfo.sourceFile.getRealFilePath(),
1737
- });
1738
1564
  }
1739
- return program;
1565
+ return false;
1740
1566
  }
1741
- canRenameSymbolAtPosition(filePath, position, isDefaultWorkspace, allowModuleRename, token) {
1742
- return this._runEvaluatorWithCancellationToken(token, () => {
1743
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1744
- if (!sourceFileInfo) {
1745
- return undefined;
1567
+ _createSourceMapper(execEnv, token, from, mapCompiled, preferStubs) {
1568
+ const sourceMapper = new sourceMapper_1.SourceMapper(this._importResolver, execEnv, this._evaluator, (stubFilePath, implFilePath) => {
1569
+ let stubFileInfo = this.getSourceFileInfo(stubFilePath);
1570
+ if (!stubFileInfo) {
1571
+ // Special case for import statement like "import X.Y". The SourceFile
1572
+ // for X might not be in memory since import `X.Y` only brings in Y.
1573
+ stubFileInfo = this.addInterimFile(stubFilePath);
1746
1574
  }
1747
- this._bindFile(sourceFileInfo);
1748
- const referencesResult = this._getReferenceResult(sourceFileInfo, filePath, position, allowModuleRename, token);
1749
- if (!referencesResult) {
1750
- return undefined;
1575
+ this._addShadowedFile(stubFileInfo, implFilePath);
1576
+ return this.getBoundSourceFile(implFilePath);
1577
+ }, (f) => {
1578
+ let fileInfo = this.getBoundSourceFileInfo(f);
1579
+ if (!fileInfo) {
1580
+ // Special case for import statement like "import X.Y". The SourceFile
1581
+ // for X might not be in memory since import `X.Y` only brings in Y.
1582
+ fileInfo = this.addInterimFile(f);
1583
+ // Even though this file is not referenced by anything, make sure
1584
+ // we have a parse tree for the doc string.
1585
+ this._parseFile(fileInfo, /* content */ undefined, /* force */ true);
1751
1586
  }
1752
- if (referencesResult.containsOnlyImportDecls &&
1753
- !this._supportRenameModule(referencesResult.declarations, isDefaultWorkspace)) {
1754
- return undefined;
1587
+ return fileInfo;
1588
+ }, mapCompiled !== null && mapCompiled !== void 0 ? mapCompiled : false, preferStubs !== null && preferStubs !== void 0 ? preferStubs : false, from, token);
1589
+ return sourceMapper;
1590
+ }
1591
+ _isImportAllowed(importer, importResult, isImportStubFile) {
1592
+ // Don't import native libs. We don't want to track these files,
1593
+ // and we definitely don't want to attempt to parse them.
1594
+ if (importResult.isNativeLib) {
1595
+ return false;
1596
+ }
1597
+ let thirdPartyImportAllowed = this._configOptions.useLibraryCodeForTypes ||
1598
+ (importResult.importType === 1 /* ThirdParty */ && !!importResult.pyTypedInfo) ||
1599
+ (importResult.importType === 2 /* Local */ && importer.isThirdPartyPyTypedPresent);
1600
+ if (importResult.importType === 1 /* ThirdParty */ ||
1601
+ (importer.isThirdPartyImport && importResult.importType === 2 /* Local */)) {
1602
+ if (this._allowedThirdPartyImports) {
1603
+ if (importResult.isRelative) {
1604
+ // If it's a relative import, we'll allow it because the
1605
+ // importer was already deemed to be allowed.
1606
+ thirdPartyImportAllowed = true;
1607
+ }
1608
+ else if (this._allowedThirdPartyImports.some((importName) => {
1609
+ // If this import name is the one that was explicitly
1610
+ // allowed or is a child of that import name,
1611
+ // it's considered allowed.
1612
+ if (importResult.importName === importName) {
1613
+ return true;
1614
+ }
1615
+ if (importResult.importName.startsWith(importName + '.')) {
1616
+ return true;
1617
+ }
1618
+ return false;
1619
+ })) {
1620
+ thirdPartyImportAllowed = true;
1621
+ }
1755
1622
  }
1756
- const renameMode = this._getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace);
1757
- if (renameMode === 'none') {
1758
- return undefined;
1623
+ else if (importer.isThirdPartyImport && this._configOptions.useLibraryCodeForTypes) {
1624
+ // If the importing file is a third-party import, allow importing of
1625
+ // additional third-party imports. This supports the case where the importer
1626
+ // is in a py.typed library but is importing from another non-py.typed
1627
+ // library. It also supports the case where someone explicitly opens a
1628
+ // library source file in their editor.
1629
+ thirdPartyImportAllowed = true;
1759
1630
  }
1760
- // Return the range of the symbol.
1761
- const parseResult = sourceFileInfo.sourceFile.getParseResults();
1762
- return {
1763
- range: (0, positionUtils_1.convertTextRangeToRange)(referencesResult.nodeAtOffset, parseResult.tokenizerOutput.lines),
1764
- declarations: referencesResult.declarations,
1765
- };
1766
- });
1767
- }
1768
- renameSymbolAtPosition(filePath, position, newName, isDefaultWorkspace, allowModuleRename, token) {
1769
- return this._runEvaluatorWithCancellationToken(token, () => {
1770
- var _a;
1771
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1772
- if (!sourceFileInfo) {
1773
- return undefined;
1631
+ else if (importResult.isNamespacePackage &&
1632
+ importResult.filteredImplicitImports.some((implicitImport) => !!implicitImport.pyTypedInfo)) {
1633
+ // Handle the case where the import targets a namespace package, and a
1634
+ // submodule contained within it has a py.typed marker.
1635
+ thirdPartyImportAllowed = true;
1774
1636
  }
1775
- this._bindFile(sourceFileInfo);
1776
- const referencesResult = this._getReferenceResult(sourceFileInfo, filePath, position, allowModuleRename, token);
1777
- if (!referencesResult) {
1778
- return undefined;
1637
+ // Some libraries ship with stub files that import from non-stubs. Don't
1638
+ // explore those.
1639
+ // Don't explore any third-party files unless they're type stub files
1640
+ // or we've been told explicitly that third-party imports are OK.
1641
+ if (!isImportStubFile) {
1642
+ return thirdPartyImportAllowed;
1779
1643
  }
1780
- if (referencesResult.containsOnlyImportDecls) {
1781
- // All decls must be on a user file.
1782
- if (!this._supportRenameModule(referencesResult.declarations, isDefaultWorkspace)) {
1783
- return undefined;
1784
- }
1785
- const moduleInfo = renameModuleProvider_1.RenameModuleProvider.getRenameModulePathInfo(renameModuleProvider_1.RenameModuleProvider.getRenameModulePath(referencesResult.declarations), newName);
1786
- if (!moduleInfo) {
1787
- // Can't figure out module to rename.
1788
- return undefined;
1644
+ }
1645
+ return true;
1646
+ }
1647
+ _updateSourceFileImports(sourceFileInfo, options) {
1648
+ const filesAdded = [];
1649
+ // Get the new list of imports and see if it changed from the last
1650
+ // list of imports for this file.
1651
+ const imports = sourceFileInfo.sourceFile.getImports();
1652
+ // Create a local function that determines whether the import should
1653
+ // be considered a "third-party import" and whether it is coming from
1654
+ // a third-party package that claims to be typed. An import is
1655
+ // considered third-party if it is external to the importer
1656
+ // or is internal but the importer is itself a third-party package.
1657
+ const getThirdPartyImportInfo = (importResult) => {
1658
+ let isThirdPartyImport = false;
1659
+ let isPyTypedPresent = false;
1660
+ if (importResult.importType === 1 /* ThirdParty */) {
1661
+ isThirdPartyImport = true;
1662
+ if (importResult.pyTypedInfo) {
1663
+ isPyTypedPresent = true;
1789
1664
  }
1790
- const editActions = this.renameModule(moduleInfo.filePath, moduleInfo.newFilePath, token);
1791
- // Add file system rename.
1792
- editActions === null || editActions === void 0 ? void 0 : editActions.fileOperations.push({
1793
- kind: 'rename',
1794
- oldFilePath: moduleInfo.filePath,
1795
- newFilePath: moduleInfo.newFilePath,
1665
+ }
1666
+ else if (sourceFileInfo.isThirdPartyImport && importResult.importType === 2 /* Local */) {
1667
+ isThirdPartyImport = true;
1668
+ if (sourceFileInfo.isThirdPartyPyTypedPresent) {
1669
+ isPyTypedPresent = true;
1670
+ }
1671
+ }
1672
+ return {
1673
+ isThirdPartyImport,
1674
+ isPyTypedPresent,
1675
+ };
1676
+ };
1677
+ // Create a map of unique imports, since imports can appear more than once.
1678
+ const newImportPathMap = new Map();
1679
+ // Add chained source file as import if it exists.
1680
+ if (sourceFileInfo.chainedSourceFile) {
1681
+ if (sourceFileInfo.chainedSourceFile.sourceFile.isFileDeleted()) {
1682
+ sourceFileInfo.chainedSourceFile = undefined;
1683
+ }
1684
+ else {
1685
+ const filePath = sourceFileInfo.chainedSourceFile.sourceFile.getFilePath();
1686
+ newImportPathMap.set((0, pathUtils_1.normalizePathCase)(this.fileSystem, filePath), {
1687
+ path: filePath,
1688
+ isTypeshedFile: false,
1689
+ isThirdPartyImport: false,
1690
+ isPyTypedPresent: false,
1796
1691
  });
1797
- if ((0, sourceMapper_1.isStubFile)(moduleInfo.filePath)) {
1798
- const matchingFiles = this._importResolver.getSourceFilesFromStub(moduleInfo.filePath, this._configOptions.findExecEnvironment(filePath),
1799
- /* mapCompiled */ false);
1800
- for (const matchingFile of matchingFiles) {
1801
- const matchingFileInfo = renameModuleProvider_1.RenameModuleProvider.getRenameModulePathInfo(matchingFile, newName);
1802
- if (matchingFileInfo) {
1803
- editActions === null || editActions === void 0 ? void 0 : editActions.fileOperations.push({
1804
- kind: 'rename',
1805
- oldFilePath: matchingFileInfo.filePath,
1806
- newFilePath: matchingFileInfo.newFilePath,
1692
+ }
1693
+ }
1694
+ imports.forEach((importResult) => {
1695
+ if (importResult.isImportFound) {
1696
+ if (this._isImportAllowed(sourceFileInfo, importResult, importResult.isStubFile)) {
1697
+ if (importResult.resolvedPaths.length > 0) {
1698
+ const filePath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1];
1699
+ if (filePath) {
1700
+ const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult);
1701
+ newImportPathMap.set((0, pathUtils_1.normalizePathCase)(this.fileSystem, filePath), {
1702
+ path: filePath,
1703
+ isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile,
1704
+ isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport,
1705
+ isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent,
1807
1706
  });
1808
1707
  }
1809
1708
  }
1810
1709
  }
1811
- return editActions;
1812
- }
1813
- const renameMode = this._getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace);
1814
- switch (renameMode) {
1815
- case 'singleFileMode':
1816
- sourceFileInfo.sourceFile.addReferences(referencesResult, true, this._evaluator, token);
1817
- break;
1818
- case 'multiFileMode': {
1819
- for (const curSourceFileInfo of this._sourceFileList) {
1820
- // Make sure we only add user code to the references to prevent us
1821
- // from accidentally changing third party library or type stub.
1822
- if ((0, sourceFileInfoUtils_1.isUserCode)(curSourceFileInfo)) {
1823
- // Make sure searching symbol name exists in the file.
1824
- const content = (_a = curSourceFileInfo.sourceFile.getFileContent()) !== null && _a !== void 0 ? _a : '';
1825
- if (!referencesResult.symbolNames.some((s) => content.search(s) >= 0)) {
1826
- continue;
1710
+ importResult.filteredImplicitImports.forEach((implicitImport) => {
1711
+ if (this._isImportAllowed(sourceFileInfo, importResult, implicitImport.isStubFile)) {
1712
+ if (!implicitImport.isNativeLib) {
1713
+ const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult);
1714
+ newImportPathMap.set((0, pathUtils_1.normalizePathCase)(this.fileSystem, implicitImport.path), {
1715
+ path: implicitImport.path,
1716
+ isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile,
1717
+ isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport,
1718
+ isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent,
1719
+ });
1720
+ }
1721
+ }
1722
+ });
1723
+ // If the stub was found but the non-stub (source) file was not, dump
1724
+ // the failure to the log for diagnostic purposes.
1725
+ if (importResult.nonStubImportResult && !importResult.nonStubImportResult.isImportFound) {
1726
+ // We'll skip this for imports from within stub files and imports that target
1727
+ // stdlib typeshed stubs because many of these are known to not have
1728
+ // associated source files, and we don't want to fill the logs with noise.
1729
+ if (!sourceFileInfo.sourceFile.isStubFile() && !importResult.isStdlibTypeshedFile) {
1730
+ if (options.verboseOutput) {
1731
+ this._console.info(`Could not resolve source for '${importResult.importName}' ` +
1732
+ `in file '${sourceFileInfo.sourceFile.getFilePath()}'`);
1733
+ if (importResult.nonStubImportResult.importFailureInfo) {
1734
+ importResult.nonStubImportResult.importFailureInfo.forEach((diag) => {
1735
+ this._console.info(` ${diag}`);
1736
+ });
1827
1737
  }
1828
- this._bindFile(curSourceFileInfo, content);
1829
- curSourceFileInfo.sourceFile.addReferences(referencesResult, true, this._evaluator, token);
1830
1738
  }
1831
- // This operation can consume significant memory, so check
1832
- // for situations where we need to discard the type cache.
1833
- this._handleMemoryHighUsage();
1834
1739
  }
1835
- break;
1836
1740
  }
1837
- case 'none':
1838
- // Rename is not allowed.
1839
- // ex) rename symbols from libraries.
1840
- return undefined;
1841
- default:
1842
- (0, debug_1.assertNever)(renameMode);
1843
1741
  }
1844
- const edits = [];
1845
- referencesResult.locations.forEach((loc) => {
1846
- edits.push({
1847
- filePath: loc.path,
1848
- range: loc.range,
1849
- replacementText: newName,
1850
- });
1851
- });
1852
- return { edits, fileOperations: [] };
1742
+ else if (options.verboseOutput) {
1743
+ this._console.info(`Could not import '${importResult.importName}' ` +
1744
+ `in file '${sourceFileInfo.sourceFile.getFilePath()}'`);
1745
+ if (importResult.importFailureInfo) {
1746
+ importResult.importFailureInfo.forEach((diag) => {
1747
+ this._console.info(` ${diag}`);
1748
+ });
1749
+ }
1750
+ }
1853
1751
  });
1854
- }
1855
- getCallForPosition(filePath, position, token) {
1856
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1857
- if (!sourceFileInfo) {
1858
- return undefined;
1859
- }
1860
- this._bindFile(sourceFileInfo);
1861
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1862
- const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition(this._createSourceMapper(execEnv, token, sourceFileInfo), position, this._evaluator, undefined, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Reference, token);
1863
- if (!referencesResult || referencesResult.declarations.length === 0) {
1864
- return undefined;
1865
- }
1866
- const { targetDecl, callItemUri, symbolName } = callHierarchyProvider_1.CallHierarchyProvider.getTargetDeclaration(referencesResult, filePath);
1867
- return callHierarchyProvider_1.CallHierarchyProvider.getCallForDeclaration(symbolName, targetDecl, this._evaluator, token, callItemUri);
1868
- }
1869
- getIncomingCallsForPosition(filePath, position, token) {
1870
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1871
- if (!sourceFileInfo) {
1872
- return undefined;
1873
- }
1874
- this._bindFile(sourceFileInfo);
1875
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1876
- const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition(this._createSourceMapper(execEnv, token, sourceFileInfo), position, this._evaluator, undefined, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Reference, token);
1877
- if (!referencesResult || referencesResult.declarations.length === 0) {
1878
- return undefined;
1879
- }
1880
- const { targetDecl, symbolName } = callHierarchyProvider_1.CallHierarchyProvider.getTargetDeclaration(referencesResult, filePath);
1881
- let items = [];
1882
- const sourceFiles = targetDecl.type === 8 /* Alias */ ? [sourceFileInfo] : this._sourceFileList;
1883
- for (const curSourceFileInfo of sourceFiles) {
1884
- if ((0, sourceFileInfoUtils_1.isUserCode)(curSourceFileInfo) || curSourceFileInfo.isOpenByClient) {
1885
- this._bindFile(curSourceFileInfo);
1886
- const itemsToAdd = callHierarchyProvider_1.CallHierarchyProvider.getIncomingCallsForDeclaration(curSourceFileInfo.sourceFile.getFilePath(), symbolName, targetDecl, curSourceFileInfo.sourceFile.getParseResults(), this._evaluator, token);
1887
- if (itemsToAdd) {
1888
- items = items.concat(...itemsToAdd);
1752
+ const updatedImportMap = new Map();
1753
+ sourceFileInfo.imports.forEach((importInfo) => {
1754
+ const oldFilePath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, importInfo.sourceFile.getFilePath());
1755
+ // A previous import was removed.
1756
+ if (!newImportPathMap.has(oldFilePath)) {
1757
+ importInfo.importedBy = importInfo.importedBy.filter((fi) => (0, pathUtils_1.normalizePathCase)(this.fileSystem, fi.sourceFile.getFilePath()) !==
1758
+ (0, pathUtils_1.normalizePathCase)(this.fileSystem, sourceFileInfo.sourceFile.getFilePath()));
1759
+ }
1760
+ else {
1761
+ updatedImportMap.set(oldFilePath, importInfo);
1762
+ }
1763
+ });
1764
+ // See if there are any new imports to be added.
1765
+ newImportPathMap.forEach((importInfo, normalizedImportPath) => {
1766
+ if (!updatedImportMap.has(normalizedImportPath)) {
1767
+ // We found a new import to add. See if it's already part
1768
+ // of the program.
1769
+ let importedFileInfo = this.getSourceFileInfo(importInfo.path);
1770
+ if (!importedFileInfo) {
1771
+ const importName = this._getImportNameForFile(importInfo.path);
1772
+ const sourceFile = new sourceFile_1.SourceFile(this.fileSystem, importInfo.path, importName, importInfo.isThirdPartyImport, importInfo.isPyTypedPresent, this._console, this._logTracker);
1773
+ importedFileInfo = {
1774
+ sourceFile,
1775
+ isTracked: false,
1776
+ isOpenByClient: false,
1777
+ isTypeshedFile: importInfo.isTypeshedFile,
1778
+ isThirdPartyImport: importInfo.isThirdPartyImport,
1779
+ isThirdPartyPyTypedPresent: importInfo.isPyTypedPresent,
1780
+ diagnosticsVersion: undefined,
1781
+ imports: [],
1782
+ importedBy: [],
1783
+ shadows: [],
1784
+ shadowedBy: [],
1785
+ };
1786
+ this._addToSourceFileListAndMap(importedFileInfo);
1787
+ filesAdded.push(importedFileInfo);
1889
1788
  }
1890
- // This operation can consume significant memory, so check
1891
- // for situations where we need to discard the type cache.
1892
- this._handleMemoryHighUsage();
1789
+ importedFileInfo.importedBy.push(sourceFileInfo);
1790
+ updatedImportMap.set(normalizedImportPath, importedFileInfo);
1893
1791
  }
1792
+ });
1793
+ // Update the imports list. It should now map the set of imports
1794
+ // specified by the source file.
1795
+ sourceFileInfo.imports = [];
1796
+ newImportPathMap.forEach((_, path) => {
1797
+ if (this.getSourceFileInfo(path)) {
1798
+ sourceFileInfo.imports.push(this.getSourceFileInfo(path));
1799
+ }
1800
+ });
1801
+ // Resolve the builtins import for the file. This needs to be
1802
+ // analyzed before the file can be analyzed.
1803
+ sourceFileInfo.builtinsImport = undefined;
1804
+ const builtinsImport = sourceFileInfo.sourceFile.getBuiltinsImport();
1805
+ if (builtinsImport && builtinsImport.isImportFound) {
1806
+ const resolvedBuiltinsPath = builtinsImport.resolvedPaths[builtinsImport.resolvedPaths.length - 1];
1807
+ sourceFileInfo.builtinsImport = this.getSourceFileInfo(resolvedBuiltinsPath);
1894
1808
  }
1895
- return items;
1896
- }
1897
- getOutgoingCallsForPosition(filePath, position, token) {
1898
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1899
- if (!sourceFileInfo) {
1900
- return undefined;
1901
- }
1902
- this._bindFile(sourceFileInfo);
1903
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1904
- const referencesResult = sourceFileInfo.sourceFile.getDeclarationForPosition(this._createSourceMapper(execEnv, token, sourceFileInfo), position, this._evaluator, undefined, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Reference, token);
1905
- if (!referencesResult || referencesResult.declarations.length === 0) {
1906
- return undefined;
1907
- }
1908
- const { targetDecl } = callHierarchyProvider_1.CallHierarchyProvider.getTargetDeclaration(referencesResult, filePath);
1909
- return callHierarchyProvider_1.CallHierarchyProvider.getOutgoingCallsForDeclaration(targetDecl, sourceFileInfo.sourceFile.getParseResults(), this._evaluator, token);
1910
- }
1911
- performQuickAction(filePath, command, args, token) {
1912
- const sourceFileInfo = this.getSourceFileInfo(filePath);
1913
- if (!sourceFileInfo) {
1914
- return undefined;
1809
+ // Resolve the ipython display import for the file. This needs to be
1810
+ // analyzed before the file can be analyzed.
1811
+ sourceFileInfo.ipythonDisplayImport = undefined;
1812
+ const ipythonDisplayImport = sourceFileInfo.sourceFile.getIPythonDisplayImport();
1813
+ if (ipythonDisplayImport && ipythonDisplayImport.isImportFound) {
1814
+ const resolvedIPythonDisplayPath = ipythonDisplayImport.resolvedPaths[ipythonDisplayImport.resolvedPaths.length - 1];
1815
+ sourceFileInfo.ipythonDisplayImport = this.getSourceFileInfo(resolvedIPythonDisplayPath);
1915
1816
  }
1916
- this._bindFile(sourceFileInfo);
1917
- return sourceFileInfo.sourceFile.performQuickAction(command, args, token);
1918
- }
1919
- // Returns a value from 0 to 1 (or more) indicating how "full" the cache is
1920
- // relative to some predetermined high-water mark. We'll compute this value
1921
- // based on two easy-to-compute metrics: the number of entries in the type
1922
- // cache and the number of parsed files.
1923
- getCacheUsage() {
1924
- const typeCacheEntryCount = this._evaluator.getTypeCacheEntryCount();
1925
- const entryCountRatio = typeCacheEntryCount / 750000;
1926
- const fileCountRatio = this._parsedFileCount / 1000;
1927
- return Math.max(entryCountRatio, fileCountRatio);
1817
+ return filesAdded;
1928
1818
  }
1929
- // Discards any cached information associated with this program.
1930
- emptyCache() {
1931
- this._createNewEvaluator();
1932
- this._discardCachedParseResults();
1933
- this._parsedFileCount = 0;
1934
- extensibility_1.Extensions.getProgramExtensions(this.rootPath).forEach((e) => (e.clearCache ? e.clearCache() : null));
1819
+ _removeSourceFileFromListAndMap(filePath, indexToRemove) {
1820
+ this._sourceFileMap.delete((0, pathUtils_1.normalizePathCase)(this.fileSystem, filePath));
1821
+ this._sourceFileList.splice(indexToRemove, 1);
1935
1822
  }
1936
- test_createSourceMapper(execEnv, from) {
1937
- return this._createSourceMapper(execEnv, vscode_languageserver_1.CancellationToken.None, /* from */ from, /* mapCompiled */ false);
1823
+ _addToSourceFileListAndMap(fileInfo) {
1824
+ const filePath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, fileInfo.sourceFile.getFilePath());
1825
+ // We should never add a file with the same path twice.
1826
+ (0, debug_1.assert)(!this._sourceFileMap.has(filePath));
1827
+ this._sourceFileList.push(fileInfo);
1828
+ this._sourceFileMap.set(filePath, fileInfo);
1938
1829
  }
1939
- _getRenameSymbolMode(sourceFileInfo, referencesResult, isDefaultWorkspace) {
1940
- // We have 2 different cases
1941
- // Single file mode.
1942
- // 1. rename on default workspace (ex, standalone file mode).
1943
- // 2. rename local symbols.
1944
- // 3. rename symbols defined in the non user open file.
1945
- //
1946
- // and Multi file mode.
1947
- // 1. rename public symbols defined in user files on regular workspace (ex, open folder mode).
1948
- const userFile = (0, sourceFileInfoUtils_1.isUserCode)(sourceFileInfo);
1949
- if (isDefaultWorkspace ||
1950
- (userFile && !referencesResult.requiresGlobalSearch) ||
1951
- (!userFile &&
1952
- sourceFileInfo.isOpenByClient &&
1953
- referencesResult.declarations.every((d) => this.getSourceFileInfo(d.path) === sourceFileInfo))) {
1954
- return 'singleFileMode';
1830
+ static _getPrintTypeFlags(configOptions) {
1831
+ let flags = 0 /* None */;
1832
+ if (configOptions.diagnosticRuleSet.printUnknownAsAny) {
1833
+ flags |= 1 /* PrintUnknownWithAny */;
1834
+ }
1835
+ if (configOptions.diagnosticRuleSet.omitConditionalConstraint) {
1836
+ flags |= 64 /* OmitConditionalConstraint */;
1837
+ }
1838
+ if (configOptions.diagnosticRuleSet.omitTypeArgsIfUnknown) {
1839
+ flags |= 2 /* OmitTypeArgumentsIfUnknown */;
1840
+ }
1841
+ if (configOptions.diagnosticRuleSet.omitUnannotatedParamType) {
1842
+ flags |= 4 /* OmitUnannotatedParamType */;
1955
1843
  }
1956
- if (referencesResult.declarations.every((d) => (0, sourceFileInfoUtils_1.isUserCode)(this.getSourceFileInfo(d.path)))) {
1957
- return 'multiFileMode';
1844
+ if (configOptions.diagnosticRuleSet.pep604Printing) {
1845
+ flags |= 8 /* PEP604 */;
1958
1846
  }
1959
- // Rename is not allowed.
1960
- // ex) rename symbols from libraries.
1961
- return 'none';
1847
+ return flags;
1962
1848
  }
1963
- _supportRenameModule(declarations, isDefaultWorkspace) {
1964
- // Rename module is not supported for standalone file and all decls must be on a user file.
1965
- return !isDefaultWorkspace && declarations.every((d) => (0, sourceFileInfoUtils_1.isUserCode)(this.getSourceFileInfo(d.path)));
1849
+ _getImportNameForFile(filePath) {
1850
+ // We allow illegal module names (e.g. names that include "-" in them)
1851
+ // because we want a unique name for each module even if it cannot be
1852
+ // imported through an "import" statement. It's important to have a
1853
+ // unique name in case two modules declare types with the same local
1854
+ // name. The type checker uses the fully-qualified (unique) module name
1855
+ // to differentiate between such types.
1856
+ const moduleNameAndType = this._importResolver.getModuleNameForImport(filePath, this._configOptions.getDefaultExecEnvironment(),
1857
+ /* allowIllegalModuleName */ true);
1858
+ return moduleNameAndType.moduleName;
1966
1859
  }
1967
- _getReferenceResult(sourceFileInfo, filePath, position, allowModuleRename, token) {
1968
- const execEnv = this._configOptions.findExecEnvironment(filePath);
1969
- const referencesResult = this._getDeclarationForPosition(sourceFileInfo, position, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Rename, this._createSourceMapper(execEnv, token), token);
1970
- if (!referencesResult) {
1971
- return undefined;
1860
+ // A "shadowed" file is a python source file that has been added to the program because
1861
+ // it "shadows" a type stub file for purposes of finding doc strings and definitions.
1862
+ // We need to track the relationship so if the original type stub is removed from the
1863
+ // program, we can remove the corresponding shadowed file and any files it imports.
1864
+ _addShadowedFile(stubFile, shadowImplPath) {
1865
+ let shadowFileInfo = this.getSourceFileInfo(shadowImplPath);
1866
+ if (!shadowFileInfo) {
1867
+ shadowFileInfo = this.addInterimFile(shadowImplPath);
1972
1868
  }
1973
- if (allowModuleRename && referencesResult.containsOnlyImportDecls) {
1974
- return referencesResult;
1869
+ if (!shadowFileInfo.shadows.includes(stubFile)) {
1870
+ shadowFileInfo.shadows.push(stubFile);
1975
1871
  }
1976
- if (referencesResult.nonImportDeclarations.length === 0) {
1977
- // There is no symbol we can rename.
1978
- return undefined;
1872
+ if (!stubFile.shadowedBy.includes(shadowFileInfo)) {
1873
+ stubFile.shadowedBy.push(shadowFileInfo);
1979
1874
  }
1980
- // Use declarations that doesn't contain import decls.
1981
- return new referencesProvider_1.ReferencesResult(referencesResult.requiresGlobalSearch, referencesResult.nodeAtOffset, referencesResult.symbolNames, referencesResult.nonImportDeclarations, referencesResult.useCase);
1982
- }
1983
- _getDeclarationForPosition(sourceFileInfo, position, useCase, sourceMapper, token, reporter) {
1984
- return sourceFileInfo.sourceFile.getDeclarationForPosition(sourceMapper, position, this._evaluator, reporter, useCase, token, Array.from((0, sourceFileInfoUtils_1.collectImportedByFiles)(sourceFileInfo)).map((fileInfo) => fileInfo.sourceFile));
1875
+ return shadowFileInfo.sourceFile;
1985
1876
  }
1986
- _processModuleReferences(renameModuleProvider, filteringText, currentFilePath) {
1987
- var _a;
1988
- // _sourceFileList contains every user files that match "include" pattern including
1989
- // py file even if corresponding pyi exists.
1990
- for (const currentFileInfo of this._sourceFileList) {
1991
- // Make sure we only touch user code to prevent us
1992
- // from accidentally changing third party library or type stub.
1993
- if (!(0, sourceFileInfoUtils_1.isUserCode)(currentFileInfo)) {
1994
- continue;
1995
- }
1996
- // If module name isn't mentioned in the current file, skip the file
1997
- // except the file that got actually renamed/moved.
1998
- // The file that got moved might have relative import paths we need to update.
1999
- const filePath = currentFileInfo.sourceFile.getFilePath();
2000
- const content = (_a = currentFileInfo.sourceFile.getFileContent()) !== null && _a !== void 0 ? _a : '';
2001
- if (filePath !== currentFilePath && content.indexOf(filteringText) < 0) {
2002
- continue;
2003
- }
2004
- this._bindFile(currentFileInfo, content);
2005
- const parseResult = currentFileInfo.sourceFile.getParseResults();
2006
- if (!parseResult) {
2007
- continue;
2008
- }
2009
- renameModuleProvider.renameReferences(parseResult);
2010
- // This operation can consume significant memory, so check
2011
- // for situations where we need to discard the type cache.
2012
- this._handleMemoryHighUsage();
2013
- }
1877
+ _createInterimFileInfo(filePath) {
1878
+ const importName = this._getImportNameForFile(filePath);
1879
+ const sourceFile = new sourceFile_1.SourceFile(this.fileSystem, filePath, importName,
1880
+ /* isThirdPartyImport */ false,
1881
+ /* isInPyTypedPackage */ false, this._console, this._logTracker);
1882
+ const sourceFileInfo = {
1883
+ sourceFile,
1884
+ isTracked: false,
1885
+ isOpenByClient: false,
1886
+ isTypeshedFile: false,
1887
+ isThirdPartyImport: false,
1888
+ isThirdPartyPyTypedPresent: false,
1889
+ diagnosticsVersion: undefined,
1890
+ imports: [],
1891
+ importedBy: [],
1892
+ shadows: [],
1893
+ shadowedBy: [],
1894
+ };
1895
+ return sourceFileInfo;
2014
1896
  }
2015
- _handleMemoryHighUsage() {
2016
- const cacheUsage = this._cacheManager.getCacheUsage();
2017
- // If the total cache has exceeded 75%, determine whether we should empty
2018
- // the cache.
2019
- if (cacheUsage > 0.75) {
2020
- const usedHeapRatio = this._cacheManager.getUsedHeapRatio(this._configOptions.verboseOutput ? this._console : undefined);
2021
- // The type cache uses a Map, which has an absolute limit of 2^24 entries
2022
- // before it will fail. If we cross the 95% mark, we'll empty the cache.
2023
- const absoluteMaxCacheEntryCount = (1 << 24) * 0.9;
2024
- const typeCacheEntryCount = this._evaluator.getTypeCacheEntryCount();
2025
- // If we use more than 90% of the heap size limit, avoid a crash
2026
- // by emptying the type cache.
2027
- if (typeCacheEntryCount > absoluteMaxCacheEntryCount || usedHeapRatio > 0.9) {
2028
- this._cacheManager.emptyCache(this._console);
2029
- }
1897
+ _createNewEvaluator() {
1898
+ if (this._evaluator) {
1899
+ // We shouldn't need to call this, but there appears to be a bug
1900
+ // in the v8 garbage collector where it's unable to resolve orphaned
1901
+ // objects without us giving it some assistance.
1902
+ this._evaluator.disposeEvaluator();
2030
1903
  }
1904
+ this._evaluator = (0, typeEvaluatorWithTracker_1.createTypeEvaluatorWithTracker)(this._lookUpImport, {
1905
+ printTypeFlags: Program._getPrintTypeFlags(this._configOptions),
1906
+ logCalls: this._configOptions.logTypeEvaluationTime,
1907
+ minimumLoggingThreshold: this._configOptions.typeEvaluationTimeThreshold,
1908
+ evaluateUnknownImportsAsAny: !!this._configOptions.evaluateUnknownImportsAsAny,
1909
+ verifyTypeCacheEvaluatorFlags: !!this._configOptions.internalTestMode,
1910
+ }, this._logTracker, this._configOptions.logTypeEvaluationTime
1911
+ ? (0, tracePrinter_1.createTracePrinter)(this._importResolver.getImportRoots(this._configOptions.findExecEnvironment(this._configOptions.projectRoot)))
1912
+ : undefined);
1913
+ return this._evaluator;
2031
1914
  }
2032
- // Discards all cached parse results and file contents to free up memory.
2033
- // It does not discard cached index results or diagnostics for files.
2034
- _discardCachedParseResults() {
2035
- for (const sourceFileInfo of this._sourceFileList) {
2036
- sourceFileInfo.sourceFile.dropParseAndBindInfo();
1915
+ _parseFile(fileToParse, content, skipFileNeededCheck) {
1916
+ if (!this._isFileNeeded(fileToParse, skipFileNeededCheck) || !fileToParse.sourceFile.isParseRequired()) {
1917
+ return;
2037
1918
  }
2038
- }
2039
- // Wrapper function that should be used when invoking this._evaluator
2040
- // with a cancellation token. It handles cancellation exceptions and
2041
- // any other unexpected exceptions.
2042
- _runEvaluatorWithCancellationToken(token, callback) {
2043
- try {
2044
- if (token) {
2045
- return this._evaluator.runWithCancellationToken(token, callback);
2046
- }
2047
- else {
2048
- return callback();
2049
- }
1919
+ // SourceFile.parse should only be called here in the program, as calling it
1920
+ // elsewhere could break the entire dependency graph maintained by the program.
1921
+ // Other parts of the program should use _parseFile to create ParseResults from
1922
+ // the sourceFile. For standalone parseResults, use parseFile or the Parser directly.
1923
+ if (fileToParse.sourceFile.parse(this._configOptions, this._importResolver, content)) {
1924
+ this._parsedFileCount++;
1925
+ this._updateSourceFileImports(fileToParse, this._configOptions);
2050
1926
  }
2051
- catch (e) {
2052
- // An unexpected exception occurred, potentially leaving the current evaluator
2053
- // in an inconsistent state. Discard it and replace it with a fresh one. It is
2054
- // Cancellation exceptions are known to handle this correctly.
2055
- if (!cancellationUtils_1.OperationCanceledException.is(e)) {
2056
- this._createNewEvaluator();
2057
- }
2058
- throw e;
1927
+ if (fileToParse.sourceFile.isFileDeleted()) {
1928
+ fileToParse.isTracked = false;
1929
+ // Mark any files that depend on this file as dirty
1930
+ // also. This will retrigger analysis of these other files.
1931
+ const markDirtySet = new Set();
1932
+ this._markFileDirtyRecursive(fileToParse, markDirtySet);
1933
+ // Invalidate the import resolver's cache as well.
1934
+ this._importResolver.invalidateCache();
2059
1935
  }
2060
1936
  }
2061
- // Returns a list of empty file diagnostic entries for the files
2062
- // that have been removed. This is needed to clear out the
2063
- // errors for files that have been deleted or closed.
2064
- _removeUnneededFiles() {
2065
- const fileDiagnostics = [];
2066
- // If a file is no longer tracked, opened or shadowed, it can
2067
- // be removed from the program.
2068
- for (let i = 0; i < this._sourceFileList.length;) {
2069
- const fileInfo = this._sourceFileList[i];
2070
- if (!this._isFileNeeded(fileInfo)) {
2071
- fileDiagnostics.push({
2072
- filePath: fileInfo.sourceFile.getFilePath(),
2073
- version: fileInfo.sourceFile.getClientVersion(),
2074
- diagnostics: [],
2075
- });
2076
- fileInfo.sourceFile.prepareForClose();
2077
- this._removeSourceFileFromListAndMap(fileInfo.sourceFile.getFilePath(), i);
2078
- // Unlink any imports and remove them from the list if
2079
- // they are no longer referenced.
2080
- fileInfo.imports.forEach((importedFile) => {
2081
- const indexToRemove = importedFile.importedBy.findIndex((fi) => fi === fileInfo);
2082
- if (indexToRemove < 0) {
2083
- return;
2084
- }
2085
- importedFile.importedBy.splice(indexToRemove, 1);
2086
- // See if we need to remove the imported file because it
2087
- // is no longer needed. If its index is >= i, it will be
2088
- // removed when we get to it.
2089
- if (!this._isFileNeeded(importedFile)) {
2090
- const indexToRemove = this._sourceFileList.findIndex((fi) => fi === importedFile);
2091
- if (indexToRemove >= 0 && indexToRemove < i) {
2092
- fileDiagnostics.push({
2093
- filePath: importedFile.sourceFile.getFilePath(),
2094
- version: importedFile.sourceFile.getClientVersion(),
2095
- diagnostics: [],
2096
- });
2097
- importedFile.sourceFile.prepareForClose();
2098
- this._removeSourceFileFromListAndMap(importedFile.sourceFile.getFilePath(), indexToRemove);
2099
- i--;
2100
- }
2101
- }
2102
- });
2103
- // Remove any shadowed files corresponding to this file.
2104
- fileInfo.shadowedBy.forEach((shadowedFile) => {
2105
- shadowedFile.shadows = shadowedFile.shadows.filter((f) => f !== fileInfo);
2106
- });
2107
- fileInfo.shadowedBy = [];
2108
- }
2109
- else {
2110
- // If we're showing the user errors only for open files, clear
2111
- // out the errors for the now-closed file.
2112
- if (!this._shouldCheckFile(fileInfo) && fileInfo.diagnosticsVersion !== undefined) {
2113
- fileDiagnostics.push({
2114
- filePath: fileInfo.sourceFile.getFilePath(),
2115
- version: fileInfo.sourceFile.getClientVersion(),
2116
- diagnostics: [],
2117
- });
2118
- fileInfo.diagnosticsVersion = undefined;
2119
- }
2120
- i++;
2121
- }
1937
+ _getImplicitImports(file) {
1938
+ var _a, _b;
1939
+ // If file is not parsed, then chainedSourceFile, ipythonDisplayImport,
1940
+ // builtinsImport might not exist or incorrect.
1941
+ // They will be added when _parseFile is called and _updateSourceFileImports ran.
1942
+ if (file.builtinsImport === file) {
1943
+ return undefined;
2122
1944
  }
2123
- return fileDiagnostics;
1945
+ const tryReturn = (input) => {
1946
+ if (!input || input.sourceFile.isFileDeleted()) {
1947
+ return undefined;
1948
+ }
1949
+ return input;
1950
+ };
1951
+ return (_b = (_a = tryReturn(file.chainedSourceFile)) !== null && _a !== void 0 ? _a : tryReturn(file.ipythonDisplayImport)) !== null && _b !== void 0 ? _b : file.builtinsImport;
2124
1952
  }
2125
- _isFileNeeded(fileInfo) {
2126
- if (fileInfo.sourceFile.isFileDeleted()) {
2127
- return false;
2128
- }
2129
- if (fileInfo.isTracked || fileInfo.isOpenByClient) {
2130
- return true;
1953
+ _bindImplicitImports(fileToAnalyze, skipFileNeededCheck) {
1954
+ // Get all of the potential imports for this file.
1955
+ const implicitImports = [];
1956
+ const implicitSet = new Set();
1957
+ let nextImplicitImport = this._getImplicitImports(fileToAnalyze);
1958
+ while (nextImplicitImport) {
1959
+ const implicitPath = nextImplicitImport.sourceFile.getFilePath();
1960
+ if (implicitSet.has(implicitPath)) {
1961
+ // We've found a cycle. Break out of the loop.
1962
+ debug.fail(`Found a cycle in implicit imports files for ${implicitPath}`);
1963
+ }
1964
+ implicitSet.add(implicitPath);
1965
+ implicitImports.push(nextImplicitImport);
1966
+ this._parseFile(nextImplicitImport, /* content */ undefined, skipFileNeededCheck);
1967
+ nextImplicitImport = this._getImplicitImports(nextImplicitImport);
2131
1968
  }
2132
- if (fileInfo.shadows.length > 0) {
2133
- return true;
1969
+ if (implicitImports.length === 0) {
1970
+ return;
2134
1971
  }
2135
- if (fileInfo.importedBy.length === 0) {
2136
- return false;
1972
+ // Go in reverse order (so top of chain is first).
1973
+ let implicitImport = implicitImports.pop();
1974
+ while (implicitImport) {
1975
+ // Bind this file, but don't recurse into its imports.
1976
+ this._bindFile(implicitImport, undefined, skipFileNeededCheck, /* isImplicitImport */ true);
1977
+ implicitImport = implicitImports.pop();
2137
1978
  }
2138
- // It's possible for a cycle of files to be imported
2139
- // by a tracked file but then abandoned. The import cycle
2140
- // will keep the entire group "alive" if we don't detect
2141
- // the condition and garbage collect them.
2142
- return this._isImportNeededRecursive(fileInfo, new Set());
2143
1979
  }
2144
- _isImportNeededRecursive(fileInfo, recursionSet) {
2145
- if (fileInfo.isTracked || fileInfo.isOpenByClient || fileInfo.shadows.length > 0) {
2146
- return true;
2147
- }
2148
- const filePath = (0, pathUtils_1.normalizePathCase)(this._fs, fileInfo.sourceFile.getFilePath());
2149
- // Avoid infinite recursion.
2150
- if (recursionSet.has(filePath)) {
2151
- return false;
1980
+ // Binds the specified file and all of its dependencies, recursively. If
1981
+ // it runs out of time, it returns true. If it completes, it returns false.
1982
+ _bindFile(fileToAnalyze, content, skipFileNeededCheck, isImplicitImport) {
1983
+ var _a, _b;
1984
+ if (!this._isFileNeeded(fileToAnalyze, skipFileNeededCheck) || !fileToAnalyze.sourceFile.isBindingRequired()) {
1985
+ return;
2152
1986
  }
2153
- recursionSet.add(filePath);
2154
- for (const importerInfo of fileInfo.importedBy) {
2155
- if (this._isImportNeededRecursive(importerInfo, recursionSet)) {
2156
- return true;
1987
+ this._parseFile(fileToAnalyze, content, skipFileNeededCheck);
1988
+ // Create a function to get the scope info.
1989
+ const getScopeIfAvailable = (fileInfo) => {
1990
+ if (!fileInfo || fileInfo === fileToAnalyze) {
1991
+ return undefined;
1992
+ }
1993
+ // If the file was deleted, there's no scope to return.
1994
+ if (fileInfo.sourceFile.isFileDeleted()) {
1995
+ return undefined;
1996
+ }
1997
+ const parseResults = fileInfo.sourceFile.getParseResults();
1998
+ if (!parseResults) {
1999
+ return undefined;
2000
+ }
2001
+ // File should already be bound because of the chained file binding above.
2002
+ const scope = AnalyzerNodeInfo.getScope(parseResults.parseTree);
2003
+ return scope;
2004
+ };
2005
+ let builtinsScope;
2006
+ if (fileToAnalyze.builtinsImport && fileToAnalyze.builtinsImport !== fileToAnalyze) {
2007
+ // Bind all of the implicit imports first. So we don't recurse into them.
2008
+ if (!isImplicitImport) {
2009
+ this._bindImplicitImports(fileToAnalyze);
2157
2010
  }
2011
+ // If it is not builtin module itself, we need to parse and bind
2012
+ // the ipython display import if required. Otherwise, get builtin module.
2013
+ builtinsScope =
2014
+ (_b = (_a = getScopeIfAvailable(fileToAnalyze.chainedSourceFile)) !== null && _a !== void 0 ? _a : getScopeIfAvailable(fileToAnalyze.ipythonDisplayImport)) !== null && _b !== void 0 ? _b : getScopeIfAvailable(fileToAnalyze.builtinsImport);
2158
2015
  }
2159
- return false;
2016
+ let futureImports = fileToAnalyze.sourceFile.getParseResults().futureImports;
2017
+ if (fileToAnalyze.chainedSourceFile) {
2018
+ futureImports = this._getEffectiveFutureImports(futureImports, fileToAnalyze.chainedSourceFile);
2019
+ }
2020
+ fileToAnalyze.effectiveFutureImports = futureImports.size > 0 ? futureImports : undefined;
2021
+ fileToAnalyze.sourceFile.bind(this._configOptions, this._lookUpImport, builtinsScope, futureImports);
2160
2022
  }
2161
- _createSourceMapper(execEnv, token, from, mapCompiled, preferStubs) {
2162
- const sourceMapper = new sourceMapper_1.SourceMapper(this._importResolver, execEnv, this._evaluator, (stubFilePath, implFilePath) => {
2163
- let stubFileInfo = this.getSourceFileInfo(stubFilePath);
2164
- if (!stubFileInfo) {
2165
- // Special case for import statement like "import X.Y". The SourceFile
2166
- // for X might not be in memory since import `X.Y` only brings in Y.
2167
- stubFileInfo = this.addInterimFile(stubFilePath);
2023
+ _getEffectiveFutureImports(futureImports, chainedSourceFile) {
2024
+ var _a;
2025
+ const effectiveFutureImports = new Set(futureImports);
2026
+ (_a = chainedSourceFile.effectiveFutureImports) === null || _a === void 0 ? void 0 : _a.forEach((value) => {
2027
+ effectiveFutureImports.add(value);
2028
+ });
2029
+ return effectiveFutureImports;
2030
+ }
2031
+ // Build a map of all modules within this program and the module-
2032
+ // level scope that contains the symbol table for the module.
2033
+ _buildModuleSymbolsMap(sourceFileToExclude, libraryMap, includeSymbolsFromIndices, token) {
2034
+ // If we have library map, always use the map for library symbols.
2035
+ const predicate = (s) => {
2036
+ if (!libraryMap) {
2037
+ // We don't have any prebuilt indices, so we need to include
2038
+ // all files.
2039
+ return true;
2168
2040
  }
2169
- this._addShadowedFile(stubFileInfo, implFilePath);
2170
- return this.getBoundSourceFile(implFilePath);
2171
- }, (f) => {
2172
- let fileInfo = this.getBoundSourceFileInfo(f);
2173
- if (!fileInfo) {
2174
- // Special case for import statement like "import X.Y". The SourceFile
2175
- // for X might not be in memory since import `X.Y` only brings in Y.
2176
- fileInfo = this.addInterimFile(f);
2177
- // Even though this file is not referenced by anything, make sure
2178
- // we have a parse tree for the doc string.
2179
- this._parseFile(fileInfo, /* content */ undefined, /* force */ true);
2041
+ if (!this._configOptions.indexing) {
2042
+ // We have some prebuilt indices such as stdlib, but indexing is disabled.
2043
+ // Include files we don't have prebuilt indices.
2044
+ return libraryMap.get(s.sourceFile.getFilePath()) === undefined;
2180
2045
  }
2181
- return fileInfo;
2182
- }, mapCompiled !== null && mapCompiled !== void 0 ? mapCompiled : false, preferStubs !== null && preferStubs !== void 0 ? preferStubs : false, from, token);
2183
- return sourceMapper;
2046
+ // We have prebuilt indices for third party libraries. Include only
2047
+ // user files.
2048
+ return (0, sourceFileInfoUtils_1.isUserCode)(s);
2049
+ };
2050
+ // Only include import alias from user files if indexing is off for now.
2051
+ // Currently, when indexing is off, we don't do import alias deduplication, so
2052
+ // adding import alias is cheap. But when indexing is on, we do deduplication, which
2053
+ // require resolveAliasDeclaration that can cause more files to be parsed and bound.
2054
+ return (0, autoImporter_1.buildModuleSymbolsMap)(this._sourceFileList.filter((s) => s !== sourceFileToExclude && predicate(s)), includeSymbolsFromIndices, token);
2184
2055
  }
2185
- _isImportAllowed(importer, importResult, isImportStubFile) {
2186
- // Don't import native libs. We don't want to track these files,
2187
- // and we definitely don't want to attempt to parse them.
2188
- if (importResult.isNativeLib) {
2189
- return false;
2056
+ _shouldCheckFile(fileInfo) {
2057
+ // Always do a full checking for a file that's open in the editor.
2058
+ if (fileInfo.isOpenByClient) {
2059
+ return true;
2190
2060
  }
2191
- let thirdPartyImportAllowed = this._configOptions.useLibraryCodeForTypes ||
2192
- (importResult.importType === 1 /* ThirdParty */ && !!importResult.pyTypedInfo) ||
2193
- (importResult.importType === 2 /* Local */ && importer.isThirdPartyPyTypedPresent);
2194
- if (importResult.importType === 1 /* ThirdParty */ ||
2195
- (importer.isThirdPartyImport && importResult.importType === 2 /* Local */)) {
2196
- if (this._allowedThirdPartyImports) {
2197
- if (importResult.isRelative) {
2198
- // If it's a relative import, we'll allow it because the
2199
- // importer was already deemed to be allowed.
2200
- thirdPartyImportAllowed = true;
2201
- }
2202
- else if (this._allowedThirdPartyImports.some((importName) => {
2203
- // If this import name is the one that was explicitly
2204
- // allowed or is a child of that import name,
2205
- // it's considered allowed.
2206
- if (importResult.importName === importName) {
2207
- return true;
2208
- }
2209
- if (importResult.importName.startsWith(importName + '.')) {
2210
- return true;
2211
- }
2212
- return false;
2213
- })) {
2214
- thirdPartyImportAllowed = true;
2215
- }
2216
- }
2217
- else if (importer.isThirdPartyImport && this._configOptions.useLibraryCodeForTypes) {
2218
- // If the importing file is a third-party import, allow importing of
2219
- // additional third-party imports. This supports the case where the importer
2220
- // is in a py.typed library but is importing from another non-py.typed
2221
- // library. It also supports the case where someone explicitly opens a
2222
- // library source file in their editor.
2223
- thirdPartyImportAllowed = true;
2224
- }
2225
- else if (importResult.isNamespacePackage &&
2226
- importResult.filteredImplicitImports.some((implicitImport) => !!implicitImport.pyTypedInfo)) {
2227
- // Handle the case where the import targets a namespace package, and a
2228
- // submodule contained within it has a py.typed marker.
2229
- thirdPartyImportAllowed = true;
2230
- }
2231
- // Some libraries ship with stub files that import from non-stubs. Don't
2232
- // explore those.
2233
- // Don't explore any third-party files unless they're type stub files
2234
- // or we've been told explicitly that third-party imports are OK.
2235
- if (!isImportStubFile) {
2236
- return thirdPartyImportAllowed;
2237
- }
2061
+ // If the file isn't currently open, only perform full checking for
2062
+ // files that are tracked, and only if the checkOnlyOpenFiles is disabled.
2063
+ if (!this._configOptions.checkOnlyOpenFiles && fileInfo.isTracked) {
2064
+ return true;
2238
2065
  }
2239
- return true;
2066
+ return false;
2240
2067
  }
2241
- _updateSourceFileImports(sourceFileInfo, options) {
2242
- const filesAdded = [];
2243
- // Get the new list of imports and see if it changed from the last
2244
- // list of imports for this file.
2245
- const imports = sourceFileInfo.sourceFile.getImports();
2246
- // Create a local function that determines whether the import should
2247
- // be considered a "third-party import" and whether it is coming from
2248
- // a third-party package that claims to be typed. An import is
2249
- // considered third-party if it is external to the importer
2250
- // or is internal but the importer is itself a third-party package.
2251
- const getThirdPartyImportInfo = (importResult) => {
2252
- let isThirdPartyImport = false;
2253
- let isPyTypedPresent = false;
2254
- if (importResult.importType === 1 /* ThirdParty */) {
2255
- isThirdPartyImport = true;
2256
- if (importResult.pyTypedInfo) {
2257
- isPyTypedPresent = true;
2258
- }
2068
+ _checkTypes(fileToCheck, token) {
2069
+ return this._logTracker.log(`analyzing: ${fileToCheck.sourceFile.getFilePath()}`, (logState) => {
2070
+ // If the file isn't needed because it was eliminated from the
2071
+ // transitive closure or deleted, skip the file rather than wasting
2072
+ // time on it.
2073
+ if (!this._isFileNeeded(fileToCheck)) {
2074
+ logState.suppress();
2075
+ return false;
2259
2076
  }
2260
- else if (sourceFileInfo.isThirdPartyImport && importResult.importType === 2 /* Local */) {
2261
- isThirdPartyImport = true;
2262
- if (sourceFileInfo.isThirdPartyPyTypedPresent) {
2263
- isPyTypedPresent = true;
2264
- }
2077
+ if (!fileToCheck.sourceFile.isCheckingRequired()) {
2078
+ logState.suppress();
2079
+ return false;
2265
2080
  }
2266
- return {
2267
- isThirdPartyImport,
2268
- isPyTypedPresent,
2269
- };
2270
- };
2271
- // Create a map of unique imports, since imports can appear more than once.
2272
- const newImportPathMap = new Map();
2273
- // Add chained source file as import if it exists.
2274
- if (sourceFileInfo.chainedSourceFile) {
2275
- if (sourceFileInfo.chainedSourceFile.sourceFile.isFileDeleted()) {
2276
- sourceFileInfo.chainedSourceFile = undefined;
2081
+ if (!this._shouldCheckFile(fileToCheck)) {
2082
+ logState.suppress();
2083
+ return false;
2277
2084
  }
2278
- else {
2279
- const filePath = sourceFileInfo.chainedSourceFile.sourceFile.getFilePath();
2280
- newImportPathMap.set((0, pathUtils_1.normalizePathCase)(this._fs, filePath), {
2281
- path: filePath,
2282
- isTypeshedFile: false,
2283
- isThirdPartyImport: false,
2284
- isPyTypedPresent: false,
2285
- });
2085
+ this._bindFile(fileToCheck);
2086
+ if (this._preCheckCallback) {
2087
+ const parseResults = fileToCheck.sourceFile.getParseResults();
2088
+ if (parseResults) {
2089
+ this._preCheckCallback(parseResults, this._evaluator);
2090
+ }
2286
2091
  }
2287
- }
2288
- imports.forEach((importResult) => {
2289
- if (importResult.isImportFound) {
2290
- if (this._isImportAllowed(sourceFileInfo, importResult, importResult.isStubFile)) {
2291
- if (importResult.resolvedPaths.length > 0) {
2292
- const filePath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1];
2293
- if (filePath) {
2294
- const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult);
2295
- newImportPathMap.set((0, pathUtils_1.normalizePathCase)(this._fs, filePath), {
2296
- path: filePath,
2297
- isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile,
2298
- isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport,
2299
- isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent,
2300
- });
2092
+ if (!this._disableChecker) {
2093
+ // For ipython, make sure we check all its dependent files first since
2094
+ // their results can affect this file's result.
2095
+ let dependentFiles = undefined;
2096
+ if (fileToCheck.sourceFile.getIPythonMode() === sourceFile_1.IPythonMode.CellDocs) {
2097
+ dependentFiles = [];
2098
+ const importedByFiles = (0, sourceFileInfoUtils_1.collectImportedByFiles)(fileToCheck);
2099
+ for (const file of importedByFiles) {
2100
+ if (!(0, sourceFileInfoUtils_1.isUserCode)(file)) {
2101
+ continue;
2301
2102
  }
2302
- }
2303
- }
2304
- importResult.filteredImplicitImports.forEach((implicitImport) => {
2305
- if (this._isImportAllowed(sourceFileInfo, importResult, implicitImport.isStubFile)) {
2306
- if (!implicitImport.isNativeLib) {
2307
- const thirdPartyTypeInfo = getThirdPartyImportInfo(importResult);
2308
- newImportPathMap.set((0, pathUtils_1.normalizePathCase)(this._fs, implicitImport.path), {
2309
- path: implicitImport.path,
2310
- isTypeshedFile: !!importResult.isStdlibTypeshedFile || !!importResult.isThirdPartyTypeshedFile,
2311
- isThirdPartyImport: thirdPartyTypeInfo.isThirdPartyImport,
2312
- isPyTypedPresent: thirdPartyTypeInfo.isPyTypedPresent,
2313
- });
2103
+ // If the file is already analyzed, it will be no op.
2104
+ // And make sure we don't dump parse tree and etc while
2105
+ // recursively calling checker. Otherwise, inner check
2106
+ // can dump parse tree required by outer check.
2107
+ const handle = this._cacheManager.pauseTracking();
2108
+ try {
2109
+ this._checkTypes(file, token);
2314
2110
  }
2315
- }
2316
- });
2317
- // If the stub was found but the non-stub (source) file was not, dump
2318
- // the failure to the log for diagnostic purposes.
2319
- if (importResult.nonStubImportResult && !importResult.nonStubImportResult.isImportFound) {
2320
- // We'll skip this for imports from within stub files and imports that target
2321
- // stdlib typeshed stubs because many of these are known to not have
2322
- // associated source files, and we don't want to fill the logs with noise.
2323
- if (!sourceFileInfo.sourceFile.isStubFile() && !importResult.isStdlibTypeshedFile) {
2324
- if (options.verboseOutput) {
2325
- this._console.info(`Could not resolve source for '${importResult.importName}' ` +
2326
- `in file '${sourceFileInfo.sourceFile.getFilePath()}'`);
2327
- if (importResult.nonStubImportResult.importFailureInfo) {
2328
- importResult.nonStubImportResult.importFailureInfo.forEach((diag) => {
2329
- this._console.info(` ${diag}`);
2330
- });
2331
- }
2111
+ finally {
2112
+ handle.dispose();
2113
+ }
2114
+ const parseResults = file.sourceFile.getParseResults();
2115
+ if (parseResults) {
2116
+ dependentFiles.push(parseResults);
2332
2117
  }
2333
2118
  }
2334
2119
  }
2120
+ const execEnv = this._configOptions.findExecEnvironment(fileToCheck.sourceFile.getFilePath());
2121
+ fileToCheck.sourceFile.check(this._importResolver, this._evaluator, this._createSourceMapper(execEnv, token, fileToCheck), dependentFiles);
2335
2122
  }
2336
- else if (options.verboseOutput) {
2337
- this._console.info(`Could not import '${importResult.importName}' ` +
2338
- `in file '${sourceFileInfo.sourceFile.getFilePath()}'`);
2339
- if (importResult.importFailureInfo) {
2340
- importResult.importFailureInfo.forEach((diag) => {
2341
- this._console.info(` ${diag}`);
2123
+ // For very large programs, we may need to discard the evaluator and
2124
+ // its cached types to avoid running out of heap space.
2125
+ this._handleMemoryHighUsage();
2126
+ // Detect import cycles that involve the file.
2127
+ if (this._configOptions.diagnosticRuleSet.reportImportCycles !== 'none') {
2128
+ // Don't detect import cycles when doing type stub generation. Some
2129
+ // third-party modules are pretty convoluted.
2130
+ if (!this._allowedThirdPartyImports) {
2131
+ // We need to force all of the files to be parsed and build
2132
+ // a closure map for the files.
2133
+ const closureMap = new Map();
2134
+ this._getImportsRecursive(fileToCheck, closureMap, 0);
2135
+ closureMap.forEach((file) => {
2136
+ timing_1.timingStats.cycleDetectionTime.timeOperation(() => {
2137
+ const filesVisitedMap = new Map();
2138
+ if (!this._detectAndReportImportCycles(file, filesVisitedMap)) {
2139
+ // If no cycles were found in any of the files we visited,
2140
+ // set a flag to indicates that we don't need to visit them again
2141
+ // on subsequent cycle checks.
2142
+ filesVisitedMap.forEach((sourceFileInfo) => {
2143
+ sourceFileInfo.sourceFile.setNoCircularDependencyConfirmed();
2144
+ });
2145
+ }
2146
+ });
2342
2147
  });
2343
2148
  }
2344
2149
  }
2150
+ return true;
2345
2151
  });
2346
- const updatedImportMap = new Map();
2347
- sourceFileInfo.imports.forEach((importInfo) => {
2348
- const oldFilePath = (0, pathUtils_1.normalizePathCase)(this._fs, importInfo.sourceFile.getFilePath());
2349
- // A previous import was removed.
2350
- if (!newImportPathMap.has(oldFilePath)) {
2351
- importInfo.importedBy = importInfo.importedBy.filter((fi) => (0, pathUtils_1.normalizePathCase)(this._fs, fi.sourceFile.getFilePath()) !==
2352
- (0, pathUtils_1.normalizePathCase)(this._fs, sourceFileInfo.sourceFile.getFilePath()));
2152
+ }
2153
+ // Builds a map of files that includes the specified file and all of the files
2154
+ // it imports (recursively) and ensures that all such files. If any of these files
2155
+ // have already been checked (they and their recursive imports have completed the
2156
+ // check phase), they are not included in the results.
2157
+ _getImportsRecursive(file, closureMap, recursionCount) {
2158
+ // If the file is already in the closure map, we found a cyclical
2159
+ // dependency. Don't recur further.
2160
+ const filePath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, file.sourceFile.getFilePath());
2161
+ if (closureMap.has(filePath)) {
2162
+ return;
2163
+ }
2164
+ // If the import chain is too long, emit an error. Otherwise we
2165
+ // risk blowing the stack.
2166
+ if (recursionCount > _maxImportDepth) {
2167
+ file.sourceFile.setHitMaxImportDepth(_maxImportDepth);
2168
+ return;
2169
+ }
2170
+ // Add the file to the closure map.
2171
+ closureMap.set(filePath, file);
2172
+ // If this file hasn't already been parsed, parse it now. This will
2173
+ // discover any files it imports. Skip this if the file is part
2174
+ // of a library. We'll assume that no cycles will be generated from
2175
+ // library code or typeshed stubs.
2176
+ if ((0, sourceFileInfoUtils_1.isUserCode)(file)) {
2177
+ this._parseFile(file);
2178
+ }
2179
+ // Recursively add the file's imports.
2180
+ for (const importedFileInfo of file.imports) {
2181
+ this._getImportsRecursive(importedFileInfo, closureMap, recursionCount + 1);
2182
+ }
2183
+ }
2184
+ _detectAndReportImportCycles(sourceFileInfo, filesVisited, dependencyChain = [], dependencyMap = new Map()) {
2185
+ // Don't bother checking for typestub files or third-party files.
2186
+ if (sourceFileInfo.sourceFile.isStubFile() || sourceFileInfo.isThirdPartyImport) {
2187
+ return false;
2188
+ }
2189
+ // If we've already confirmed that this source file isn't part of a
2190
+ // cycle, we can skip it entirely.
2191
+ if (sourceFileInfo.sourceFile.isNoCircularDependencyConfirmed()) {
2192
+ return false;
2193
+ }
2194
+ const filePath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, sourceFileInfo.sourceFile.getFilePath());
2195
+ filesVisited.set(filePath, sourceFileInfo);
2196
+ let detectedCycle = false;
2197
+ if (dependencyMap.has(filePath)) {
2198
+ // We detect a cycle (partial or full). A full cycle is one that is
2199
+ // rooted in the file at the start of our dependency chain. A partial
2200
+ // cycle loops back on some other file in the dependency chain. We
2201
+ // will report only full cycles here and leave the reporting of
2202
+ // partial cycles to other passes.
2203
+ detectedCycle = true;
2204
+ // Look for chains at least two in length. A file that contains
2205
+ // an "import . from X" will technically create a cycle with
2206
+ // itself, but those are not interesting to report.
2207
+ if (dependencyChain.length > 1 && sourceFileInfo === dependencyChain[0]) {
2208
+ this._logImportCycle(dependencyChain);
2353
2209
  }
2354
- else {
2355
- updatedImportMap.set(oldFilePath, importInfo);
2210
+ }
2211
+ else {
2212
+ // If we've already checked this dependency along
2213
+ // some other path, we can skip it.
2214
+ if (dependencyMap.has(filePath)) {
2215
+ return false;
2356
2216
  }
2357
- });
2358
- // See if there are any new imports to be added.
2359
- newImportPathMap.forEach((importInfo, normalizedImportPath) => {
2360
- if (!updatedImportMap.has(normalizedImportPath)) {
2361
- // We found a new import to add. See if it's already part
2362
- // of the program.
2363
- let importedFileInfo = this.getSourceFileInfo(importInfo.path);
2364
- if (!importedFileInfo) {
2365
- const importName = this._getImportNameForFile(importInfo.path);
2366
- const sourceFile = new sourceFile_1.SourceFile(this._fs, importInfo.path, importName, importInfo.isThirdPartyImport, importInfo.isPyTypedPresent, this._console, this._logTracker);
2367
- importedFileInfo = {
2368
- sourceFile,
2369
- isTracked: false,
2370
- isOpenByClient: false,
2371
- isTypeshedFile: importInfo.isTypeshedFile,
2372
- isThirdPartyImport: importInfo.isThirdPartyImport,
2373
- isThirdPartyPyTypedPresent: importInfo.isPyTypedPresent,
2374
- diagnosticsVersion: undefined,
2375
- imports: [],
2376
- importedBy: [],
2377
- shadows: [],
2378
- shadowedBy: [],
2379
- };
2380
- this._addToSourceFileListAndMap(importedFileInfo);
2381
- filesAdded.push(importedFileInfo);
2217
+ // We use both a map (for fast lookups) and a list
2218
+ // (for ordering information). Set the dependency map
2219
+ // entry to true to indicate that we're actively exploring
2220
+ // that dependency.
2221
+ dependencyMap.set(filePath, true);
2222
+ dependencyChain.push(sourceFileInfo);
2223
+ for (const imp of sourceFileInfo.imports) {
2224
+ if (this._detectAndReportImportCycles(imp, filesVisited, dependencyChain, dependencyMap)) {
2225
+ detectedCycle = true;
2382
2226
  }
2383
- importedFileInfo.importedBy.push(sourceFileInfo);
2384
- updatedImportMap.set(normalizedImportPath, importedFileInfo);
2385
- }
2386
- });
2387
- // Update the imports list. It should now map the set of imports
2388
- // specified by the source file.
2389
- sourceFileInfo.imports = [];
2390
- newImportPathMap.forEach((_, path) => {
2391
- if (this.getSourceFileInfo(path)) {
2392
- sourceFileInfo.imports.push(this.getSourceFileInfo(path));
2393
2227
  }
2394
- });
2395
- // Resolve the builtins import for the file. This needs to be
2396
- // analyzed before the file can be analyzed.
2397
- sourceFileInfo.builtinsImport = undefined;
2398
- const builtinsImport = sourceFileInfo.sourceFile.getBuiltinsImport();
2399
- if (builtinsImport && builtinsImport.isImportFound) {
2400
- const resolvedBuiltinsPath = builtinsImport.resolvedPaths[builtinsImport.resolvedPaths.length - 1];
2401
- sourceFileInfo.builtinsImport = this.getSourceFileInfo(resolvedBuiltinsPath);
2402
- }
2403
- // Resolve the ipython display import for the file. This needs to be
2404
- // analyzed before the file can be analyzed.
2405
- sourceFileInfo.ipythonDisplayImport = undefined;
2406
- const ipythonDisplayImport = sourceFileInfo.sourceFile.getIPythonDisplayImport();
2407
- if (ipythonDisplayImport && ipythonDisplayImport.isImportFound) {
2408
- const resolvedIPythonDisplayPath = ipythonDisplayImport.resolvedPaths[ipythonDisplayImport.resolvedPaths.length - 1];
2409
- sourceFileInfo.ipythonDisplayImport = this.getSourceFileInfo(resolvedIPythonDisplayPath);
2228
+ // Set the dependencyMap entry to false to indicate that we have
2229
+ // already explored this file and don't need to explore it again.
2230
+ dependencyMap.set(filePath, false);
2231
+ dependencyChain.pop();
2410
2232
  }
2411
- return filesAdded;
2233
+ return detectedCycle;
2412
2234
  }
2413
- _removeSourceFileFromListAndMap(filePath, indexToRemove) {
2414
- this._sourceFileMap.delete((0, pathUtils_1.normalizePathCase)(this._fs, filePath));
2415
- this._sourceFileList.splice(indexToRemove, 1);
2235
+ _logImportCycle(dependencyChain) {
2236
+ const circDep = new circularDependency_1.CircularDependency();
2237
+ dependencyChain.forEach((sourceFileInfo) => {
2238
+ circDep.appendPath(sourceFileInfo.sourceFile.getFilePath());
2239
+ });
2240
+ circDep.normalizeOrder();
2241
+ const firstFilePath = circDep.getPaths()[0];
2242
+ const firstSourceFile = this.getSourceFileInfo(firstFilePath);
2243
+ (0, debug_1.assert)(firstSourceFile !== undefined);
2244
+ firstSourceFile.sourceFile.addCircularDependency(circDep);
2416
2245
  }
2417
- _addToSourceFileListAndMap(fileInfo) {
2418
- const filePath = (0, pathUtils_1.normalizePathCase)(this._fs, fileInfo.sourceFile.getFilePath());
2419
- // We should never add a file with the same path twice.
2420
- (0, debug_1.assert)(!this._sourceFileMap.has(filePath));
2421
- this._sourceFileList.push(fileInfo);
2422
- this._sourceFileMap.set(filePath, fileInfo);
2246
+ _markFileDirtyRecursive(sourceFileInfo, markSet, forceRebinding = false) {
2247
+ const filePath = (0, pathUtils_1.normalizePathCase)(this.fileSystem, sourceFileInfo.sourceFile.getFilePath());
2248
+ // Don't mark it again if it's already been visited.
2249
+ if (markSet.has(filePath)) {
2250
+ return;
2251
+ }
2252
+ sourceFileInfo.sourceFile.markReanalysisRequired(forceRebinding);
2253
+ markSet.add(filePath);
2254
+ sourceFileInfo.importedBy.forEach((dep) => {
2255
+ // Changes on chained source file can change symbols in the symbol table and
2256
+ // dependencies on the dependent file. Force rebinding.
2257
+ const forceRebinding = dep.chainedSourceFile === sourceFileInfo;
2258
+ this._markFileDirtyRecursive(dep, markSet, forceRebinding);
2259
+ });
2260
+ // Change in the current file could impact checker result of chainedSourceFile such as unused symbols.
2261
+ let chainedSourceFile = sourceFileInfo.chainedSourceFile;
2262
+ while (chainedSourceFile) {
2263
+ if (chainedSourceFile.sourceFile.isCheckingRequired()) {
2264
+ // If the file is marked for checking, its chained one should be marked
2265
+ // as well. Stop here.
2266
+ return;
2267
+ }
2268
+ chainedSourceFile.sourceFile.markReanalysisRequired(/* forceRebinding */ false);
2269
+ chainedSourceFile = chainedSourceFile.chainedSourceFile;
2270
+ }
2423
2271
  }
2424
2272
  }
2425
2273
  exports.Program = Program;