forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathorganizeImports.ts
More file actions
481 lines (405 loc) · 22.1 KB
/
organizeImports.ts
File metadata and controls
481 lines (405 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/* @internal */
namespace ts.OrganizeImports {
/**
* Organize imports by:
* 1) Removing unused imports
* 2) Coalescing imports from the same module
* 3) Sorting imports
*/
export function organizeImports(
sourceFile: SourceFile,
formatContext: formatting.FormatContext,
host: LanguageServiceHost,
program: Program,
preferences: UserPreferences,
) {
const changeTracker = textChanges.ChangeTracker.fromContext({ host, formatContext, preferences });
const coalesceAndOrganizeImports = (importGroup: readonly ImportDeclaration[]) => stableSort(
coalesceImports(removeUnusedImports(importGroup, sourceFile, program)),
(s1, s2) => compareImportsOrRequireStatements(s1, s2));
// All of the old ImportDeclarations in the file, in syntactic order.
const topLevelImportDecls = sourceFile.statements.filter(isImportDeclaration);
organizeImportsWorker(topLevelImportDecls, coalesceAndOrganizeImports);
// All of the old ExportDeclarations in the file, in syntactic order.
const topLevelExportDecls = sourceFile.statements.filter(isExportDeclaration);
organizeImportsWorker(topLevelExportDecls, coalesceExports);
for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
if (!ambientModule.body) { continue; }
const ambientModuleImportDecls = ambientModule.body.statements.filter(isImportDeclaration);
organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports);
const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, coalesceExports);
}
return changeTracker.getChanges();
function organizeImportsWorker<T extends ImportDeclaration | ExportDeclaration>(
oldImportDecls: readonly T[],
coalesce: (group: readonly T[]) => readonly T[]) {
if (length(oldImportDecls) === 0) {
return;
}
// Special case: normally, we'd expect leading and trailing trivia to follow each import
// around as it's sorted. However, we do not want this to happen for leading trivia
// on the first import because it is probably the header comment for the file.
// Consider: we could do a more careful check that this trivia is actually a header,
// but the consequences of being wrong are very minor.
suppressLeadingTrivia(oldImportDecls[0]);
const oldImportGroups = group(oldImportDecls, importDecl => getExternalModuleName(importDecl.moduleSpecifier!)!);
const sortedImportGroups = stableSort(oldImportGroups, (group1, group2) => compareModuleSpecifiers(group1[0].moduleSpecifier, group2[0].moduleSpecifier));
const newImportDecls = flatMap(sortedImportGroups, importGroup =>
getExternalModuleName(importGroup[0].moduleSpecifier!)
? coalesce(importGroup)
: importGroup);
// Delete or replace the first import.
if (newImportDecls.length === 0) {
changeTracker.delete(sourceFile, oldImportDecls[0]);
}
else {
// Note: Delete the surrounding trivia because it will have been retained in newImportDecls.
changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, {
leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, // Leave header comment in place
trailingTriviaOption: textChanges.TrailingTriviaOption.Include,
suffix: getNewLineOrDefaultFromHost(host, formatContext.options),
});
}
// Delete any subsequent imports.
for (let i = 1; i < oldImportDecls.length; i++) {
changeTracker.deleteNode(sourceFile, oldImportDecls[i]);
}
}
}
function removeUnusedImports(oldImports: readonly ImportDeclaration[], sourceFile: SourceFile, program: Program) {
const typeChecker = program.getTypeChecker();
const jsxNamespace = typeChecker.getJsxNamespace(sourceFile);
const jsxFragmentFactory = typeChecker.getJsxFragmentFactory(sourceFile);
const jsxElementsPresent = !!(sourceFile.transformFlags & TransformFlags.ContainsJsx);
const usedImports: ImportDeclaration[] = [];
for (const importDecl of oldImports) {
const { importClause, moduleSpecifier } = importDecl;
if (!importClause) {
// Imports without import clauses are assumed to be included for their side effects and are not removed.
usedImports.push(importDecl);
continue;
}
let { name, namedBindings } = importClause;
// Default import
if (name && !isDeclarationUsed(name)) {
name = undefined;
}
if (namedBindings) {
if (isNamespaceImport(namedBindings)) {
// Namespace import
if (!isDeclarationUsed(namedBindings.name)) {
namedBindings = undefined;
}
}
else {
// List of named imports
const newElements = namedBindings.elements.filter(e => isDeclarationUsed(e.name));
if (newElements.length < namedBindings.elements.length) {
namedBindings = newElements.length
? factory.updateNamedImports(namedBindings, newElements)
: undefined;
}
}
}
if (name || namedBindings) {
usedImports.push(updateImportDeclarationAndClause(importDecl, name, namedBindings));
}
// If a module is imported to be augmented, it’s used
else if (hasModuleDeclarationMatchingSpecifier(sourceFile, moduleSpecifier)) {
// If we’re in a declaration file, it’s safe to remove the import clause from it
if (sourceFile.isDeclarationFile) {
usedImports.push(factory.createImportDeclaration(
importDecl.decorators,
importDecl.modifiers,
/*importClause*/ undefined,
moduleSpecifier));
}
// If we’re not in a declaration file, we can’t remove the import clause even though
// the imported symbols are unused, because removing them makes it look like the import
// declaration has side effects, which will cause it to be preserved in the JS emit.
else {
usedImports.push(importDecl);
}
}
}
return usedImports;
function isDeclarationUsed(identifier: Identifier) {
// The JSX factory symbol is always used if JSX elements are present - even if they are not allowed.
return jsxElementsPresent && (identifier.text === jsxNamespace || jsxFragmentFactory && identifier.text === jsxFragmentFactory) ||
FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
}
}
function hasModuleDeclarationMatchingSpecifier(sourceFile: SourceFile, moduleSpecifier: Expression) {
const moduleSpecifierText = isStringLiteral(moduleSpecifier) && moduleSpecifier.text;
return isString(moduleSpecifierText) && some(sourceFile.moduleAugmentations, moduleName =>
isStringLiteral(moduleName)
&& moduleName.text === moduleSpecifierText);
}
function getExternalModuleName(specifier: Expression) {
return specifier !== undefined && isStringLiteralLike(specifier)
? specifier.text
: undefined;
}
// Internal for testing
/**
* @param importGroup a list of ImportDeclarations, all with the same module name.
*/
export function coalesceImports(importGroup: readonly ImportDeclaration[]) {
if (importGroup.length === 0) {
return importGroup;
}
const { importWithoutClause, typeOnlyImports, regularImports } = getCategorizedImports(importGroup);
const coalescedImports: ImportDeclaration[] = [];
if (importWithoutClause) {
coalescedImports.push(importWithoutClause);
}
for (const group of [regularImports, typeOnlyImports]) {
const isTypeOnly = group === typeOnlyImports;
const { defaultImports, namespaceImports, namedImports } = group;
// Normally, we don't combine default and namespace imports, but it would be silly to
// produce two import declarations in this special case.
if (!isTypeOnly && defaultImports.length === 1 && namespaceImports.length === 1 && namedImports.length === 0) {
// Add the namespace import to the existing default ImportDeclaration.
const defaultImport = defaultImports[0];
coalescedImports.push(
updateImportDeclarationAndClause(defaultImport, defaultImport.importClause!.name, namespaceImports[0].importClause!.namedBindings)); // TODO: GH#18217
continue;
}
const sortedNamespaceImports = stableSort(namespaceImports, (i1, i2) =>
compareIdentifiers((i1.importClause!.namedBindings as NamespaceImport).name, (i2.importClause!.namedBindings as NamespaceImport).name)); // TODO: GH#18217
for (const namespaceImport of sortedNamespaceImports) {
// Drop the name, if any
coalescedImports.push(
updateImportDeclarationAndClause(namespaceImport, /*name*/ undefined, namespaceImport.importClause!.namedBindings)); // TODO: GH#18217
}
if (defaultImports.length === 0 && namedImports.length === 0) {
continue;
}
let newDefaultImport: Identifier | undefined;
const newImportSpecifiers: ImportSpecifier[] = [];
if (defaultImports.length === 1) {
newDefaultImport = defaultImports[0].importClause!.name;
}
else {
for (const defaultImport of defaultImports) {
newImportSpecifiers.push(
factory.createImportSpecifier(factory.createIdentifier("default"), defaultImport.importClause!.name!)); // TODO: GH#18217
}
}
newImportSpecifiers.push(...flatMap(namedImports, i => (i.importClause!.namedBindings as NamedImports).elements)); // TODO: GH#18217
const sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers);
const importDecl = defaultImports.length > 0
? defaultImports[0]
: namedImports[0];
const newNamedImports = sortedImportSpecifiers.length === 0
? newDefaultImport
? undefined
: factory.createNamedImports(emptyArray)
: namedImports.length === 0
? factory.createNamedImports(sortedImportSpecifiers)
: factory.updateNamedImports(namedImports[0].importClause!.namedBindings as NamedImports, sortedImportSpecifiers); // TODO: GH#18217
// Type-only imports are not allowed to mix default, namespace, and named imports in any combination.
// We could rewrite a default import as a named import (`import { default as name }`), but we currently
// choose not to as a stylistic preference.
if (isTypeOnly && newDefaultImport && newNamedImports) {
coalescedImports.push(
updateImportDeclarationAndClause(importDecl, newDefaultImport, /*namedBindings*/ undefined));
coalescedImports.push(
updateImportDeclarationAndClause(namedImports[0] ?? importDecl, /*name*/ undefined, newNamedImports));
}
else {
coalescedImports.push(
updateImportDeclarationAndClause(importDecl, newDefaultImport, newNamedImports));
}
}
return coalescedImports;
}
interface ImportGroup {
defaultImports: ImportDeclaration[];
namespaceImports: ImportDeclaration[];
namedImports: ImportDeclaration[];
}
/*
* Returns entire import declarations because they may already have been rewritten and
* may lack parent pointers. The desired parts can easily be recovered based on the
* categorization.
*
* NB: There may be overlap between `defaultImports` and `namespaceImports`/`namedImports`.
*/
function getCategorizedImports(importGroup: readonly ImportDeclaration[]) {
let importWithoutClause: ImportDeclaration | undefined;
const typeOnlyImports: ImportGroup = { defaultImports: [], namespaceImports: [], namedImports: [] };
const regularImports: ImportGroup = { defaultImports: [], namespaceImports: [], namedImports: [] };
for (const importDeclaration of importGroup) {
if (importDeclaration.importClause === undefined) {
// Only the first such import is interesting - the others are redundant.
// Note: Unfortunately, we will lose trivia that was on this node.
importWithoutClause = importWithoutClause || importDeclaration;
continue;
}
const group = importDeclaration.importClause.isTypeOnly ? typeOnlyImports : regularImports;
const { name, namedBindings } = importDeclaration.importClause;
if (name) {
group.defaultImports.push(importDeclaration);
}
if (namedBindings) {
if (isNamespaceImport(namedBindings)) {
group.namespaceImports.push(importDeclaration);
}
else {
group.namedImports.push(importDeclaration);
}
}
}
return {
importWithoutClause,
typeOnlyImports,
regularImports,
};
}
// Internal for testing
/**
* @param exportGroup a list of ExportDeclarations, all with the same module name.
*/
export function coalesceExports(exportGroup: readonly ExportDeclaration[]) {
if (exportGroup.length === 0) {
return exportGroup;
}
const { exportWithoutClause, namedExports, typeOnlyExports } = getCategorizedExports(exportGroup);
const coalescedExports: ExportDeclaration[] = [];
if (exportWithoutClause) {
coalescedExports.push(exportWithoutClause);
}
for (const exportGroup of [namedExports, typeOnlyExports]) {
if (exportGroup.length === 0) {
continue;
}
const newExportSpecifiers: ExportSpecifier[] = [];
newExportSpecifiers.push(...flatMap(exportGroup, i => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray));
const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers);
const exportDecl = exportGroup[0];
coalescedExports.push(
factory.updateExportDeclaration(
exportDecl,
exportDecl.decorators,
exportDecl.modifiers,
exportDecl.isTypeOnly,
exportDecl.exportClause && (
isNamedExports(exportDecl.exportClause) ?
factory.updateNamedExports(exportDecl.exportClause, sortedExportSpecifiers) :
factory.updateNamespaceExport(exportDecl.exportClause, exportDecl.exportClause.name)
),
exportDecl.moduleSpecifier));
}
return coalescedExports;
/*
* Returns entire export declarations because they may already have been rewritten and
* may lack parent pointers. The desired parts can easily be recovered based on the
* categorization.
*/
function getCategorizedExports(exportGroup: readonly ExportDeclaration[]) {
let exportWithoutClause: ExportDeclaration | undefined;
const namedExports: ExportDeclaration[] = [];
const typeOnlyExports: ExportDeclaration[] = [];
for (const exportDeclaration of exportGroup) {
if (exportDeclaration.exportClause === undefined) {
// Only the first such export is interesting - the others are redundant.
// Note: Unfortunately, we will lose trivia that was on this node.
exportWithoutClause = exportWithoutClause || exportDeclaration;
}
else if (exportDeclaration.isTypeOnly) {
typeOnlyExports.push(exportDeclaration);
}
else {
namedExports.push(exportDeclaration);
}
}
return {
exportWithoutClause,
namedExports,
typeOnlyExports,
};
}
}
function updateImportDeclarationAndClause(
importDeclaration: ImportDeclaration,
name: Identifier | undefined,
namedBindings: NamedImportBindings | undefined) {
return factory.updateImportDeclaration(
importDeclaration,
importDeclaration.decorators,
importDeclaration.modifiers,
factory.updateImportClause(importDeclaration.importClause!, importDeclaration.importClause!.isTypeOnly, name, namedBindings), // TODO: GH#18217
importDeclaration.moduleSpecifier);
}
function sortSpecifiers<T extends ImportOrExportSpecifier>(specifiers: readonly T[]) {
return stableSort(specifiers, compareImportOrExportSpecifiers);
}
export function compareImportOrExportSpecifiers<T extends ImportOrExportSpecifier>(s1: T, s2: T) {
return compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name)
|| compareIdentifiers(s1.name, s2.name);
}
/* internal */ // Exported for testing
export function compareModuleSpecifiers(m1: Expression | undefined, m2: Expression | undefined) {
const name1 = m1 === undefined ? undefined : getExternalModuleName(m1);
const name2 = m2 === undefined ? undefined : getExternalModuleName(m2);
return compareBooleans(name1 === undefined, name2 === undefined) ||
compareBooleans(isExternalModuleNameRelative(name1!), isExternalModuleNameRelative(name2!)) ||
compareStringsCaseInsensitive(name1!, name2!);
}
function compareIdentifiers(s1: Identifier, s2: Identifier) {
return compareStringsCaseInsensitive(s1.text, s2.text);
}
function getModuleSpecifierExpression(declaration: AnyImportOrRequireStatement): Expression | undefined {
switch (declaration.kind) {
case SyntaxKind.ImportEqualsDeclaration:
return tryCast(declaration.moduleReference, isExternalModuleReference)?.expression;
case SyntaxKind.ImportDeclaration:
return declaration.moduleSpecifier;
case SyntaxKind.VariableStatement:
return declaration.declarationList.declarations[0].initializer.arguments[0];
}
}
export function importsAreSorted(imports: readonly AnyImportOrRequireStatement[]): imports is SortedReadonlyArray<AnyImportOrRequireStatement> {
return arrayIsSorted(imports, compareImportsOrRequireStatements);
}
export function importSpecifiersAreSorted(imports: readonly ImportSpecifier[]): imports is SortedReadonlyArray<ImportSpecifier> {
return arrayIsSorted(imports, compareImportOrExportSpecifiers);
}
export function getImportDeclarationInsertionIndex(sortedImports: SortedReadonlyArray<AnyImportOrRequireStatement>, newImport: AnyImportOrRequireStatement) {
const index = binarySearch(sortedImports, newImport, identity, compareImportsOrRequireStatements);
return index < 0 ? ~index : index;
}
export function getImportSpecifierInsertionIndex(sortedImports: SortedReadonlyArray<ImportSpecifier>, newImport: ImportSpecifier) {
const index = binarySearch(sortedImports, newImport, identity, compareImportOrExportSpecifiers);
return index < 0 ? ~index : index;
}
export function compareImportsOrRequireStatements(s1: AnyImportOrRequireStatement, s2: AnyImportOrRequireStatement) {
return compareModuleSpecifiers(getModuleSpecifierExpression(s1), getModuleSpecifierExpression(s2)) || compareImportKind(s1, s2);
}
function compareImportKind(s1: AnyImportOrRequireStatement, s2: AnyImportOrRequireStatement) {
return compareValues(getImportKindOrder(s1), getImportKindOrder(s2));
}
// 1. Side-effect imports
// 2. Type-only imports
// 3. Namespace imports
// 4. Default imports
// 5. Named imports
// 6. ImportEqualsDeclarations
// 7. Require variable statements
function getImportKindOrder(s1: AnyImportOrRequireStatement) {
switch (s1.kind) {
case SyntaxKind.ImportDeclaration:
if (!s1.importClause) return 0;
if (s1.importClause.isTypeOnly) return 1;
if (s1.importClause.namedBindings?.kind === SyntaxKind.NamespaceImport) return 2;
if (s1.importClause.name) return 3;
return 4;
case SyntaxKind.ImportEqualsDeclaration:
return 5;
case SyntaxKind.VariableStatement:
return 6;
}
}
}