Skip to content

generate import statements and replace import types when implementing interface #28165 #33126

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

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,13 @@ namespace ts.codefix {
// so duplicates cannot occur.
const abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember);

createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member));
// Delete existing import statements, since they get overwritten by the fix.
const existingImportDeclarations = sourceFile.statements.filter(isImportDeclaration);
if (existingImportDeclarations.length > 0) {
changeTracker.deleteNodeRange(sourceFile, first(existingImportDeclarations), last(existingImportDeclarations));
}

createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member), importStatement => insertImport(changeTracker, sourceFile, importStatement));
}

function symbolPointsToNonPrivateAndAbstractMember(symbol: Symbol): boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ namespace ts.codefix {
createMissingIndexSignatureDeclaration(implementedType, IndexKind.String);
}

createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member));
// Delete existing import statements, since they get overwritten by the fix.
const existingImportDeclarations = sourceFile.statements.filter(isImportDeclaration);
if (existingImportDeclarations.length > 0) {
changeTracker.deleteNodeRange(sourceFile, first(existingImportDeclarations), last(existingImportDeclarations));
}

createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, member => changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member), importStatement => insertImport(changeTracker, sourceFile, importStatement));

function createMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind): void {
const indexInfoOfKind = checker.getIndexInfoOfType(type, kind);
Expand Down
71 changes: 64 additions & 7 deletions src/services/codefixes/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,42 @@ namespace ts.codefix {
* @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for.
* @returns Empty string iff there are no member insertions.
*/
export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray<Symbol>, context: TypeConstructionContext, preferences: UserPreferences, out: (node: ClassElement) => void): void {
export function createMissingMemberNodes(classDeclaration: ClassLikeDeclaration, possiblyMissingSymbols: ReadonlyArray<Symbol>, context: TypeConstructionContext, preferences: UserPreferences, out: (node: ClassElement) => void, outImportStatements: (statement: Statement) => void): void {
const classMembers = classDeclaration.symbol.members!;
const sourceFile = classDeclaration.getSourceFile();
const importStatements: ImportDeclaration[] = [...sourceFile.statements.filter(isImportDeclaration)];
for (const symbol of possiblyMissingSymbols) {
if (!classMembers.has(symbol.escapedName)) {
addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out);
addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, getQuotePreference(sourceFile, preferences), out, (newImport) => {
addNonDuplicateImport(importStatements, newImport);
});
}
}
importStatements.forEach(outImportStatements);
}

function addNonDuplicateImport(imports: ImportDeclaration[], newImport: ImportDeclaration) {
for (const existingImport of imports) {
if (isStringLiteralLike(existingImport.moduleSpecifier) && isStringLiteralLike(newImport.moduleSpecifier) &&
existingImport.moduleSpecifier.text === newImport.moduleSpecifier.text &&
existingImport.importClause && newImport.importClause) {

if (newImport.importClause.name) {
existingImport.importClause.name = newImport.importClause.name;
return;
}
if (newImport.importClause.namedBindings && existingImport.importClause.namedBindings &&
isNamedImportBindings(newImport.importClause.namedBindings) && isNamedImportBindings(existingImport.importClause.namedBindings)) {

const existingNamedImports = (existingImport.importClause.namedBindings as NamedImports);
const newNamedImports = (newImport.importClause.namedBindings as NamedImports);
const newElements = newNamedImports.elements.filter(e => !existingNamedImports.elements.some(existing => existing.name.text === e.name.text));
existingImport.importClause.namedBindings = createNamedImports([...existingNamedImports.elements, ...newElements]);
return;
}
}
}
imports.push(newImport);
}

function getModuleSpecifierResolverHost(context: TypeConstructionContext): SymbolTracker["moduleResolverHost"] {
Expand Down Expand Up @@ -42,7 +71,7 @@ namespace ts.codefix {
/**
* @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`.
*/
function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, context: TypeConstructionContext, preferences: UserPreferences, out: (node: Node) => void): void {
function addNewNodeForMemberSymbol(symbol: Symbol, enclosingDeclaration: ClassLikeDeclaration, context: TypeConstructionContext, preferences: UserPreferences, quotePreference: QuotePreference, out: (node: Node) => void, outImportStatements: (statement: ImportDeclaration) => void): void {
const declarations = symbol.getDeclarations();
if (!(declarations && declarations.length)) {
return undefined;
Expand All @@ -66,7 +95,7 @@ namespace ts.codefix {
modifiers,
name,
optional ? createToken(SyntaxKind.QuestionToken) : undefined,
typeNode,
replaceInlineImportAndEmitImportStatement(typeNode),
/*initializer*/ undefined));
break;
case SyntaxKind.GetAccessor:
Expand All @@ -83,7 +112,7 @@ namespace ts.codefix {
modifiers,
name,
emptyArray,
typeNode,
replaceInlineImportAndEmitImportStatement(typeNode),
ambient ? undefined : createStubbedMethodBody(preferences)));
}
else {
Expand All @@ -94,7 +123,7 @@ namespace ts.codefix {
/*decorators*/ undefined,
modifiers,
name,
createDummyParameters(1, [parameterName], [typeNode], 1, /*inJs*/ false),
createDummyParameters(1, [parameterName], [replaceInlineImportAndEmitImportStatement(typeNode)], 1, /*inJs*/ false),
ambient ? undefined : createStubbedMethodBody(preferences)));
}
}
Expand Down Expand Up @@ -141,7 +170,35 @@ namespace ts.codefix {

function outputMethod(signature: Signature, modifiers: NodeArray<Modifier> | undefined, name: PropertyName, body?: Block): void {
const method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body);
if (method) out(method);
if (method) out(removeFunctionInlineImports(method));
}

function removeFunctionInlineImports(functionNode: FunctionTypeNode | MethodDeclaration) {
functionNode.parameters.forEach((parameter) => {
const parameterType = parameter.type;
if (parameterType && parameterType.kind === SyntaxKind.ImportType) {
const importNode = parameterType as ImportTypeNode;
parameter.type = replaceInlineImportAndEmitImportStatement(importNode);
}
});
functionNode.type = replaceInlineImportAndEmitImportStatement(functionNode.type);
return functionNode;
}

function replaceInlineImportAndEmitImportStatement(typeNode?: TypeNode) {
if (typeNode && typeNode.kind === SyntaxKind.ImportType) {
const imported = typeNode as ImportTypeNode;
const importedIdentifier = (imported.qualifier as Identifier).text;
const moduleFileName = ((imported.argument as LiteralTypeNode).literal as StringLiteral).text;
const importSpecifier = createImportSpecifier(undefined, createIdentifier((importedIdentifier)));
const importStatement = makeImportIfNecessary(/* defaultImport */ undefined, [importSpecifier], moduleFileName, quotePreference);

if (importStatement) {
outImportStatements(importStatement);
}
return createTypeReferenceNode(importedIdentifier, /* typeArgument */ undefined);
}
return typeNode;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ goTo.file("/C.ts");
verify.codeFix({
description: "Implement interface 'I'",
newFileContent:
`import { I } from "./I";
`import { I, J } from "./I";
export class C implements I {
x: import("./I").J;
m(): import("./I").J {
x: J;
m(): J {
throw new Error("Method not implemented.");
}
}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ verify.codeFix({
description: "Implement interface 'Foo'",
newFileContent: {
"/tests/cases/fourslash/index.ts": `import { Foo } from './interface';
import { Class } from './class';

class X implements Foo {
x: import("./class").Class;
x: Class;
}`
}
});