Skip to content

Commit e8fb587

Browse files
author
Andy
authored
organizeImports: Avoid using full FindAllReferences (#22102)
* organizeImports: Avoid using full FindAllReferences * Add parentheses
1 parent 86dca7b commit e8fb587

File tree

2 files changed

+11
-16
lines changed

2 files changed

+11
-16
lines changed

src/services/findAllReferences.ts

+10
Original file line numberDiff line numberDiff line change
@@ -707,6 +707,16 @@ namespace ts.FindAllReferences.Core {
707707
return exposedByParent ? scope.getSourceFile() : scope;
708708
}
709709

710+
/** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
711+
export function isSymbolReferencedInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile) {
712+
const symbol = checker.getSymbolAtLocation(definition);
713+
if (!symbol) return true; // Be lenient with invalid code.
714+
return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(position => {
715+
const token = tryCast(getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), isIdentifier);
716+
return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol;
717+
});
718+
}
719+
710720
function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile): ReadonlyArray<number> {
711721
const positions: number[] = [];
712722

src/services/organizeImports.ts

+1-16
Original file line numberDiff line numberDiff line change
@@ -104,23 +104,8 @@ namespace ts.OrganizeImports {
104104
return usedImports;
105105

106106
function isDeclarationUsed(identifier: Identifier) {
107-
const symbol = typeChecker.getSymbolAtLocation(identifier);
108-
109-
// Be lenient with invalid code.
110-
if (symbol === undefined) {
111-
return true;
112-
}
113-
114107
// The JSX factory symbol is always used.
115-
if (jsxContext && symbol.name === jsxNamespace) {
116-
return true;
117-
}
118-
119-
const entries = FindAllReferences.getReferenceEntriesForNode(identifier.pos, identifier, program, [sourceFile], {
120-
isCancellationRequested: () => false,
121-
throwIfCancellationRequested: () => { /*noop*/ },
122-
}).filter(e => e.type === "node" && e.node.getSourceFile() === sourceFile);
123-
return entries.length > 1;
108+
return jsxContext && (identifier.text === jsxNamespace) || FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
124109
}
125110
}
126111

0 commit comments

Comments
 (0)