organizeImports: Avoid using full FindAllReferences (#22102)

* organizeImports: Avoid using full FindAllReferences

* Add parentheses
This commit is contained in:
Andy 2018-02-22 16:26:37 -08:00 committed by GitHub
parent 86dca7bada
commit e8fb587097
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 16 deletions

View File

@ -707,6 +707,16 @@ namespace ts.FindAllReferences.Core {
return exposedByParent ? scope.getSourceFile() : scope;
}
/** Used as a quick check for whether a symbol is used at all in a file (besides its definition). */
export function isSymbolReferencedInFile(definition: Identifier, checker: TypeChecker, sourceFile: SourceFile) {
const symbol = checker.getSymbolAtLocation(definition);
if (!symbol) return true; // Be lenient with invalid code.
return getPossibleSymbolReferencePositions(sourceFile, symbol.name).some(position => {
const token = tryCast(getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true), isIdentifier);
return token && token !== definition && token.escapedText === definition.escapedText && checker.getSymbolAtLocation(token) === symbol;
});
}
function getPossibleSymbolReferencePositions(sourceFile: SourceFile, symbolName: string, container: Node = sourceFile): ReadonlyArray<number> {
const positions: number[] = [];

View File

@ -104,23 +104,8 @@ namespace ts.OrganizeImports {
return usedImports;
function isDeclarationUsed(identifier: Identifier) {
const symbol = typeChecker.getSymbolAtLocation(identifier);
// Be lenient with invalid code.
if (symbol === undefined) {
return true;
}
// The JSX factory symbol is always used.
if (jsxContext && symbol.name === jsxNamespace) {
return true;
}
const entries = FindAllReferences.getReferenceEntriesForNode(identifier.pos, identifier, program, [sourceFile], {
isCancellationRequested: () => false,
throwIfCancellationRequested: () => { /*noop*/ },
}).filter(e => e.type === "node" && e.node.getSourceFile() === sourceFile);
return entries.length > 1;
return jsxContext && (identifier.text === jsxNamespace) || FindAllReferences.Core.isSymbolReferencedInFile(identifier, typeChecker, sourceFile);
}
}