Skip to content

Organize type imports #55269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10074,6 +10074,7 @@ export interface UserPreferences {
readonly organizeImportsNumericCollation?: boolean;
readonly organizeImportsAccentCollation?: boolean;
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";
readonly excludeLibrarySymbolsInNavTo?: boolean;
}

Expand Down
10 changes: 6 additions & 4 deletions src/harness/fourslashImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3521,10 +3521,12 @@ export class TestState {
actualTextArray.push(text);

// Undo changes to perform next fix
const span = change.textChanges[0].span;
const deletedText = originalContent.substr(span.start, change.textChanges[0].span.length);
const insertedText = change.textChanges[0].newText;
this.editScriptAndUpdateMarkers(fileName, span.start, span.start + insertedText.length, deletedText);
for (const textChange of change.textChanges) {
const span = textChange.span;
const deletedText = originalContent.slice(span.start, span.start + textChange.span.length);
const insertedText = textChange.newText;
this.editScriptAndUpdateMarkers(fileName, span.start, span.start + insertedText.length, deletedText);
}
}
if (expectedTextArray.length !== actualTextArray.length) {
this.raiseError(`Expected ${expectedTextArray.length} import fixes, got ${actualTextArray.length}:\n\n${actualTextArray.join("\n\n" + "-".repeat(20) + "\n\n")}`);
Expand Down
7 changes: 7 additions & 0 deletions src/server/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3643,6 +3643,13 @@ export interface UserPreferences {
* Default: `false`
*/
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
/**
* Indicates where named type-only imports should sort. "inline" sorts named imports without regard to if the import is
* type-only.
*
* Default: `last`
*/
readonly organizeImportsTypeOrder?: "last" | "first" | "inline";

/**
* Indicates whether {@link ReferencesResponseItem.lineText} is supported.
Expand Down
9 changes: 5 additions & 4 deletions src/services/codefixes/importFixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
getSourceFileOfNode,
getSymbolId,
getTokenAtPosition,
getTokenPosOfNode,
getTypeKeywordOfTypeOnlyImport,
getUniqueSymbolId,
hostGetCanonicalFileName,
Expand Down Expand Up @@ -1406,14 +1407,14 @@ function promoteFromTypeOnly(
if (aliasDeclaration.parent.elements.length > 1 && sortKind) {
const newSpecifier = factory.updateImportSpecifier(aliasDeclaration, /*isTypeOnly*/ false, aliasDeclaration.propertyName, aliasDeclaration.name);
const comparer = OrganizeImports.getOrganizeImportsComparer(preferences, sortKind === SortKind.CaseInsensitive);
const insertionIndex = OrganizeImports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer);
if (aliasDeclaration.parent.elements.indexOf(aliasDeclaration) !== insertionIndex) {
const insertionIndex = OrganizeImports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier, comparer, preferences);
if (insertionIndex !== aliasDeclaration.parent.elements.indexOf(aliasDeclaration)) {
changes.delete(sourceFile, aliasDeclaration);
changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex);
return aliasDeclaration;
}
}
changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()!);
changes.deleteRange(sourceFile, { pos: getTokenPosOfNode(aliasDeclaration.getFirstToken()!), end: getTokenPosOfNode(aliasDeclaration.propertyName ?? aliasDeclaration.name) });
return aliasDeclaration;
}
else {
Expand Down Expand Up @@ -1538,7 +1539,7 @@ function doAddExistingFix(
// type-only, there's no need to ask for the insertion index - it's 0.
const insertionIndex = promoteFromTypeOnly && !spec.isTypeOnly
? 0
: OrganizeImports.getImportSpecifierInsertionIndex(existingSpecifiers, spec, comparer);
: OrganizeImports.getImportSpecifierInsertionIndex(existingSpecifiers, spec, comparer, preferences);
changes.insertImportSpecifierAtIndex(sourceFile, spec, clause.namedBindings as NamedImports, insertionIndex);
}
}
Expand Down
88 changes: 68 additions & 20 deletions src/services/organizeImports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ import {
flatMap,
formatting,
getNewLineOrDefaultFromHost,
getStringComparer,
getUILocale,
group,
groupBy,
Identifier,
identity,
ImportClause,
Expand Down Expand Up @@ -94,7 +96,7 @@ export function organizeImports(

const processImportsOfSameModuleSpecifier = (importGroup: readonly ImportDeclaration[]) => {
if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program);
if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile);
if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, comparer, sourceFile, preferences);
if (shouldSort) importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, comparer));
return importGroup;
};
Expand All @@ -104,7 +106,7 @@ export function organizeImports(
// Exports are always used
if (mode !== OrganizeImportsMode.RemoveUnused) {
// All of the old ExportDeclarations in the file, in syntactic order.
getTopLevelExportGroups(sourceFile).forEach(exportGroupDecl => organizeImportsWorker(exportGroupDecl, group => coalesceExportsWorker(group, comparer)));
getTopLevelExportGroups(sourceFile).forEach(exportGroupDecl => organizeImportsWorker(exportGroupDecl, group => coalesceExportsWorker(group, comparer, preferences)));
}

for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) {
Expand All @@ -116,7 +118,7 @@ export function organizeImports(
// Exports are always used
if (mode !== OrganizeImportsMode.RemoveUnused) {
const ambientModuleExportDecls = ambientModule.body.statements.filter(isExportDeclaration);
organizeImportsWorker(ambientModuleExportDecls, group => coalesceExportsWorker(group, comparer));
organizeImportsWorker(ambientModuleExportDecls, group => coalesceExportsWorker(group, comparer, preferences));
}
}

Expand Down Expand Up @@ -310,12 +312,12 @@ function getExternalModuleName(specifier: Expression | undefined) {
* @deprecated Only used for testing
* @internal
*/
export function coalesceImports(importGroup: readonly ImportDeclaration[], ignoreCase: boolean, sourceFile?: SourceFile): readonly ImportDeclaration[] {
export function coalesceImports(importGroup: readonly ImportDeclaration[], ignoreCase: boolean, sourceFile?: SourceFile, preferences?: UserPreferences): readonly ImportDeclaration[] {
const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase);
return coalesceImportsWorker(importGroup, comparer, sourceFile);
return coalesceImportsWorker(importGroup, comparer, sourceFile, preferences);
}

function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], comparer: Comparer<string>, sourceFile?: SourceFile): readonly ImportDeclaration[] {
function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], comparer: Comparer<string>, sourceFile?: SourceFile, preferences?: UserPreferences): readonly ImportDeclaration[] {
if (importGroup.length === 0) {
return importGroup;
}
Expand Down Expand Up @@ -374,7 +376,7 @@ function coalesceImportsWorker(importGroup: readonly ImportDeclaration[], compar
newImportSpecifiers.push(...getNewImportSpecifiers(namedImports));

const sortedImportSpecifiers = factory.createNodeArray(
sortSpecifiers(newImportSpecifiers, comparer),
sortSpecifiers(newImportSpecifiers, comparer, preferences),
firstNamedImport?.importClause.namedBindings.elements.hasTrailingComma,
);

Expand Down Expand Up @@ -491,18 +493,17 @@ function getCategorizedImports(importGroup: readonly ImportDeclaration[]) {
* @deprecated Only used for testing
* @internal
*/
export function coalesceExports(exportGroup: readonly ExportDeclaration[], ignoreCase: boolean) {
export function coalesceExports(exportGroup: readonly ExportDeclaration[], ignoreCase: boolean, preferences?: UserPreferences) {
const comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase);
return coalesceExportsWorker(exportGroup, comparer);
return coalesceExportsWorker(exportGroup, comparer, preferences);
}

function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], comparer: Comparer<string>) {
function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], comparer: Comparer<string>, preferences?: UserPreferences) {
if (exportGroup.length === 0) {
return exportGroup;
}

const { exportWithoutClause, namedExports, typeOnlyExports } = getCategorizedExports(exportGroup);

const coalescedExports: ExportDeclaration[] = [];

if (exportWithoutClause) {
Expand All @@ -516,7 +517,7 @@ function coalesceExportsWorker(exportGroup: readonly ExportDeclaration[], compar
const newExportSpecifiers: ExportSpecifier[] = [];
newExportSpecifiers.push(...flatMap(exportGroup, i => i.exportClause && isNamedExports(i.exportClause) ? i.exportClause.elements : emptyArray));

const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer);
const sortedExportSpecifiers = sortSpecifiers(newExportSpecifiers, comparer, preferences);

const exportDecl = exportGroup[0];
coalescedExports.push(
Expand Down Expand Up @@ -583,13 +584,20 @@ function updateImportDeclarationAndClause(
);
}

function sortSpecifiers<T extends ImportOrExportSpecifier>(specifiers: readonly T[], comparer: Comparer<string>) {
return stableSort(specifiers, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer));
function sortSpecifiers<T extends ImportOrExportSpecifier>(specifiers: readonly T[], comparer: Comparer<string>, preferences?: UserPreferences): readonly T[] {
return stableSort(specifiers, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer, preferences));
}

/** @internal */
export function compareImportOrExportSpecifiers<T extends ImportOrExportSpecifier>(s1: T, s2: T, comparer: Comparer<string>): Comparison {
return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text);
export function compareImportOrExportSpecifiers<T extends ImportOrExportSpecifier>(s1: T, s2: T, comparer: Comparer<string>, preferences?: UserPreferences): Comparison {
switch (preferences?.organizeImportsTypeOrder) {
case "first":
return compareBooleans(s2.isTypeOnly, s1.isTypeOnly) || comparer(s1.name.text, s2.name.text);
case "inline":
return comparer(s1.name.text, s2.name.text);
default:
return compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || comparer(s1.name.text, s2.name.text);
}
}

/**
Expand Down Expand Up @@ -721,11 +729,51 @@ class ImportSpecifierSortingCache implements MemoizeCache<[readonly ImportSpecif

/** @internal */
export const detectImportSpecifierSorting = memoizeCached((specifiers: readonly ImportSpecifier[], preferences: UserPreferences): SortKind => {
if (!arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s1.isTypeOnly, s2.isTypeOnly))) {
return SortKind.None;
// If types are not sorted as specified, then imports are assumed to be unsorted.
// If there is no type sorting specification, we default to "last" and move on to case sensitivity detection.
switch (preferences.organizeImportsTypeOrder) {
case "first":
if (!arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s2.isTypeOnly, s1.isTypeOnly))) return SortKind.None;
break;
case "inline":
if (
!arrayIsSorted(specifiers, (s1, s2) => {
const comparer = getStringComparer(/*ignoreCase*/ true);
return comparer(s1.name.text, s2.name.text);
})
) {
return SortKind.None;
}
break;
default:
if (!arrayIsSorted(specifiers, (s1, s2) => compareBooleans(s1.isTypeOnly, s2.isTypeOnly))) return SortKind.None;
break;
}

const collateCaseSensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ false);
const collateCaseInsensitive = getOrganizeImportsComparer(preferences, /*ignoreCase*/ true);

if (preferences.organizeImportsTypeOrder !== "inline") {
const { type: regularImports, regular: typeImports } = groupBy(specifiers, s => s.isTypeOnly ? "type" : "regular");
const regularCaseSensitivity = regularImports?.length
? detectSortCaseSensitivity(regularImports, specifier => specifier.name.text, collateCaseSensitive, collateCaseInsensitive)
: undefined;
const typeCaseSensitivity = typeImports?.length
? detectSortCaseSensitivity(typeImports, specifier => specifier.name.text ?? "", collateCaseSensitive, collateCaseInsensitive)
: undefined;
if (regularCaseSensitivity === undefined) {
return typeCaseSensitivity ?? SortKind.None;
}
if (typeCaseSensitivity === undefined) {
return regularCaseSensitivity;
}
if (regularCaseSensitivity === SortKind.None || typeCaseSensitivity === SortKind.None) {
return SortKind.None;
}
return typeCaseSensitivity & regularCaseSensitivity;
}

// else inline
return detectSortCaseSensitivity(specifiers, specifier => specifier.name.text, collateCaseSensitive, collateCaseInsensitive);
}, new ImportSpecifierSortingCache());

