Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
dc73483
Parse type-only import specifiers
andrewbranch Sep 16, 2021
ad27364
Add type-only export specifiers
andrewbranch Sep 16, 2021
0ba00b9
Update transform and emit
andrewbranch Sep 16, 2021
eb63b02
Update checking
andrewbranch Sep 16, 2021
9b31bd1
Fix elision when combined with importsNotUsedAsValues=preserve
andrewbranch Sep 16, 2021
02d4ff9
Accept baselines
andrewbranch Sep 17, 2021
ac9b14b
Add test
andrewbranch Sep 20, 2021
577868d
WIP auto imports updates
andrewbranch Sep 20, 2021
c41f8ee
First auto-imports test working
andrewbranch Sep 20, 2021
d34544c
More auto-import tests
andrewbranch Sep 20, 2021
76da8c7
Fix auto imports of type-only exports
andrewbranch Sep 21, 2021
487f585
Add test for promoting type-only import
andrewbranch Sep 21, 2021
b6ea3ac
Sort import/export specifiers by type-onlyness
andrewbranch Sep 21, 2021
9a1765e
Update completions for `import { type |`
andrewbranch Sep 22, 2021
9e1878d
Update other completions tests
andrewbranch Sep 22, 2021
f7248e1
Respect organize imports sorting when promoting type-only to regular …
andrewbranch Sep 22, 2021
06063f2
Fix comment mistakes
andrewbranch Sep 24, 2021
4ba367b
Update src/services/codefixes/importFixes.ts
andrewbranch Sep 24, 2021
75a2909
Rearrange some order of assignments in parser
andrewbranch Sep 24, 2021
b55acde
Split huge if statement
andrewbranch Sep 24, 2021
414f38b
Remove redundant check
andrewbranch Sep 24, 2021
3768d0a
Merge branch 'main' into feature/type-only-specifiers
andrewbranch Sep 24, 2021
39e72d8
Update new transformer
andrewbranch Sep 24, 2021
9033c72
Fix import statement completions
andrewbranch Sep 24, 2021
adcb331
Fix type keyword completions good grief
andrewbranch Sep 27, 2021
d64c923
Fix last tests
andrewbranch Sep 27, 2021
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
Prev Previous commit
Next Next commit
Fix import statement completions
  • Loading branch information
