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

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 (260) 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 +7 -4
  4. package/dist/analyzer/backgroundAnalysisProgram.js +22 -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.d.ts +1 -0
  9. package/dist/analyzer/checker.js +58 -7
  10. package/dist/analyzer/checker.js.map +1 -1
  11. package/dist/analyzer/constructors.d.ts +6 -0
  12. package/dist/analyzer/constructors.js +456 -0
  13. package/dist/analyzer/constructors.js.map +1 -0
  14. package/dist/analyzer/dataClasses.js +89 -2
  15. package/dist/analyzer/dataClasses.js.map +1 -1
  16. package/dist/analyzer/declarationUtils.d.ts +6 -1
  17. package/dist/analyzer/declarationUtils.js +10 -8
  18. package/dist/analyzer/declarationUtils.js.map +1 -1
  19. package/dist/analyzer/enums.js +54 -8
  20. package/dist/analyzer/enums.js.map +1 -1
  21. package/dist/analyzer/importResolver.d.ts +15 -15
  22. package/dist/analyzer/importResolver.js +477 -477
  23. package/dist/analyzer/importResolver.js.map +1 -1
  24. package/dist/analyzer/importStatementUtils.d.ts +2 -2
  25. package/dist/analyzer/importStatementUtils.js.map +1 -1
  26. package/dist/analyzer/namedTuples.d.ts +1 -1
  27. package/dist/analyzer/namedTuples.js +30 -42
  28. package/dist/analyzer/namedTuples.js.map +1 -1
  29. package/dist/analyzer/operations.d.ts +16 -0
  30. package/dist/analyzer/operations.js +749 -0
  31. package/dist/analyzer/operations.js.map +1 -0
  32. package/dist/analyzer/packageTypeReport.d.ts +2 -1
  33. package/dist/analyzer/packageTypeReport.js +2 -1
  34. package/dist/analyzer/packageTypeReport.js.map +1 -1
  35. package/dist/analyzer/packageTypeVerifier.d.ts +1 -1
  36. package/dist/analyzer/packageTypeVerifier.js +27 -13
  37. package/dist/analyzer/packageTypeVerifier.js.map +1 -1
  38. package/dist/analyzer/parseTreeUtils.d.ts +4 -2
  39. package/dist/analyzer/parseTreeUtils.js +32 -1
  40. package/dist/analyzer/parseTreeUtils.js.map +1 -1
  41. package/dist/analyzer/patternMatching.js +16 -0
  42. package/dist/analyzer/patternMatching.js.map +1 -1
  43. package/dist/analyzer/program.d.ts +29 -53
  44. package/dist/analyzer/program.js +1050 -1649
  45. package/dist/analyzer/program.js.map +1 -1
  46. package/dist/analyzer/protocols.js +1 -1
  47. package/dist/analyzer/protocols.js.map +1 -1
  48. package/dist/analyzer/service.d.ts +14 -35
  49. package/dist/analyzer/service.js +92 -121
  50. package/dist/analyzer/service.js.map +1 -1
  51. package/dist/analyzer/sourceFile.d.ts +14 -49
  52. package/dist/analyzer/sourceFile.js +271 -291
  53. package/dist/analyzer/sourceFile.js.map +1 -1
  54. package/dist/analyzer/sourceFileInfoUtils.d.ts +2 -2
  55. package/dist/analyzer/sourceFileInfoUtils.js.map +1 -1
  56. package/dist/analyzer/typeEvaluator.js +417 -1570
  57. package/dist/analyzer/typeEvaluator.js.map +1 -1
  58. package/dist/analyzer/typeEvaluatorTypes.d.ts +44 -9
  59. package/dist/analyzer/typeEvaluatorTypes.js +33 -1
  60. package/dist/analyzer/typeEvaluatorTypes.js.map +1 -1
  61. package/dist/analyzer/typeGuards.js +5 -9
  62. package/dist/analyzer/typeGuards.js.map +1 -1
  63. package/dist/analyzer/typeStubWriter.js.map +1 -1
  64. package/dist/analyzer/typeUtils.d.ts +3 -0
  65. package/dist/analyzer/typeUtils.js +66 -9
  66. package/dist/analyzer/typeUtils.js.map +1 -1
  67. package/dist/analyzer/typeVarContext.d.ts +5 -5
  68. package/dist/analyzer/typeVarContext.js +7 -0
  69. package/dist/analyzer/typeVarContext.js.map +1 -1
  70. package/dist/analyzer/typedDicts.js +2 -2
  71. package/dist/analyzer/typedDicts.js.map +1 -1
  72. package/dist/analyzer/types.d.ts +4 -2
  73. package/dist/analyzer/types.js +7 -0
  74. package/dist/analyzer/types.js.map +1 -1
  75. package/dist/backgroundAnalysisBase.d.ts +10 -11
  76. package/dist/backgroundAnalysisBase.js +87 -87
  77. package/dist/backgroundAnalysisBase.js.map +1 -1
  78. package/dist/commands/dumpFileDebugInfoCommand.js +8 -8
  79. package/dist/commands/dumpFileDebugInfoCommand.js.map +1 -1
  80. package/dist/commands/quickActionCommand.js +4 -1
  81. package/dist/commands/quickActionCommand.js.map +1 -1
  82. package/dist/common/cancellationUtils.d.ts +1 -1
  83. package/dist/common/cancellationUtils.js +9 -9
  84. package/dist/common/cancellationUtils.js.map +1 -1
  85. package/dist/common/commandLineOptions.d.ts +1 -2
  86. package/dist/common/commandLineOptions.js.map +1 -1
  87. package/dist/common/configOptions.d.ts +2 -2
  88. package/dist/common/configOptions.js.map +1 -1
  89. package/dist/common/console.d.ts +5 -9
  90. package/dist/common/console.js +46 -33
  91. package/dist/common/console.js.map +1 -1
  92. package/dist/common/deferred.js +10 -10
  93. package/dist/common/deferred.js.map +1 -1
  94. package/dist/common/extensibility.d.ts +27 -5
  95. package/dist/common/extensibility.js +1 -1
  96. package/dist/common/extensibility.js.map +1 -1
  97. package/dist/common/fileBasedCancellationUtils.js +5 -5
  98. package/dist/common/fileBasedCancellationUtils.js.map +1 -1
  99. package/dist/common/fileSystem.d.ts +12 -10
  100. package/dist/common/fileSystem.js.map +1 -1
  101. package/dist/common/fullAccessHost.d.ts +3 -3
  102. package/dist/common/fullAccessHost.js +6 -6
  103. package/dist/common/fullAccessHost.js.map +1 -1
  104. package/dist/common/pathUtils.d.ts +13 -13
  105. package/dist/common/pathUtils.js.map +1 -1
  106. package/dist/common/realFileSystem.js +12 -7
  107. package/dist/common/realFileSystem.js.map +1 -1
  108. package/dist/common/uriParser.d.ts +2 -2
  109. package/dist/common/uriParser.js +3 -3
  110. package/dist/common/uriParser.js.map +1 -1
  111. package/dist/common/workspaceEditUtils.d.ts +5 -5
  112. package/dist/common/workspaceEditUtils.js +7 -4
  113. package/dist/common/workspaceEditUtils.js.map +1 -1
  114. package/dist/languageServerBase.d.ts +32 -31
  115. package/dist/languageServerBase.js +278 -345
  116. package/dist/languageServerBase.js.map +1 -1
  117. package/dist/languageService/analyzerServiceExecutor.js +0 -1
  118. package/dist/languageService/analyzerServiceExecutor.js.map +1 -1
  119. package/dist/languageService/callHierarchyProvider.d.ts +16 -12
  120. package/dist/languageService/callHierarchyProvider.js +125 -41
  121. package/dist/languageService/callHierarchyProvider.js.map +1 -1
  122. package/dist/languageService/completionProvider.d.ts +10 -13
  123. package/dist/languageService/completionProvider.js +21 -10
  124. package/dist/languageService/completionProvider.js.map +1 -1
  125. package/dist/languageService/definitionProvider.d.ts +23 -9
  126. package/dist/languageService/definitionProvider.js +116 -91
  127. package/dist/languageService/definitionProvider.js.map +1 -1
  128. package/dist/languageService/documentHighlightProvider.d.ts +8 -3
  129. package/dist/languageService/documentHighlightProvider.js +17 -6
  130. package/dist/languageService/documentHighlightProvider.js.map +1 -1
  131. package/dist/languageService/documentSymbolCollector.d.ts +6 -7
  132. package/dist/languageService/documentSymbolCollector.js +21 -11
  133. package/dist/languageService/documentSymbolCollector.js.map +1 -1
  134. package/dist/languageService/documentSymbolProvider.js +5 -3
  135. package/dist/languageService/documentSymbolProvider.js.map +1 -1
  136. package/dist/languageService/hoverProvider.d.ts +4 -3
  137. package/dist/languageService/hoverProvider.js +30 -36
  138. package/dist/languageService/hoverProvider.js.map +1 -1
  139. package/dist/languageService/navigationUtils.d.ts +6 -0
  140. package/dist/languageService/navigationUtils.js +28 -0
  141. package/dist/languageService/navigationUtils.js.map +1 -0
  142. package/dist/languageService/quickActions.d.ts +2 -2
  143. package/dist/languageService/quickActions.js +12 -1
  144. package/dist/languageService/quickActions.js.map +1 -1
  145. package/dist/languageService/referencesProvider.d.ts +13 -12
  146. package/dist/languageService/referencesProvider.js +102 -16
  147. package/dist/languageService/referencesProvider.js.map +1 -1
  148. package/dist/languageService/renameProvider.d.ts +17 -0
  149. package/dist/languageService/renameProvider.js +143 -0
  150. package/dist/languageService/renameProvider.js.map +1 -0
  151. package/dist/languageService/signatureHelpProvider.d.ts +19 -23
  152. package/dist/languageService/signatureHelpProvider.js +111 -18
  153. package/dist/languageService/signatureHelpProvider.js.map +1 -1
  154. package/dist/localization/localize.d.ts +17 -14
  155. package/dist/localization/localize.js +4 -6
  156. package/dist/localization/localize.js.map +1 -1
  157. package/dist/localization/package.nls.en-us.json +5 -6
  158. package/dist/parser/characterStream.d.ts +3 -3
  159. package/dist/parser/characterStream.js +12 -12
  160. package/dist/parser/characterStream.js.map +1 -1
  161. package/dist/parser/parser.d.ts +1 -1
  162. package/dist/parser/parser.js.map +1 -1
  163. package/dist/pyright.js +57 -54
  164. package/dist/pyright.js.map +1 -1
  165. package/dist/pyrightFileSystem.d.ts +1 -1
  166. package/dist/pyrightFileSystem.js +21 -21
  167. package/dist/pyrightFileSystem.js.map +1 -1
  168. package/dist/readonlyAugmentedFileSystem.d.ts +6 -6
  169. package/dist/readonlyAugmentedFileSystem.js +28 -28
  170. package/dist/readonlyAugmentedFileSystem.js.map +1 -1
  171. package/dist/server.js +6 -6
  172. package/dist/server.js.map +1 -1
  173. package/dist/tests/chainedSourceFiles.test.js +1 -1
  174. package/dist/tests/chainedSourceFiles.test.js.map +1 -1
  175. package/dist/tests/checker.test.js +1 -1
  176. package/dist/tests/documentSymbolCollector.test.js +3 -3
  177. package/dist/tests/documentSymbolCollector.test.js.map +1 -1
  178. package/dist/tests/fourslash/fourslash.d.ts +4 -4
  179. package/dist/tests/fourslash/missingTypeStub.codeAction.fourslash.js +1 -1
  180. package/dist/tests/fourslash/missingTypeStub.codeAction.fourslash.js.map +1 -1
  181. package/dist/tests/harness/fourslash/testLanguageService.d.ts +3 -3
  182. package/dist/tests/harness/fourslash/testLanguageService.js.map +1 -1
  183. package/dist/tests/harness/fourslash/testState.d.ts +11 -11
  184. package/dist/tests/harness/fourslash/testState.js +123 -113
  185. package/dist/tests/harness/fourslash/testState.js.map +1 -1
  186. package/dist/tests/harness/vfs/filesystem.d.ts +8 -8
  187. package/dist/tests/harness/vfs/filesystem.js +68 -68
  188. package/dist/tests/harness/vfs/filesystem.js.map +1 -1
  189. package/dist/tests/importStatementUtils.test.js +34 -0
  190. package/dist/tests/importStatementUtils.test.js.map +1 -1
  191. package/dist/tests/signatureHelp.test.js +5 -1
  192. package/dist/tests/signatureHelp.test.js.map +1 -1
  193. package/dist/tests/sourceFile.test.js +2 -2
  194. package/dist/tests/sourceFile.test.js.map +1 -1
  195. package/dist/tests/testStateUtils.d.ts +2 -2
  196. package/dist/tests/testStateUtils.js +39 -9
  197. package/dist/tests/testStateUtils.js.map +1 -1
  198. package/dist/tests/typeEvaluator1.test.js +8 -0
  199. package/dist/tests/typeEvaluator1.test.js.map +1 -1
  200. package/dist/tests/typeEvaluator2.test.js +13 -1
  201. package/dist/tests/typeEvaluator2.test.js.map +1 -1
  202. package/dist/tests/typeEvaluator3.test.js +2 -2
  203. package/dist/tests/typeEvaluator4.test.js +9 -1
  204. package/dist/tests/typeEvaluator4.test.js.map +1 -1
  205. package/dist/tests/typeEvaluator5.test.js +4 -0
  206. package/dist/tests/typeEvaluator5.test.js.map +1 -1
  207. package/dist/tests/workspaceEditUtils.test.js +84 -0
  208. package/dist/tests/workspaceEditUtils.test.js.map +1 -1
  209. package/package.json +4 -4
  210. package/dist/languageService/indentationUtils.d.ts +0 -16
  211. package/dist/languageService/indentationUtils.js +0 -727
  212. package/dist/languageService/indentationUtils.js.map +0 -1
  213. package/dist/languageService/insertionPointUtils.d.ts +0 -9
  214. package/dist/languageService/insertionPointUtils.js +0 -132
  215. package/dist/languageService/insertionPointUtils.js.map +0 -1
  216. package/dist/languageService/renameModuleProvider.d.ts +0 -65
  217. package/dist/languageService/renameModuleProvider.js +0 -939
  218. package/dist/languageService/renameModuleProvider.js.map +0 -1
  219. package/dist/tests/indentationUtils.ptvs.test.d.ts +0 -1
  220. package/dist/tests/indentationUtils.ptvs.test.js +0 -324
  221. package/dist/tests/indentationUtils.ptvs.test.js.map +0 -1
  222. package/dist/tests/indentationUtils.reindent.test.d.ts +0 -1
  223. package/dist/tests/indentationUtils.reindent.test.js +0 -372
  224. package/dist/tests/indentationUtils.reindent.test.js.map +0 -1
  225. package/dist/tests/indentationUtils.test.d.ts +0 -1
  226. package/dist/tests/indentationUtils.test.js +0 -502
  227. package/dist/tests/indentationUtils.test.js.map +0 -1
  228. package/dist/tests/insertionPointUtils.test.d.ts +0 -1
  229. package/dist/tests/insertionPointUtils.test.js +0 -154
  230. package/dist/tests/insertionPointUtils.test.js.map +0 -1
  231. package/dist/tests/moveSymbol.importAdder.test.d.ts +0 -1
  232. package/dist/tests/moveSymbol.importAdder.test.js +0 -298
  233. package/dist/tests/moveSymbol.importAdder.test.js.map +0 -1
  234. package/dist/tests/moveSymbol.insertion.test.d.ts +0 -1
  235. package/dist/tests/moveSymbol.insertion.test.js +0 -537
  236. package/dist/tests/moveSymbol.insertion.test.js.map +0 -1
  237. package/dist/tests/moveSymbol.misc.test.d.ts +0 -1
  238. package/dist/tests/moveSymbol.misc.test.js +0 -169
  239. package/dist/tests/moveSymbol.misc.test.js.map +0 -1
  240. package/dist/tests/moveSymbol.updateReference.test.d.ts +0 -1
  241. package/dist/tests/moveSymbol.updateReference.test.js +0 -1057
  242. package/dist/tests/moveSymbol.updateReference.test.js.map +0 -1
  243. package/dist/tests/renameModule.folder.test.d.ts +0 -1
  244. package/dist/tests/renameModule.folder.test.js +0 -229
  245. package/dist/tests/renameModule.folder.test.js.map +0 -1
  246. package/dist/tests/renameModule.fromImports.test.d.ts +0 -1
  247. package/dist/tests/renameModule.fromImports.test.js +0 -790
  248. package/dist/tests/renameModule.fromImports.test.js.map +0 -1
  249. package/dist/tests/renameModule.imports.test.d.ts +0 -1
  250. package/dist/tests/renameModule.imports.test.js +0 -380
  251. package/dist/tests/renameModule.imports.test.js.map +0 -1
  252. package/dist/tests/renameModule.misc.test.d.ts +0 -1
  253. package/dist/tests/renameModule.misc.test.js +0 -615
  254. package/dist/tests/renameModule.misc.test.js.map +0 -1
  255. package/dist/tests/renameModule.relativePath.test.d.ts +0 -1
  256. package/dist/tests/renameModule.relativePath.test.js +0 -231
  257. package/dist/tests/renameModule.relativePath.test.js.map +0 -1
  258. package/dist/tests/renameModuleTestUtils.d.ts +0 -4
  259. package/dist/tests/renameModuleTestUtils.js +0 -76
  260. package/dist/tests/renameModuleTestUtils.js.map +0 -1