Expand All @@ -736,8 +784,8 @@ export function getImportDeclarationInsertionIndex(sortedImports: readonly AnyIm
}

/** @internal */
export function getImportSpecifierInsertionIndex(sortedImports: readonly ImportSpecifier[], newImport: ImportSpecifier, comparer: Comparer<string>) {
const index = binarySearch(sortedImports, newImport, identity, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer));
export function getImportSpecifierInsertionIndex(sortedImports: readonly ImportSpecifier[], newImport: ImportSpecifier, comparer: Comparer<string>, preferences: UserPreferences) {
const index = binarySearch(sortedImports, newImport, identity, (s1, s2) => compareImportOrExportSpecifiers(s1, s2, comparer, preferences));
return index < 0 ? ~index : index;
}

Expand Down
6 changes: 3 additions & 3 deletions src/testRunner/unittests/services/organizeImports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,10 @@ describe("unittests:: services:: organizeImports", () => {
assertListEqual(actualCoalescedExports, expectedCoalescedExports);
});

it("Sort specifiers - type-only", () => {
it("Sort specifiers - type-only-inline", () => {
const sortedImports = parseImports(`import { type z, y, type x, c, type b, a } from "lib";`);
const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true);
const expectedCoalescedImports = parseImports(`import { a, c, y, type b, type x, type z } from "lib";`);
const actualCoalescedImports = ts.OrganizeImports.coalesceImports(sortedImports, /*ignoreCase*/ true, ts.getSourceFileOfNode(sortedImports[0]), { organizeImportsTypeOrder: "inline" });
const expectedCoalescedImports = parseImports(`import { a, type b, c, type x, y, type z } from "lib";`);
assertListEqual(actualCoalescedImports, expectedCoalescedImports);
});

Expand Down
8 changes: 8 additions & 0 deletions tests/baselines/reference/api/typescript.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2933,6 +2933,13 @@ declare namespace ts {
* Default: `false`
*/
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
/**
* Indicates where named type-only imports should sort. "inline" sorts named imports without regard to if the import is
* type-only.
*
* Default: `last`
*/
readonly organizeImportsTypeOrder?: "last" | "first" | "inline";
/**
* Indicates whether {@link ReferencesResponseItem.lineText} is supported.
*/
Expand Down Expand Up @@ -8784,6 +8791,7 @@ declare namespace ts {
readonly organizeImportsNumericCollation?: boolean;
readonly organizeImportsAccentCollation?: boolean;
readonly organizeImportsCaseFirst?: "upper" | "lower" | false;
readonly organizeImportsTypeOrder?: "first" | "last" | "inline";
readonly excludeLibrarySymbolsInNavTo?: boolean;
}
/** Represents a bigint literal value without requiring bigint support */
Expand Down
46 changes: 46 additions & 0 deletions tests/cases/fourslash/autoImportTypeImport1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/// <reference path="fourslash.ts" />

// @verbatimModuleSyntax: true
// @target: esnext

// @Filename: /foo.ts
//// export const A = 1;
//// export type B = { x: number };
//// export type C = 1;
//// export class D = { y: string };

// @Filename: /test.ts
//// import { A, D, type C } from './foo';
//// const b: B/**/ | C;
//// console.log(A, D);

goTo.marker("");

// importFixes should only place the import in sorted position if the existing imports are sorted as specified,
// otherwise the import should be placed at the end
verify.importFixAtPosition([
`import { A, D, type C, type B } from './foo';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does this one turn out to have C first? The next one doesn't which feels odd.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it's adding type B and it's determined that the types are unsorted (since it specified inline), it adds it on to the end. If the imports were unsorted before, it would always add onto the end, otherwise it might add the import somewhere weird in the middle, since we're not changing the order of the rest of the imports

const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "inline" }
// `type B` is added to the end since the existing imports are not sorted as specified
);

verify.importFixAtPosition([
`import { A, D, type B, type C } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "last" }
// `type B` is added to the sorted position since the existing imports *are* sorted as specified
);

verify.importFixAtPosition([
`import { A, D, type C, type B } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "first" }
// `type B` is added to the end (default behavior) since the existing imports are not sorted as specified
);
43 changes: 43 additions & 0 deletions tests/cases/fourslash/autoImportTypeImport2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/// <reference path="fourslash.ts" />

// @verbatimModuleSyntax: true
// @target: esnext

// @Filename: /foo.ts
//// export const A = 1;
//// export type B = { x: number };
//// export type C = 1;
//// export class D = { y: string };

// @Filename: /test.ts
//// import { A, type C, D } from './foo';
//// const b: B/**/ | C;
//// console.log(A, D);

goTo.marker("");

// importFixes should only place the import in sorted position if the existing imports are sorted as specified,
// otherwise the import should be placed at the end
verify.importFixAtPosition([
`import { A, type B, type C, D } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "inline" }
);

verify.importFixAtPosition([
`import { A, type C, D, type B } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "last" }
);

verify.importFixAtPosition([
`import { A, type C, D, type B } from './foo';
const b: B | C;
console.log(A, D);`],
/*errorCode*/ undefined,
{ organizeImportsTypeOrder: "first" }
);
Loading