andrewbranch committed Sep 24, 2021
commit 9033c72fa65b73c373dad46f21867fbf78efec14
69 changes: 51 additions & 18 deletions src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,7 @@ namespace ts.Completions {
function completionInfoFromData(sourceFile: SourceFile, typeChecker: TypeChecker, compilerOptions: CompilerOptions, log: Log, completionData: CompletionData, preferences: UserPreferences): CompletionInfo | undefined {
const {
symbols,
contextToken,
completionKind,
isInSnippetScope,
isNewIdentifierLocation,
Expand Down Expand Up @@ -423,7 +424,8 @@ namespace ts.Completions {
const uniqueNames = getCompletionEntriesFromSymbols(
symbols,
entries,
/* contextToken */ undefined,
/*replacementToken*/ undefined,
contextToken,
location,
sourceFile,
typeChecker,
Expand Down Expand Up @@ -451,7 +453,8 @@ namespace ts.Completions {
getCompletionEntriesFromSymbols(
symbols,
entries,
/* contextToken */ undefined,
/*replacementToken*/ undefined,
contextToken,
location,
sourceFile,
typeChecker,
Expand Down Expand Up @@ -592,6 +595,7 @@ namespace ts.Completions {
function createCompletionEntry(
symbol: Symbol,
sortText: SortText,
replacementToken: Node | undefined,
contextToken: Node | undefined,
location: Node,
sourceFile: SourceFile,
Expand All @@ -603,13 +607,12 @@ namespace ts.Completions {
propertyAccessToConvert: PropertyAccessExpression | undefined,
isJsxInitializer: IsJsxInitializer | undefined,
importCompletionNode: Node | undefined,
isTypeOnlyImport: boolean,
useSemicolons: boolean,
options: CompilerOptions,
preferences: UserPreferences,
): CompletionEntry | undefined {
let insertText: string | undefined;
let replacementSpan = getReplacementSpanForContextToken(contextToken);
let replacementSpan = getReplacementSpanForContextToken(replacementToken);
let data: CompletionEntryData | undefined;
let isSnippet: true | undefined;
let sourceDisplay;
Expand Down Expand Up @@ -663,7 +666,7 @@ namespace ts.Completions {
if (originIsResolvedExport(origin)) {
sourceDisplay = [textPart(origin.moduleSpecifier)];
if (importCompletionNode) {
({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, isTypeOnlyImport, origin, useSemicolons, options, preferences));
({ insertText, replacementSpan } = getInsertTextAndReplacementSpanForImportCompletion(name, importCompletionNode, contextToken, origin, useSemicolons, options, preferences));
isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined;
}
}
Expand Down Expand Up @@ -748,23 +751,26 @@ namespace ts.Completions {
};
}

function getInsertTextAndReplacementSpanForImportCompletion(name: string, importCompletionNode: Node, isTypeOnly: boolean | undefined, origin: SymbolOriginInfoResolvedExport, useSemicolons: boolean, options: CompilerOptions, preferences: UserPreferences) {
function getInsertTextAndReplacementSpanForImportCompletion(name: string, importCompletionNode: Node, contextToken: Node | undefined, origin: SymbolOriginInfoResolvedExport, useSemicolons: boolean, options: CompilerOptions, preferences: UserPreferences) {
const sourceFile = importCompletionNode.getSourceFile();
const replacementSpan = createTextSpanFromNode(importCompletionNode, sourceFile);
const replacementSpan = createTextSpanFromNode(findAncestor(importCompletionNode, or(isImportDeclaration, isImportEqualsDeclaration))!, sourceFile);
const quotedModuleSpecifier = quote(sourceFile, preferences, origin.moduleSpecifier);
const exportKind =
origin.isDefaultExport ? ExportKind.Default :
origin.exportName === InternalSymbolName.ExportEquals ? ExportKind.ExportEquals :
ExportKind.Named;
const tabStop = preferences.includeCompletionsWithSnippetText ? "$1" : "";
const importKind = codefix.getImportKind(sourceFile, exportKind, options, /*forceImportKeyword*/ true);
const typeOnlyPrefix = isTypeOnly ? ` ${tokenToString(SyntaxKind.TypeKeyword)} ` : " ";
const isTopLevelTypeOnly = tryCast(importCompletionNode, isImportDeclaration)?.importClause?.isTypeOnly || tryCast(importCompletionNode, isImportEqualsDeclaration)?.isTypeOnly;
const isImportSpecifierTypeOnly = couldBeTypeOnlyImportSpecifier(importCompletionNode, contextToken);
const topLevelTypeOnlyText = isTopLevelTypeOnly ? ` ${tokenToString(SyntaxKind.TypeKeyword)} ` : " ";
const importSpecifierTypeOnlyText = isImportSpecifierTypeOnly ? `${tokenToString(SyntaxKind.TypeKeyword)} ` : "";
const suffix = useSemicolons ? ";" : "";
switch (importKind) {
case ImportKind.CommonJS: return { replacementSpan, insertText: `import${typeOnlyPrefix}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` };
case ImportKind.Default: return { replacementSpan, insertText: `import${typeOnlyPrefix}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` };
case ImportKind.Namespace: return { replacementSpan, insertText: `import${typeOnlyPrefix}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` };
case ImportKind.Named: return { replacementSpan, insertText: `import${typeOnlyPrefix}{ ${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` };
case ImportKind.CommonJS: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} = require(${quotedModuleSpecifier})${suffix}` };
case ImportKind.Default: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}${escapeSnippetText(name)}${tabStop} from ${quotedModuleSpecifier}${suffix}` };
case ImportKind.Namespace: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}* as ${escapeSnippetText(name)} from ${quotedModuleSpecifier}${suffix}` };
case ImportKind.Named: return { replacementSpan, insertText: `import${topLevelTypeOnlyText}{ ${importSpecifierTypeOnlyText}${escapeSnippetText(name)}${tabStop} } from ${quotedModuleSpecifier}${suffix}` };
}
}

Expand Down Expand Up @@ -796,6 +802,7 @@ namespace ts.Completions {
export function getCompletionEntriesFromSymbols(
symbols: readonly Symbol[],
entries: Push<CompletionEntry>,
replacementToken: Node | undefined,
contextToken: Node | undefined,
location: Node,
sourceFile: SourceFile,
Expand All @@ -817,7 +824,6 @@ namespace ts.Completions {
const start = timestamp();
const variableDeclaration = getVariableDeclaration(location);
const useSemicolons = probablyUsesSemicolons(sourceFile);
const isTypeOnlyImport = !!importCompletionNode && isTypeOnlyImportOrExportDeclaration(location.parent);
// Tracks unique names.
// Value is set to false for global variables or completions from external module exports, because we can have multiple of those;
// true otherwise. Based on the order we add things we will always see locals first, then globals, then module exports.
Expand All @@ -837,6 +843,7 @@ namespace ts.Completions {
const entry = createCompletionEntry(
symbol,
sortText,
replacementToken,
contextToken,
location,
sourceFile,
Expand All @@ -848,7 +855,6 @@ namespace ts.Completions {
propertyAccessToConvert,
isJsxInitializer,
importCompletionNode,
isTypeOnlyImport,
useSemicolons,
compilerOptions,
preferences
Expand Down Expand Up @@ -1165,6 +1171,7 @@ namespace ts.Completions {
readonly symbolToOriginInfoMap: SymbolOriginInfoMap;
readonly recommendedCompletion: Symbol | undefined;
readonly previousToken: Node | undefined;
readonly contextToken: Node | undefined;
readonly isJsxInitializer: IsJsxInitializer;
readonly insideJsDocTagTypeExpression: boolean;
readonly symbolToSortTextIdMap: SymbolSortTextIdMap;
Expand Down Expand Up @@ -1559,6 +1566,7 @@ namespace ts.Completions {
symbolToOriginInfoMap,
recommendedCompletion,
previousToken,
contextToken,
isJsxInitializer,
insideJsDocTagTypeExpression,
symbolToSortTextIdMap,
Expand Down Expand Up @@ -1816,7 +1824,10 @@ namespace ts.Completions {
function tryGetImportCompletionSymbols(): GlobalsSearch {
if (!importCompletionNode) return GlobalsSearch.Continue;
isNewIdentifierLocation = true;
if (isTypeKeywordTokenOrIdentifier(contextToken)) {
if (!isTypeKeywordTokenOrIdentifier(contextToken) &&
!isImportEqualsDeclaration(importCompletionNode) &&
!tryCast(importCompletionNode, isImportDeclaration)?.importClause?.isTypeOnly
) {
keywordFilters = KeywordCompletionFilters.TypeKeyword;
}
collectAutoImports();
Expand Down Expand Up @@ -1975,10 +1986,18 @@ namespace ts.Completions {
return;
}

// import { type | -> token text should be blank
const isAfterTypeOnlyImportSpecifierModifier = previousToken === contextToken
&& importCompletionNode
&& couldBeTypeOnlyImportSpecifier(importCompletionNode, contextToken);

const lowerCaseTokenText =
isAfterTypeOnlyImportSpecifierModifier ? "" :
previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() :
"";

const moduleSpecifierCache = host.getModuleSpecifierCache?.();
const lowerCaseTokenText = previousToken && isIdentifier(previousToken) ? previousToken.text.toLowerCase() : "";
const exportInfo = getExportInfoMap(sourceFile, host, program, cancellationToken);

const packageJsonAutoImportProvider = host.getPackageJsonAutoImportProvider?.();
const packageJsonFilter = detailsEntryId ? undefined : createPackageJsonImportFilter(sourceFile, preferences, host);
resolvingModuleSpecifiers(
Expand Down Expand Up @@ -3350,8 +3369,11 @@ namespace ts.Completions {
if (isImportEqualsDeclaration(parent)) {
return isModuleSpecifierMissingOrEmpty(parent.moduleReference) ? parent : undefined;
}
if (couldBeTypeOnlyImportSpecifier(parent, contextToken) && canCompleteFromNamedBindings(parent.parent)) {
return parent;
}
if (isNamedImports(parent) || isNamespaceImport(parent)) {
if (isModuleSpecifierMissingOrEmpty(parent.parent.parent.moduleSpecifier) && (isNamespaceImport(parent) || parent.elements.length < 2) && !parent.parent.name) {
if (canCompleteFromNamedBindings(parent)) {
// At `import { ... } |` or `import * as Foo |`, the only possible completion is `from`
return contextToken.kind === SyntaxKind.CloseBraceToken || contextToken.kind === SyntaxKind.Identifier
? SyntaxKind.FromKeyword
Expand All @@ -3371,6 +3393,17 @@ namespace ts.Completions {
}
}

function couldBeTypeOnlyImportSpecifier(importSpecifier: Node, contextToken: Node | undefined): importSpecifier is ImportSpecifier {
return isImportSpecifier(importSpecifier)
&& (importSpecifier.isTypeOnly || contextToken === importSpecifier.name && isTypeKeywordTokenOrIdentifier(contextToken));
}

function canCompleteFromNamedBindings(namedBindings: NamedImportBindings) {
return isModuleSpecifierMissingOrEmpty(namedBindings.parent.parent.moduleSpecifier)
&& (isNamespaceImport(namedBindings) || namedBindings.elements.length < 2)
&& !namedBindings.parent.name;
}

function isModuleSpecifierMissingOrEmpty(specifier: ModuleReference | Expression) {
if (nodeIsMissing(specifier)) return true;
return !tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)?.text;
Expand Down
1 change: 1 addition & 0 deletions src/services/stringCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ namespace ts.Completions.StringCompletions {
completion.symbols,
entries,
contextToken,
contextToken,
sourceFile,
sourceFile,
checker,
Expand Down
26 changes: 26 additions & 0 deletions tests/cases/fourslash/importTypeCompletions8.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/// <reference path="fourslash.ts" />
// @target: esnext

// @filename: /foo.ts
////export interface Foo {}

// @filename: /bar.ts
////[|import { type F/**/ }|]

goTo.file("/bar.ts")
verify.completions({
marker: "",
exact: [{
name: "Foo",
sourceDisplay: "./foo",
source: "./foo",
insertText: "import { type Foo } from \"./foo\";",
replacementSpan: test.ranges()[0]
}],
isNewIdentifierLocation: true,
preferences: {
includeCompletionsForModuleExports: true,
includeCompletionsForImportStatements: true,
includeCompletionsWithInsertText: true
}
});
26 changes: 26 additions & 0 deletions tests/cases/fourslash/importTypeCompletions9.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/// <reference path="fourslash.ts" />
// @target: esnext

// @filename: /foo.ts
////export interface Foo {}

// @filename: /bar.ts
////[|import { type /**/ }|]

goTo.file("/bar.ts")
verify.completions({
marker: "",
exact: [{
name: "Foo",
sourceDisplay: "./foo",
source: "./foo",
insertText: "import { type Foo } from \"./foo\";",
replacementSpan: test.ranges()[0]
}],
isNewIdentifierLocation: true,
preferences: {
includeCompletionsForModuleExports: true,
includeCompletionsForImportStatements: true,
includeCompletionsWithInsertText: true
}
});