@@ -1,939 +0,0 @@
1
- "use strict";
2
- /*
3
- * renameModuleProvider.ts
4
- * Copyright (c) Microsoft Corporation.
5
- * Licensed under the MIT license.
6
- *
7
- * Logic that updates affected references of a module rename/move.
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.RenameModuleProvider = void 0;
11
- const vscode_languageserver_1 = require("vscode-languageserver");
12
- const analyzerNodeInfo_1 = require("../analyzer/analyzerNodeInfo");
13
- const declaration_1 = require("../analyzer/declaration");
14
- const declarationUtils_1 = require("../analyzer/declarationUtils");
15
- const importResolver_1 = require("../analyzer/importResolver");
16
- const importStatementUtils_1 = require("../analyzer/importStatementUtils");
17
- const parseTreeUtils_1 = require("../analyzer/parseTreeUtils");
18
- const parseTreeWalker_1 = require("../analyzer/parseTreeWalker");
19
- const sourceMapper_1 = require("../analyzer/sourceMapper");
20
- const symbolNameUtils_1 = require("../analyzer/symbolNameUtils");
21
- const collectionUtils_1 = require("../common/collectionUtils");
22
- const configOptions_1 = require("../common/configOptions");
23
- const debug_1 = require("../common/debug");
24
- const pathUtils_1 = require("../common/pathUtils");
25
- const positionUtils_1 = require("../common/positionUtils");
26
- const textEditTracker_1 = require("../common/textEditTracker");
27
- const textRange_1 = require("../common/textRange");
28
- const parseNodes_1 = require("../parser/parseNodes");
29
- const documentSymbolCollector_1 = require("./documentSymbolCollector");
30
- var UpdateType;
31
- (function (UpdateType) {
32
- UpdateType[UpdateType["File"] = 0] = "File";
33
- UpdateType[UpdateType["Folder"] = 1] = "Folder";
34
- UpdateType[UpdateType["Symbol"] = 2] = "Symbol";
35
- })(UpdateType || (UpdateType = {}));
36
- class RenameModuleProvider {
37
- constructor(_fs, _evaluator, _moduleFilePath, newModuleFilePath, _moduleNameAndType, _newModuleNameAndType, _type, declarations, _token) {
38
- this._fs = _fs;
39
- this._evaluator = _evaluator;
40
- this._moduleFilePath = _moduleFilePath;
41
- this._moduleNameAndType = _moduleNameAndType;
42
- this._newModuleNameAndType = _newModuleNameAndType;
43
- this._type = _type;
44
- this.declarations = declarations;
45
- this._token = _token;
46
- this._aliasIntroduced = new Set();
47
- this._textEditTracker = new textEditTracker_1.TextEditTracker();
48
- // moduleName and newModuleName are always in the absolute path form.
49
- this._newModuleFilePath = (0, pathUtils_1.resolvePaths)(newModuleFilePath);
50
- this._moduleNames = this._moduleName.split('.');
51
- this._newModuleNames = this._newModuleName.split('.');
52
- this._onlyNameChanged = (0, importStatementUtils_1.haveSameParentModule)(this._moduleNames, this._newModuleNames);
53
- (0, debug_1.assert)(this._type !== UpdateType.Folder || this._onlyNameChanged, 'We only support simple rename for folder');
54
- }
55
- static createForModule(importResolver, configOptions, evaluator, path, newPath, token) {
56
- if (!importResolver.fileSystem.existsSync(path)) {
57
- return undefined;
58
- }
59
- if ((0, pathUtils_1.isFile)(importResolver.fileSystem, path)) {
60
- return this._create(importResolver, configOptions, evaluator, path, newPath, UpdateType.File, token);
61
- }
62
- else if ((0, pathUtils_1.isDirectory)(importResolver.fileSystem, path)) {
63
- // Make sure folder path is simple rename.
64
- if ((0, pathUtils_1.getDirectoryChangeKind)(importResolver.fileSystem, path, newPath) !== 'Renamed') {
65
- return undefined;
66
- }
67
- // We don't support namespace folder name. Currently, we don't have
68
- // a way to find namespace folder references.
69
- let fileNameForPackage = (0, pathUtils_1.combinePaths)(path, '__init__.pyi');
70
- if (!importResolver.fileSystem.existsSync(fileNameForPackage)) {
71
- fileNameForPackage = (0, pathUtils_1.combinePaths)(path, '__init__.py');
72
- if (!importResolver.fileSystem.existsSync(fileNameForPackage)) {
73
- return undefined;
74
- }
75
- }
76
- return this._create(importResolver, configOptions, evaluator, fileNameForPackage, (0, pathUtils_1.combinePaths)(newPath, (0, pathUtils_1.getFileName)(fileNameForPackage)), UpdateType.Folder, token);
77
- }
78
- return undefined;
79
- }
80
- static createForSymbol(importResolver, configOptions, evaluator, path, newPath, declarations, token) {
81
- if (!importResolver.fileSystem.existsSync(path)) {
82
- return undefined;
83
- }
84
- const filteredDecls = declarations.filter((d) => (0, declaration_1.isClassDeclaration)(d) || (0, declaration_1.isFunctionDeclaration)(d) || (0, declaration_1.isVariableDeclaration)(d));
85
- if (filteredDecls.length === 0) {
86
- return undefined;
87
- }
88
- return this._create(importResolver, configOptions, evaluator, path, newPath, UpdateType.Symbol, filteredDecls, token);
89
- }
90
- static canMoveSymbol(configOptions, evaluator, node) {
91
- var _a;
92
- const filePath = (_a = (0, analyzerNodeInfo_1.getFileInfo)(node)) === null || _a === void 0 ? void 0 : _a.filePath;
93
- if (!filePath || !(0, configOptions_1.matchFileSpecs)(configOptions, filePath, /* isFile */ true)) {
94
- // We only support moving symbols from a user file.
95
- return false;
96
- }
97
- if ((0, symbolNameUtils_1.isPrivateName)(node.value)) {
98
- return false;
99
- }
100
- const lookUpResult = evaluator.lookUpSymbolRecursive(node, node.value, /* honorCodeFlow */ false);
101
- if (lookUpResult === undefined || lookUpResult.scope.type !== 3 /* Module */) {
102
- // We only allow moving a symbol at the module level.
103
- return false;
104
- }
105
- // For now, we only supports module level variable, function and class.
106
- const declarations = lookUpResult.symbol.getDeclarations();
107
- if (declarations.length === 0) {
108
- return false;
109
- }
110
- return declarations.every((d) => {
111
- var _a, _b, _c;
112
- if (!textRange_1.TextRange.containsRange(d.node, node)) {
113
- return false;
114
- }
115
- if ((0, declaration_1.isFunctionDeclaration)(d) || (0, declaration_1.isClassDeclaration)(d)) {
116
- return true;
117
- }
118
- if ((0, declaration_1.isVariableDeclaration)(d)) {
119
- // We only support simple variable assignment.
120
- // ex) a = 1
121
- if (evaluator.isExplicitTypeAliasDeclaration(d)) {
122
- return false;
123
- }
124
- if (d.inferredTypeSource && (0, parseNodes_1.isExpressionNode)(d.inferredTypeSource)) {
125
- const type = evaluator.getType(d.inferredTypeSource);
126
- if ((type === null || type === void 0 ? void 0 : type.category) === 10 /* TypeVar */) {
127
- return false;
128
- }
129
- }
130
- // This make sure we are not one of these
131
- // ex) a = b = 1
132
- // a, b = 1, 2
133
- if (((_a = d.node.parent) === null || _a === void 0 ? void 0 : _a.nodeType) !== 3 /* Assignment */ ||
134
- ((_c = (_b = d.node.parent) === null || _b === void 0 ? void 0 : _b.parent) === null || _c === void 0 ? void 0 : _c.nodeType) !== 47 /* StatementList */) {
135
- return false;
136
- }
137
- if (d.node.start !== d.node.parent.start) {
138
- return false;
139
- }
140
- return true;
141
- }
142
- return false;
143
- });
144
- }
145
- static getSymbolTextRange(parseResults, decl) {
146
- var _a, _b;
147
- if ((0, declaration_1.isVariableDeclaration)(decl)) {
148
- const assignment = (_a = (0, parseTreeUtils_1.getFirstAncestorOrSelfOfKind)(decl.node, 3 /* Assignment */)) !== null && _a !== void 0 ? _a : decl.node;
149
- const range = (0, parseTreeUtils_1.getFullStatementRange)(assignment, parseResults);
150
- const textRange = (_b = (0, positionUtils_1.convertRangeToTextRange)(range, parseResults.tokenizerOutput.lines)) !== null && _b !== void 0 ? _b : assignment;
151
- if (decl.docString !== undefined) {
152
- const docNode = (0, parseTreeUtils_1.getVariableDocStringNode)(decl.node);
153
- if (docNode) {
154
- textRange_1.TextRange.extend(textRange, docNode);
155
- }
156
- }
157
- return textRange;
158
- }
159
- return decl.node;
160
- }
161
- static getSymbolFullStatementTextRange(parseResults, decl) {
162
- var _a, _b;
163
- const statementNode = (0, declaration_1.isVariableDeclaration)(decl)
164
- ? (_a = (0, parseTreeUtils_1.getFirstAncestorOrSelfOfKind)(decl.node, 3 /* Assignment */)) !== null && _a !== void 0 ? _a : decl.node
165
- : decl.node;
166
- const range = (0, parseTreeUtils_1.getFullStatementRange)(statementNode, parseResults, {
167
- includeTrailingBlankLines: true,
168
- });
169
- return (_b = (0, positionUtils_1.convertRangeToTextRange)(range, parseResults.tokenizerOutput.lines)) !== null && _b !== void 0 ? _b : statementNode;
170
- }
171
- static getRenameModulePath(declarations) {
172
- // If we have a decl with no node, we will prefer that decl over others.
173
- // The decl with no node is a synthesized alias decl created only for IDE case
174
- // that should point to the right module file.
175
- const bestDecl = declarations.find((d) => !d.node);
176
- if (bestDecl) {
177
- return bestDecl.path;
178
- }
179
- // Otherwise, prefer stub if we have one. or just return first decl.
180
- const declarationPaths = [...declarations.reduce((s, d) => s.add(d.path), new Set())];
181
- const stubIndex = declarationPaths.findIndex((d) => (0, sourceMapper_1.isStubFile)(d));
182
- if (stubIndex >= 0) {
183
- return declarationPaths[stubIndex];
184
- }
185
- return declarationPaths[0];
186
- }
187
- static getRenameModulePathInfo(declarationPath, newName) {
188
- const filePath = getFilePathToRename(declarationPath);
189
- const newFilePath = replaceFileName(filePath, newName);
190
- return { filePath, newFilePath };
191
- function getFilePathToRename(filePath) {
192
- const fileName = (0, pathUtils_1.stripFileExtension)((0, pathUtils_1.getFileName)(filePath));
193
- if (fileName === '__init__') {
194
- return (0, pathUtils_1.getDirectoryPath)(filePath);
195
- }
196
- return filePath;
197
- }
198
- function replaceFileName(filePath, newName) {
199
- const ext = (0, pathUtils_1.getFileExtension)(filePath);
200
- const directory = (0, pathUtils_1.getDirectoryPath)(filePath);
201
- return (0, pathUtils_1.combinePaths)(directory, `${newName}${ext}`);
202
- }
203
- }
204
- static _create(importResolver, configOptions, evaluator, moduleFilePath, newModuleFilePath, type, tokenOrDeclarations, token) {
205
- const execEnv = configOptions.findExecEnvironment(moduleFilePath);
206
- const moduleName = importResolver.getModuleNameForImport(moduleFilePath, execEnv);
207
- if (!moduleName.moduleName) {
208
- return undefined;
209
- }
210
- const newModuleName = importResolver.getModuleNameForImport(newModuleFilePath, execEnv);
211
- if (!newModuleName.moduleName) {
212
- return undefined;
213
- }
214
- token = vscode_languageserver_1.CancellationToken.is(tokenOrDeclarations) ? tokenOrDeclarations : token;
215
- const declarations = vscode_languageserver_1.CancellationToken.is(tokenOrDeclarations) ? [] : tokenOrDeclarations;
216
- if (declarations.length === 0) {
217
- // Create synthesized alias decls from the given file path. If the given file is for stub,
218
- // create one for the corresponding py file as well.
219
- declarations.push((0, declarationUtils_1.createSynthesizedAliasDeclaration)(moduleFilePath));
220
- if ((0, sourceMapper_1.isStubFile)(moduleFilePath)) {
221
- // The resolveImport should make sure non stub file search to happen.
222
- importResolver.resolveImport(moduleFilePath, execEnv, (0, importResolver_1.createImportedModuleDescriptor)(moduleName.moduleName));
223
- importResolver
224
- .getSourceFilesFromStub(moduleFilePath, execEnv, /* mapCompiled */ false)
225
- .forEach((p) => declarations.push((0, declarationUtils_1.createSynthesizedAliasDeclaration)(p)));
226
- }
227
- }
228
- return new RenameModuleProvider(importResolver.fileSystem, evaluator, moduleFilePath, newModuleFilePath, moduleName, newModuleName, type, declarations, token);
229
- }
230
- get lastModuleName() {
231
- return this._moduleNames[this._moduleNames.length - 1];
232
- }
233
- get textEditTracker() {
234
- return this._textEditTracker;
235
- }
236
- getEdits() {
237
- return this._textEditTracker.getEdits(this._token);
238
- }
239
- renameReferences(parseResults) {
240
- switch (this._type) {
241
- case UpdateType.Folder:
242
- return this._renameFolderReferences(parseResults);
243
- case UpdateType.File:
244
- return this._renameModuleReferences(parseResults);
245
- case UpdateType.Symbol:
246
- return this._updateSymbolReferences(parseResults);
247
- default:
248
- return (0, debug_1.assertNever)(this._type, `${this._type} is unknown`);
249
- }
250
- }
251
- tryGetFirstSymbolUsage(parseResults, symbol) {
252
- var _a, _b, _c;
253
- const name = (_b = (_a = symbol === null || symbol === void 0 ? void 0 : symbol.name) !== null && _a !== void 0 ? _a : (0, declarationUtils_1.getNameFromDeclaration)(this.declarations[0])) !== null && _b !== void 0 ? _b : '';
254
- const collector = new documentSymbolCollector_1.DocumentSymbolCollector([name], (_c = symbol === null || symbol === void 0 ? void 0 : symbol.decls) !== null && _c !== void 0 ? _c : this.declarations, this._evaluator, this._token, parseResults.parseTree,
255
- /* treatModuleImportAndFromImportSame */ true,
256
- /* skipUnreachableCode */ false);
257
- for (const result of collector.collect().sort((r1, r2) => r1.range.start - r2.range.start)) {
258
- // We only care about symbol usages, not alias decl of the symbol.
259
- if ((0, parseTreeUtils_1.isImportModuleName)(result.node) ||
260
- (0, parseTreeUtils_1.isImportAlias)(result.node) ||
261
- (0, parseTreeUtils_1.isFromImportModuleName)(result.node) ||
262
- (0, parseTreeUtils_1.isFromImportName)(result.node) ||
263
- (0, parseTreeUtils_1.isFromImportAlias)(result.node)) {
264
- continue;
265
- }
266
- return result.range.start;
267
- }
268
- return undefined;
269
- }
270
- _updateSymbolReferences(parseResults) {
271
- const filePath = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parseTree).filePath;
272
- const isSource = filePath === this._moduleFilePath;
273
- const collector = new documentSymbolCollector_1.DocumentSymbolCollector([(0, declarationUtils_1.getNameFromDeclaration)(this.declarations[0]) || ''], this.declarations, this._evaluator, this._token, parseResults.parseTree,
274
- /* treatModuleImportAndFromImportSame */ true,
275
- /* skipUnreachableCode */ false);
276
- // See if we need to insert new import statement
277
- const importStatements = (0, importStatementUtils_1.getTopLevelImports)(parseResults.parseTree, /* includeImplicitImports */ true);
278
- // See whether we have existing import statement for the same module
279
- // ex) import [moduleName] or from ... import [moduleName]
280
- const imported = importStatements.orderedImports.find((i) => i.moduleName === this._newModuleName);
281
- // Indicate whether current file has any usage of the symbol
282
- let hasSymbolUsage = false;
283
- const wildcardImports = new Map();
284
- const importUsed = new Map();
285
- for (const result of collector.collect()) {
286
- const nodeFound = result.node;
287
- if (nodeFound.nodeType === 49 /* String */) {
288
- if (isSource) {
289
- // Delete the symbol reference in __all__ if the file is the source file.
290
- this._textEditTracker.addEditWithTextRange(parseResults, nodeFound, '');
291
- }
292
- continue;
293
- }
294
- if ((0, parseTreeUtils_1.isFromImportName)(nodeFound)) {
295
- this._updateNameInFromImportForSymbolReferences(parseResults, importStatements, nodeFound);
296
- continue;
297
- }
298
- // Exclude symbol decl itself.
299
- hasSymbolUsage = isSource
300
- ? !this.declarations.some((d) => textRange_1.TextRange.containsRange(d.node, nodeFound))
301
- : true;
302
- const dottedName = (0, parseTreeUtils_1.getDottedNameWithGivenNodeAsLastName)(nodeFound);
303
- if (dottedName === nodeFound || dottedName.nodeType !== 35 /* MemberAccess */) {
304
- this._collectWildcardImports(nodeFound, wildcardImports);
305
- // ex) from module import foo
306
- // foo
307
- // foo.method()
308
- continue;
309
- }
310
- this._collectSymbolReferencesPerImports(dottedName, importUsed);
311
- }
312
- if (isSource && hasSymbolUsage) {
313
- // If the original file has references to the symbol moved, we need to either
314
- // insert import statement or update existing one.
315
- const newModuleName = (imported === null || imported === void 0 ? void 0 : imported.node.nodeType) === 22 /* ImportFrom */
316
- ? this._getNewModuleName(filePath, imported.node.module.leadingDots > 0,
317
- /* isLastPartImportName */ false)
318
- : undefined;
319
- const options = (imported === null || imported === void 0 ? void 0 : imported.node.nodeType) === 22 /* ImportFrom */
320
- ? {
321
- currentFromImport: imported.node,
322
- originalModuleName: this._moduleName,
323
- }
324
- : undefined;
325
- this._textEditTracker.addOrUpdateImport(parseResults, importStatements, { name: this._newModuleName, nameForImportFrom: newModuleName }, (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(this._newModuleNameAndType), [{ name: (0, declarationUtils_1.getNameFromDeclaration)(this.declarations[0]) }], options);
326
- }
327
- // Handle symbol references that are used off wildcard imports.
328
- this._processSymbolReferenceOffWildcardImports(parseResults, importStatements, wildcardImports);
329
- // Handle symbol references that are used off imported modules.
330
- this._processSymbolReferenceOffImports(parseResults, importStatements, imported, importUsed);
331
- }
332
- _processSymbolReferenceOffImports(parseResults, importStatements, imported, importUsed) {
333
- const filePath = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parseTree).filePath;
334
- const isDestination = filePath === this._newModuleFilePath;
335
- if (isDestination) {
336
- for (const [key, value] of importUsed) {
337
- if (this._canReplaceImportName(parseResults, key, value)) {
338
- // We can remove existing import statement.
339
- this._textEditTracker.deleteImportName(parseResults, key);
340
- }
341
- for (const node of value) {
342
- this._textEditTracker.addEditWithTextRange(parseResults, textRange_1.TextRange.fromBounds(node.start, node.memberName.start), '');
343
- }
344
- }
345
- return;
346
- }
347
- // Other files.
348
- for (const [key, value] of importUsed) {
349
- let referenceModuleName;
350
- if (this._canReplaceImportName(parseResults, key, value)) {
351
- const moduleName = this._getReferenceModuleName(importStatements, imported);
352
- if (key.nodeType === 21 /* ImportAs */) {
353
- if (moduleName) {
354
- referenceModuleName = moduleName;
355
- this._textEditTracker.deleteImportName(parseResults, key);
356
- }
357
- else {
358
- referenceModuleName = key.alias ? key.alias.value : this._newModuleName;
359
- this._textEditTracker.addEditWithTextRange(parseResults, key.module, this._newModuleName);
360
- }
361
- }
362
- else {
363
- if (moduleName) {
364
- referenceModuleName = moduleName;
365
- this._textEditTracker.deleteImportName(parseResults, key);
366
- }
367
- else {
368
- const fromNode = key.parent;
369
- const newModuleName = this._getNewModuleName(filePath, fromNode.module.leadingDots > 0,
370
- /* isLastPartImportName */ true);
371
- referenceModuleName = key.alias ? key.alias.value : this._newLastModuleName;
372
- this._textEditTracker.addEditWithTextRange(parseResults, fromNode.module, newModuleName);
373
- this._textEditTracker.addEditWithTextRange(parseResults, key.name, this._newLastModuleName);
374
- }
375
- }
376
- }
377
- else {
378
- const moduleName = this._getReferenceModuleName(importStatements, imported);
379
- if (moduleName) {
380
- referenceModuleName = moduleName;
381
- }
382
- else {
383
- referenceModuleName = this._newModuleName;
384
- this._textEditTracker.addOrUpdateImport(parseResults, importStatements, { name: this._newModuleName }, (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(this._newModuleNameAndType));
385
- }
386
- }
387
- for (const node of value) {
388
- this._textEditTracker.addEditWithTextRange(parseResults, node.leftExpression, referenceModuleName);
389
- }
390
- }
391
- }
392
- _processSymbolReferenceOffWildcardImports(parseResults, importStatements, wildcardImports) {
393
- const filePath = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parseTree).filePath;
394
- const isDestination = filePath === this._newModuleFilePath;
395
- if (isDestination) {
396
- // Destination file contains the moved symbol decl. no need to insert
397
- // import statement for the symbol moved.
398
- return;
399
- }
400
- for (const [key, value] of wildcardImports) {
401
- const fromNode = key;
402
- const newModuleName = this._getNewModuleName(filePath, fromNode.module.leadingDots > 0,
403
- /* isLastPartImportName */ false);
404
- this._textEditTracker.addOrUpdateImport(parseResults, importStatements, { name: this._newModuleName, nameForImportFrom: newModuleName }, (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(this._newModuleNameAndType), [...value].map((v) => ({ name: v })), {
405
- currentFromImport: fromNode,
406
- originalModuleName: this._moduleName,
407
- });
408
- }
409
- }
410
- _collectSymbolReferencesPerImports(dottedName, importUsed) {
411
- var _a;
412
- const moduleName = dottedName.leftExpression.nodeType === 35 /* MemberAccess */
413
- ? dottedName.leftExpression.memberName
414
- : dottedName.leftExpression.nodeType === 38 /* Name */
415
- ? dottedName.leftExpression
416
- : undefined;
417
- if (!moduleName) {
418
- // ex) from module import foo
419
- // getModule().foo
420
- return;
421
- }
422
- const moduleDecl = (_a = this._evaluator
423
- .getDeclarationsForNameNode(moduleName)) === null || _a === void 0 ? void 0 : _a.filter((d) => (0, declaration_1.isAliasDeclaration)(d) &&
424
- (d.node.nodeType === 21 /* ImportAs */ || d.node.nodeType === 23 /* ImportFromAs */));
425
- if (!moduleDecl || moduleDecl.length === 0) {
426
- // ex) from xxx import yyy
427
- // yyy.property.foo
428
- return;
429
- }
430
- const importAs = moduleDecl[0].node;
431
- (0, collectionUtils_1.getOrAdd)(importUsed, importAs, () => []).push(dottedName);
432
- }
433
- _collectWildcardImports(nodeFound, wildcardImports) {
434
- const nameDecls = this._evaluator.getDeclarationsForNameNode(nodeFound);
435
- const aliasDeclFromWildCardImport = nameDecls === null || nameDecls === void 0 ? void 0 : nameDecls.find((d) => d.node.nodeType === 22 /* ImportFrom */ && d.node.isWildcardImport);
436
- if (!aliasDeclFromWildCardImport || !(0, declaration_1.isAliasDeclaration)(aliasDeclFromWildCardImport)) {
437
- return;
438
- }
439
- // ex) from module import *
440
- // foo()
441
- // bar()
442
- (0, collectionUtils_1.getOrAdd)(wildcardImports, aliasDeclFromWildCardImport.node, () => new Set()).add(nodeFound.value);
443
- }
444
- _updateNameInFromImportForSymbolReferences(parseResults, importStatements, nodeFound) {
445
- var _a;
446
- const filePath = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parseTree).filePath;
447
- const isDestination = filePath === this._newModuleFilePath;
448
- // ex) from ... import [symbol] ...
449
- const importFromAs = nodeFound.parent;
450
- const fromNode = importFromAs === null || importFromAs === void 0 ? void 0 : importFromAs.parent;
451
- const newModuleName = this._getNewModuleName(filePath, fromNode.module.leadingDots > 0,
452
- /* isLastPartImportName */ false);
453
- if (isDestination) {
454
- // If we have import statement for the symbol in the destination file,
455
- // we need to remove it.
456
- // ex) "from module import symbol, another_symbol" to
457
- // "from module import another_symbol"
458
- this._textEditTracker.deleteImportName(parseResults, importFromAs);
459
- return;
460
- }
461
- if (fromNode.imports.length === 1) {
462
- // ex) "from [module] import symbol" to "from [module.changed] import symbol"
463
- this._textEditTracker.addEditWithTextRange(parseResults, fromNode.module, newModuleName);
464
- return;
465
- }
466
- // ex) "from module import symbol, another_symbol" to
467
- // "from module import another_symbol" and "from module.changed import symbol"
468
- // Delete the existing import name including alias.
469
- this._textEditTracker.deleteImportName(parseResults, importFromAs);
470
- // For now, this won't merge absolute and relative path "from import" statement.
471
- const importNameInfo = {
472
- name: importFromAs.name.value,
473
- alias: (_a = importFromAs.alias) === null || _a === void 0 ? void 0 : _a.value,
474
- };
475
- this._textEditTracker.addOrUpdateImport(parseResults, importStatements, { name: this._newModuleName, nameForImportFrom: newModuleName }, (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(this._newModuleNameAndType), [importNameInfo], {
476
- currentFromImport: fromNode,
477
- originalModuleName: this._moduleName,
478
- });
479
- }
480
- _getReferenceModuleName(importStatements, imported) {
481
- var _a, _b;
482
- if (imported && imported.node.nodeType === 20 /* Import */) {
483
- return ((_a = imported.subnode) === null || _a === void 0 ? void 0 : _a.alias) ? imported.subnode.alias.value : this._newModuleName;
484
- }
485
- else if ((_b = importStatements.implicitImports) === null || _b === void 0 ? void 0 : _b.has(this._newModuleFilePath)) {
486
- const fromImportAs = importStatements.implicitImports.get(this._newModuleFilePath);
487
- return fromImportAs.alias ? fromImportAs.alias.value : fromImportAs.name.value;
488
- }
489
- return undefined;
490
- }
491
- _canReplaceImportName(parseResults, importAs, symbolReferences) {
492
- var _a;
493
- const nameToBind = (_a = importAs.alias) !== null && _a !== void 0 ? _a : (importAs.nodeType === 21 /* ImportAs */
494
- ? importAs.module.nameParts[importAs.module.nameParts.length - 1]
495
- : importAs.name);
496
- const declarations = documentSymbolCollector_1.DocumentSymbolCollector.getDeclarationsForNode(nameToBind, this._evaluator,
497
- /* resolveLocalName */ false, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Rename, this._token);
498
- if (declarations.length === 0) {
499
- return false;
500
- }
501
- const collector = new documentSymbolCollector_1.DocumentSymbolCollector([nameToBind.value], declarations, this._evaluator, this._token, parseResults.parseTree,
502
- /* treatModuleImportAndFromImportSame */ true,
503
- /* skipUnreachableCode */ false);
504
- for (const result of collector.collect()) {
505
- if ((0, parseTreeUtils_1.isImportModuleName)(result.node) ||
506
- (0, parseTreeUtils_1.isImportAlias)(result.node) ||
507
- (0, parseTreeUtils_1.isFromImportModuleName)(result.node) ||
508
- (0, parseTreeUtils_1.isFromImportName)(result.node) ||
509
- (0, parseTreeUtils_1.isFromImportAlias)(result.node)) {
510
- // collector will report decls as well. ignore decls.
511
- continue;
512
- }
513
- // other symbols from the module are used in the file.
514
- if (!symbolReferences.some((s) => textRange_1.TextRange.containsRange(s, result.node))) {
515
- return false;
516
- }
517
- }
518
- return true;
519
- }
520
- _renameFolderReferences(parseResults) {
521
- const collector = new documentSymbolCollector_1.DocumentSymbolCollector([this.lastModuleName], this.declarations, this._evaluator, this._token, parseResults.parseTree,
522
- /* treatModuleImportAndFromImportSame */ true,
523
- /* skipUnreachableCode */ false);
524
- // We only support simple rename of folder. Change all occurrence of the old folder name
525
- // to new name.
526
- for (const result of collector.collect()) {
527
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
528
- }
529
- }
530
- _renameModuleReferences(parseResults) {
531
- const collector = new documentSymbolCollector_1.DocumentSymbolCollector([this.lastModuleName], this.declarations, this._evaluator, this._token, parseResults.parseTree,
532
- /* treatModuleImportAndFromImportSame */ true,
533
- /* skipUnreachableCode */ false);
534
- const results = collector.collect();
535
- // Update module references first.
536
- this._updateModuleReferences(parseResults, results);
537
- // If the module file has moved, we need to update all relative paths used in the file to reflect the move.
538
- this._updateRelativeModuleNamePath(parseResults, results);
539
- }
540
- _updateRelativeModuleNamePath(parseResults, results) {
541
- const filePath = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parseTree).filePath;
542
- if (filePath !== this._moduleFilePath) {
543
- // We only update relative import paths for the file that has moved.
544
- return;
545
- }
546
- let importStatements;
547
- // Filter out module name that is already re-written.
548
- for (const edit of this._getNewRelativeModuleNamesForFileMoved(filePath, ModuleNameCollector.collect(parseResults.parseTree).filter((m) => !results.some((r) => textRange_1.TextRange.containsRange(m.parent, r.node))))) {
549
- this._textEditTracker.addEditWithTextRange(parseResults, edit.moduleName, edit.newModuleName);
550
- if (!edit.itemsToMove) {
551
- continue;
552
- }
553
- // This could introduce multiple import statements for same modules with
554
- // different symbols per module name. Unfortunately, there is no easy way to
555
- // prevent it since we can't see changes made by other code until all changes
556
- // are committed. In future, if we support snapshot and diff between snapshots,
557
- // then we can support those complex code generations.
558
- const fromNode = edit.moduleName.parent;
559
- // First, delete existing exported symbols from "from import" statement.
560
- for (const importFromAs of edit.itemsToMove) {
561
- this._textEditTracker.deleteImportName(parseResults, importFromAs);
562
- }
563
- importStatements =
564
- importStatements !== null && importStatements !== void 0 ? importStatements : (0, importStatementUtils_1.getTopLevelImports)(parseResults.parseTree, /* includeImplicitImports */ false);
565
- // For now, this won't merge absolute and relative path "from import"
566
- // statement.
567
- this._textEditTracker.addOrUpdateImport(parseResults, importStatements, {
568
- name: this._newModuleName,
569
- nameForImportFrom: (0, importStatementUtils_1.getRelativeModuleName)(this._fs, this._newModuleFilePath, this._newModuleFilePath,
570
- /* ignoreFolderStructure */ false,
571
- /* sourceIsFile */ true),
572
- }, (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(this._newModuleNameAndType), edit.itemsToMove.map((i) => {
573
- var _a;
574
- return { name: i.name.value, alias: (_a = i.alias) === null || _a === void 0 ? void 0 : _a.value };
575
- }), {
576
- currentFromImport: fromNode,
577
- originalModuleName: this._moduleName,
578
- });
579
- }
580
- }
581
- _updateModuleReferences(parseResults, results) {
582
- var _a, _b, _c, _d, _e;
583
- const filePath = (0, analyzerNodeInfo_1.getFileInfo)(parseResults.parseTree).filePath;
584
- let importStatements;
585
- for (const result of results) {
586
- const nodeFound = result.node;
587
- if (nodeFound.nodeType === 49 /* String */) {
588
- // ex) __all__ = ["[a]"]
589
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
590
- continue;
591
- }
592
- if ((0, parseTreeUtils_1.isImportModuleName)(nodeFound)) {
593
- if (!(0, parseTreeUtils_1.isLastNameOfModuleName)(nodeFound)) {
594
- // It must be directory and we don't support folder rename.
595
- continue;
596
- }
597
- const moduleNameNode = (0, parseTreeUtils_1.getFirstAncestorOrSelfOfKind)(nodeFound, 37 /* ModuleName */);
598
- // * Enhancement * one case we don't handle is introducing new symbol in __all__
599
- // or converting "import" statement to "from import" statement.
600
- //
601
- // when the existing statement was "import x as x" and it is changed to
602
- // "import y.z as z". we either need to introduce "z" in __all__ or convert
603
- // "import y.z as z" to "from y import z as z" to make sure we keep the symbol
604
- // visibility same.
605
- //
606
- // when we convert "import x as x" to "from y import z as z", we need to handle
607
- // deletion of existing import statement or (x as x) and inserting/merging
608
- // new "from import" statement.
609
- // If original module name was single word and it becomes dotted name without alias,
610
- // then we introduce alias to keep references as a single word.
611
- // ex) import [xxx] to import [aaa.bbb as bbb]
612
- if (moduleNameNode.nameParts.length === 1 &&
613
- ((_a = moduleNameNode.parent) === null || _a === void 0 ? void 0 : _a.nodeType) === 21 /* ImportAs */ &&
614
- !moduleNameNode.parent.alias &&
615
- this._newModuleNames.length > 1) {
616
- this._aliasIntroduced.add(moduleNameNode.parent);
617
- this._textEditTracker.addEditWithTextRange(parseResults, moduleNameNode, `${this._newModuleName} as ${this._newLastModuleName}`);
618
- continue;
619
- }
620
- // Otherwise, update whole module name to new name
621
- // ex) import [xxx.yyy] to import [aaa.bbb]
622
- this._textEditTracker.addEditWithTextRange(parseResults, moduleNameNode, this._newModuleName);
623
- continue;
624
- }
625
- if ((0, parseTreeUtils_1.isImportAlias)(nodeFound)) {
626
- // ex) import xxx as [yyy] to import xxx as [zzz]
627
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
628
- continue;
629
- }
630
- if ((0, parseTreeUtils_1.isFromImportModuleName)(nodeFound)) {
631
- if (!(0, parseTreeUtils_1.isLastNameOfModuleName)(nodeFound)) {
632
- // It must be directory and we don't support folder rename.
633
- continue;
634
- }
635
- const moduleNameNode = (0, parseTreeUtils_1.getFirstAncestorOrSelfOfKind)(nodeFound, 37 /* ModuleName */);
636
- const fromNode = moduleNameNode.parent;
637
- // We need to check whether imports of this import statement has
638
- // any implicit submodule imports or not. If there is one, we need to
639
- // either split or leave it as it is.
640
- const exportedSymbols = [];
641
- const subModules = [];
642
- for (const importFromAs of fromNode.imports) {
643
- if (this._isExportedSymbol(importFromAs.name)) {
644
- exportedSymbols.push(importFromAs);
645
- }
646
- else {
647
- subModules.push(importFromAs);
648
- }
649
- }
650
- if (subModules.length === 0) {
651
- // We don't have any sub modules, we can change module name to new one.
652
- // Update whole module name to new name.
653
- // ex) from [xxx.yyy] import zzz to from [aaa.bbb] import zzz
654
- this._textEditTracker.addEditWithTextRange(parseResults, moduleNameNode, this._getNewModuleName(filePath, moduleNameNode.leadingDots > 0,
655
- /* isLastPartImportName */ false));
656
- continue;
657
- }
658
- if (exportedSymbols.length === 0) {
659
- // We only have sub modules. That means module name actually refers to
660
- // folder name, not module (ex, __init__.py). Folder rename is done by
661
- // different code path.
662
- continue;
663
- }
664
- // Now, we need to split "from import" statement to 2.
665
- // Update module name if needed.
666
- if (fromNode.module.leadingDots > 0) {
667
- for (const edit of this._getNewRelativeModuleNamesForFileMoved(filePath, [fromNode.module])) {
668
- this._textEditTracker.addEditWithTextRange(parseResults, edit.moduleName, edit.newModuleName);
669
- }
670
- }
671
- // First, delete existing exported symbols from "from import" statement.
672
- for (const importFromAs of exportedSymbols) {
673
- this._textEditTracker.deleteImportName(parseResults, importFromAs);
674
- }
675
- importStatements =
676
- importStatements !== null && importStatements !== void 0 ? importStatements : (0, importStatementUtils_1.getTopLevelImports)(parseResults.parseTree, /* includeImplicitImports */ false);
677
- // For now, this won't merge absolute and relative path "from import"
678
- // statement.
679
- this._textEditTracker.addOrUpdateImport(parseResults, importStatements, { name: this._newModuleName }, (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(this._newModuleNameAndType), exportedSymbols.map((i) => {
680
- var _a;
681
- const name = results.findIndex((r) => r.node === i.name) >= 0 ? this._newLastModuleName : i.name.value;
682
- const alias = results.findIndex((r) => r.node === i.alias) >= 0
683
- ? this._newLastModuleName
684
- : (_a = i.alias) === null || _a === void 0 ? void 0 : _a.value;
685
- return { name, alias };
686
- }), {
687
- currentFromImport: fromNode,
688
- originalModuleName: this._moduleName,
689
- });
690
- continue;
691
- }
692
- if ((0, parseTreeUtils_1.isFromImportName)(nodeFound)) {
693
- if (this._textEditTracker.isNodeRemoved(nodeFound)) {
694
- // Import name is already removed.
695
- continue;
696
- }
697
- const fromNode = (_b = nodeFound.parent) === null || _b === void 0 ? void 0 : _b.parent;
698
- const newModuleName = this._getNewModuleName(filePath, fromNode.module.leadingDots > 0,
699
- /* isLastPartImportName */ true);
700
- // If the name bound to symbol re-exported, we don't need to update module name.
701
- // Existing logic should make sure re-exported symbol name work as before after
702
- // symbol rename.
703
- if (this._isExportedSymbol(nodeFound)) {
704
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
705
- continue;
706
- }
707
- if (fromNode.imports.length === 1) {
708
- // ex) from xxx import [yyy] to from [aaa.bbb] import [zzz]
709
- this._textEditTracker.addEditWithTextRange(parseResults, fromNode.module, newModuleName);
710
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
711
- }
712
- else {
713
- // Delete the existing import name including alias.
714
- const importFromAs = nodeFound.parent;
715
- // Update module name if needed.
716
- if (fromNode.module.leadingDots > 0) {
717
- for (const edit of this._getNewRelativeModuleNamesForFileMoved(filePath, [fromNode.module])) {
718
- this._textEditTracker.addEditWithTextRange(parseResults, edit.moduleName, edit.newModuleName);
719
- }
720
- }
721
- this._textEditTracker.deleteImportName(parseResults, importFromAs);
722
- importStatements =
723
- importStatements !== null && importStatements !== void 0 ? importStatements : (0, importStatementUtils_1.getTopLevelImports)(parseResults.parseTree, /* includeImplicitImports */ false);
724
- // ex) from xxx import yyy, [zzz] to
725
- // from xxx import yyy
726
- // from [aaa.bbb] import [ccc]
727
- // or
728
- // from aaa.bbb import ddd
729
- // from xxx import yyy, [zzz] to
730
- // from aaa.bbb import [ccc], ddd
731
- //
732
- // For now, this won't merge absolute and relative path "from import"
733
- // statement.
734
- const importNameInfo = {
735
- name: this._newLastModuleName,
736
- alias: ((_c = importFromAs.alias) === null || _c === void 0 ? void 0 : _c.value) === this.lastModuleName
737
- ? this._newLastModuleName
738
- : (_d = importFromAs.alias) === null || _d === void 0 ? void 0 : _d.value,
739
- };
740
- this._textEditTracker.addOrUpdateImport(parseResults, importStatements, { name: this._newModuleName, nameForImportFrom: newModuleName }, (0, importStatementUtils_1.getImportGroupFromModuleNameAndType)(this._newModuleNameAndType), [importNameInfo], {
741
- currentFromImport: fromNode,
742
- originalModuleName: this._moduleName,
743
- });
744
- }
745
- continue;
746
- }
747
- if ((0, parseTreeUtils_1.isFromImportAlias)(nodeFound)) {
748
- if (this._textEditTracker.isNodeRemoved(nodeFound)) {
749
- // alias is already removed.
750
- continue;
751
- }
752
- // ex) from ccc import xxx as [yyy] to from ccc import xxx as [zzz]
753
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
754
- continue;
755
- }
756
- /** TODO: if we get more than 1 decls, flag it as attention needed */
757
- const decls = documentSymbolCollector_1.DocumentSymbolCollector.getDeclarationsForNode(nodeFound, this._evaluator,
758
- /* resolveLocalName */ false, documentSymbolCollector_1.DocumentSymbolCollectorUseCase.Rename, this._token).filter((d) => (0, declaration_1.isAliasDeclaration)(d));
759
- if (this._onlyNameChanged) {
760
- // Simple case. only name has changed. but not path.
761
- // Just replace name to new symbol name.
762
- // ex) a.[b].foo() to a.[z].foo()
763
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
764
- continue;
765
- }
766
- if (decls === null || decls === void 0 ? void 0 : decls.some((d) => !d.usesLocalName &&
767
- (!d.node || d.node.nodeType === 21 /* ImportAs */) &&
768
- !this._aliasIntroduced.has(d.node))) {
769
- const dottedName = (0, parseTreeUtils_1.getDottedNameWithGivenNodeAsLastName)(nodeFound);
770
- if (((_e = dottedName.parent) === null || _e === void 0 ? void 0 : _e.nodeType) !== 35 /* MemberAccess */) {
771
- // Replace whole dotted name with new module name.
772
- this._textEditTracker.addEditWithTextRange(parseResults, dottedName, this._newModuleName);
773
- continue;
774
- }
775
- // Check whether name after me is sub module or not.
776
- // ex) a.b.[c]
777
- const nextNameDecl = this._evaluator.getDeclarationsForNameNode(dottedName.parent.memberName);
778
- if (!nextNameDecl || nextNameDecl.length === 0) {
779
- // Next dotted name is sub module. That means dottedName actually refers to folder names, not modules.
780
- // and We don't support renaming folder. So, leave things as they are.
781
- // ex) import a.b.c
782
- // [a.b].[c]
783
- continue;
784
- }
785
- // Next name is actual symbol. Replace whole name to new module name.
786
- // ex) import a.b.c
787
- // [a.b.c].[foo]()
788
- this._textEditTracker.addEditWithTextRange(parseResults, dottedName, this._newModuleName);
789
- continue;
790
- }
791
- if (result.node.value !== this._newLastModuleName) {
792
- this._textEditTracker.addEditWithTextRange(parseResults, result.range, this._newLastModuleName);
793
- continue;
794
- }
795
- }
796
- }
797
- _getNewRelativeModuleNamesForFileMoved(filePath, moduleNames) {
798
- if (filePath !== this._moduleFilePath) {
799
- // We only update relative import paths for the file that has moved.
800
- return [];
801
- }
802
- const originalFileName = (0, pathUtils_1.stripFileExtension)((0, pathUtils_1.getFileName)(filePath));
803
- const originalInit = originalFileName === '__init__';
804
- const originalDirectory = (0, pathUtils_1.getDirectoryPath)(filePath);
805
- const newNames = [];
806
- for (const moduleName of moduleNames) {
807
- // Filter out all absolute path.
808
- if (moduleName.leadingDots === 0) {
809
- continue;
810
- }
811
- const result = this._getNewModuleNameInfoForFileMoved(moduleName, originalInit, originalDirectory);
812
- if (!result) {
813
- continue;
814
- }
815
- const newModuleName = (0, importStatementUtils_1.getRelativeModuleName)(this._fs, result.src, result.dest,
816
- /* ignoreFolderStructure */ false,
817
- /* sourceIsFile */ true);
818
- newNames.push({ moduleName, newModuleName, itemsToMove: result.itemsToMove });
819
- }
820
- return newNames;
821
- }
822
- _getNewModuleNameInfoForFileMoved(moduleName, originalInit, originalDirectory) {
823
- const importInfo = (0, analyzerNodeInfo_1.getImportInfo)(moduleName);
824
- if (!importInfo) {
825
- return undefined;
826
- }
827
- let importPath = importInfo.resolvedPaths[importInfo.resolvedPaths.length - 1];
828
- if (!importPath) {
829
- // It is possible for the module name to point to namespace folder (no __init__).
830
- // See whether we can use some heuristic to get importPath
831
- if (moduleName.nameParts.length === 0) {
832
- const directory = (0, importStatementUtils_1.getDirectoryLeadingDotsPointsTo)(originalDirectory, moduleName.leadingDots);
833
- if (!directory) {
834
- return undefined;
835
- }
836
- // Add fake __init__.py since we know this is namespace folder.
837
- importPath = (0, pathUtils_1.combinePaths)(directory, '__init__.py');
838
- }
839
- else {
840
- return undefined;
841
- }
842
- }
843
- // Check whether module is pointing to moved file itself and whether it is __init__
844
- if (this._moduleFilePath !== importPath || !originalInit) {
845
- return { src: this._newModuleFilePath, dest: importPath };
846
- }
847
- // Now, moduleName is pointing to __init__ which point to moved file itself.
848
- // We need to check whether imports of this import statement has
849
- // any implicit submodule imports or not. If there is one, we need to
850
- // either split or leave it as it is.
851
- const exportedSymbols = [];
852
- const subModules = [];
853
- for (const importFromAs of moduleName.parent.imports) {
854
- if (this._isExportedSymbol(importFromAs.name)) {
855
- exportedSymbols.push(importFromAs);
856
- }
857
- else {
858
- subModules.push(importFromAs);
859
- }
860
- }
861
- // Point to itself.
862
- if (subModules.length === 0) {
863
- return { src: this._newModuleFilePath, dest: this._newModuleFilePath };
864
- }
865
- // "." is used to point folder location.
866
- if (exportedSymbols.length === 0) {
867
- return { src: this._newModuleFilePath, dest: this._moduleFilePath };
868
- }
869
- // now we need to split, provide split info as well.
870
- return {
871
- src: this._newModuleFilePath,
872
- dest: this._moduleFilePath,
873
- itemsToMove: [...exportedSymbols],
874
- };
875
- }
876
- _isExportedSymbol(nameNode) {
877
- const decls = this._evaluator.getDeclarationsForNameNode(nameNode);
878
- if (!decls) {
879
- return false;
880
- }
881
- // If submoduleFallback exists, then, it points to submodule not symbol.
882
- return !decls.some((d) => (0, declaration_1.isAliasDeclaration)(d) && d.submoduleFallback);
883
- }
884
- _getNewModuleName(currentFilePath, isRelativePath, isLastPartImportName) {
885
- const filePath = currentFilePath === this._moduleFilePath ? this._newModuleFilePath : currentFilePath;
886
- // If the existing code was using relative path, try to keep the relative path.
887
- const moduleName = isRelativePath
888
- ? (0, importStatementUtils_1.getRelativeModuleName)(this._fs, filePath, this._newModuleFilePath, isLastPartImportName,
889
- /* sourceIsFile*/ true)
890
- : this._newModuleName;
891
- if (isLastPartImportName && moduleName.endsWith(this._newLastModuleName)) {
892
- const dotPrefix = moduleName === this._newLastModuleName
893
- ? 0
894
- : moduleName.length > this._newLastModuleName.length + 1
895
- ? moduleName[moduleName.length - this._newLastModuleName.length - 2] !== '.'
896
- ? 1
897
- : 0
898
- : 0;
899
- const length = moduleName.length - this._newLastModuleName.length - dotPrefix;
900
- //ex) x.y.z used in "from x.y import z"
901
- const newModuleName = moduleName.substr(0, length);
902
- return newModuleName.length > 0 ? newModuleName : '.';
903
- }
904
- // ex) x.y.z used in "from x.y.z import ..."
905
- return moduleName;
906
- }
907
- get _moduleName() {
908
- return this._moduleNameAndType.moduleName;
909
- }
910
- get _newLastModuleName() {
911
- return this._newModuleNames[this._newModuleNames.length - 1];
912
- }
913
- get _newModuleName() {
914
- return this._newModuleNameAndType.moduleName;
915
- }
916
- }
917
- exports.RenameModuleProvider = RenameModuleProvider;
918
- class ModuleNameCollector extends parseTreeWalker_1.ParseTreeWalker {
919
- constructor() {
920
- super(...arguments);
921
- this._result = [];
922
- }
923
- walk(node) {
924
- if ((0, parseNodes_1.isExpressionNode)(node)) {
925
- return;
926
- }
927
- super.walk(node);
928
- }
929
- visitModuleName(node) {
930
- this._result.push(node);
931
- return false;
932
- }
933
- static collect(root) {
934
- const collector = new ModuleNameCollector();
935
- collector.walk(root);
936
- return collector._result;
937
- }
938
- }
939
- //# sourceMappingURL=renameModuleProvider.js.map