From 399a95c9715b0cdf77aa8a23cf9cf557d8585b41 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 23 Nov 2026 16:39:04 -0800 Subject: [PATCH] Allow getSymbol on any Node, overload for Declaration --- packages/typescript/src/api/async/api.ts | 43 +++++---- .../typescript/src/api/proto.generated.ts | 2 +- .../typescript/src/api/sourceFileCache.ts | 8 +- packages/typescript/src/api/sync/api.ts | 95 +++++++++++-------- packages/typescript/src/ast/utils.ts | 2 +- packages/typescript/test/async/api.test.ts | 25 +++++ .../test/sync/api-generators.test.ts | 14 ++- packages/typescript/test/sync/api.test.ts | 25 +++++ tsc/internal/api/session.go | 7 +- .../api/session_createsourcefile_test.go | 7 ++ 10 files changed, 162 insertions(+), 66 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 6042da5009d04..71fe1b4484e76 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -397,16 +397,17 @@ export class API implements FormatDiagnosticsHo } /** - * Looks up a remote declaration's binder symbol. Throws for synthesized or configuration ASTs. + * Looks up a remote node's binder symbol. Throws for synthesized or configuration ASTs. */ - async getSymbol(declaration: Declaration): Promise { - const file = getRemoteSourceFile(declaration); + getSymbol(node: Declaration): Promise; + getSymbol(node: Node): Promise; + async getSymbol(node: Node): Promise { + const file = getRemoteSourceFile(node); if (!file) throw new Error(`Source file not found for declaration`); const record = file.symbolCache as CachedSourceFile | undefined; if (!record) throw new Error(`Cached source file not found for declaration`); - const index = parseNodeHandleFromCompiler(getNodeId(declaration)).index; - const cached = record.symbolsByDeclarationNodeIndex.get(index); - if (cached) return cached; + const index = parseNodeHandleFromCompiler(getNodeId(node)).index; + if (record.symbolsByDeclarationNodeIndex.has(index)) return record.symbolsByDeclarationNodeIndex.get(index); // @sync-only-start // return this.fetchDeclarationSymbol(record, index); // @sync-only-end @@ -425,11 +426,15 @@ export class API implements FormatDiagnosticsHo // @sync-skip-block-end } - private async fetchDeclarationSymbol(record: CachedSourceFile, index: number): Promise { + private async fetchDeclarationSymbol(record: CachedSourceFile, index: number): Promise { const data = await this.client.apiRequest("getSymbolOfDeclaration", { file: record.descriptor, index, }); + if (!data) { + record.symbolsByDeclarationNodeIndex.set(index, undefined); + return undefined; + } validateSymbolResponse(data); const reference = data.reference; if (reference.kind !== SymbolOwnerKind.File) { @@ -972,22 +977,28 @@ function getNodeAPI(node: Node): API | undefined { return api; } -/** Looks up a remote declaration's binder symbol through its API. Throws for non-remote declarations. */ -export async function getSymbol(declaration: Declaration): Promise { - const api = getNodeAPI(declaration); +/** Looks up a remote node's binder symbol through its API. Throws for non-remote nodes. */ +export function getSymbol(node: Declaration): Promise; +export function getSymbol(node: Node): Promise; +export async function getSymbol(node: Node): Promise { + const api = getNodeAPI(node); if (!api) throw new Error("Source file not found for declaration"); - return api.getSymbol(declaration); + return api.getSymbol(node); } // @sync-only-start // export declare namespace getSymbol { -// function gen(declaration: Declaration): Generator; +// function gen(node: Declaration): Generator; +// function gen(node: Node): Generator; // } -// getSymbol.gen = function* (declaration: Declaration): Generator { -// const api = getNodeAPI(declaration); +// function getSymbolGenerator(node: Declaration): Generator; +// function getSymbolGenerator(node: Node): Generator; +// function* getSymbolGenerator(node: Node): Generator { +// const api = getNodeAPI(node); // if (!api) throw new Error("Source file not found for declaration"); -// return yield* api.getSymbol.gen(declaration); -// }; +// return yield* api.getSymbol.gen(node); +// } +// getSymbol.gen = getSymbolGenerator; // @sync-only-end /** An independently retained source file and its disposable remote-lifetime lease. */ diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index a3da313200faa..fa535065ac824 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -45,7 +45,7 @@ export interface APIMethodInfo { releaseSourceFile: APIMethod; retainSourceFile: APIMethod; getCachedSourceFile: APIMethod; - getSymbolOfDeclaration: APIMethod; + getSymbolOfDeclaration: APIMethod; batchRequests: APIMethod; initialize: APIMethod; getDefaultFormatCodeSettings: APIMethod; diff --git a/packages/typescript/src/api/sourceFileCache.ts b/packages/typescript/src/api/sourceFileCache.ts index 73a8360165a38..6673640697e0a 100644 --- a/packages/typescript/src/api/sourceFileCache.ts +++ b/packages/typescript/src/api/sourceFileCache.ts @@ -49,10 +49,10 @@ export interface CachedSourceFile { refs: Set; /** Binder symbols owned by this exact source-file incarnation. */ readonly symbolsById: Map; - /** Successfully resolved declaration symbols. */ - readonly symbolsByDeclarationNodeIndex: Map; - /** In-flight async declaration symbol lookups. */ - readonly declarationSymbolRequests: Map>; + /** Resolved binder symbol lookups, including nodes without symbols. */ + readonly symbolsByDeclarationNodeIndex: Map; + /** In-flight async binder symbol lookups. */ + readonly declarationSymbolRequests: Map>; } /** diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index adb09a2a9b2cc..59381e25a6bdf 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -417,52 +417,57 @@ export class API implements FormatDiagnosticsHo } /** - * Looks up a remote declaration's binder symbol. Throws for synthesized or configuration ASTs. + * Looks up a remote node's binder symbol. Throws for synthesized or configuration ASTs. */ get getSymbol(): { - (declaration: Declaration): Symbol; - gen(declaration: Declaration): Generator; + (node: Declaration): Symbol; + (node: Node): Symbol | undefined; + gen(node: Declaration): Generator; + gen(node: Node): Generator; } { const owner = this; - return cacheGeneratorMethod( - owner, - "getSymbol", - function (declaration: Declaration): Symbol { - const file = getRemoteSourceFile(declaration); - if (!file) throw new Error(`Source file not found for declaration`); - const record = file.symbolCache as CachedSourceFile | undefined; - if (!record) throw new Error(`Cached source file not found for declaration`); - const index = parseNodeHandleFromCompiler(getNodeId(declaration)).index; - const cached = record.symbolsByDeclarationNodeIndex.get(index); - if (cached) return cached; - return owner.fetchDeclarationSymbol(record, index); - }, - function* (declaration: Declaration): Generator { - const file = getRemoteSourceFile(declaration); - if (!file) throw new Error(`Source file not found for declaration`); - const record = file.symbolCache as CachedSourceFile | undefined; - if (!record) throw new Error(`Cached source file not found for declaration`); - const index = parseNodeHandleFromCompiler(getNodeId(declaration)).index; - const cached = record.symbolsByDeclarationNodeIndex.get(index); - if (cached) return cached; - return yield* owner.fetchDeclarationSymbol.gen(record, index); - }, - ); + function getSymbol(node: Declaration): Symbol; + function getSymbol(node: Node): Symbol | undefined; + function getSymbol(node: Node): Symbol | undefined { + const file = getRemoteSourceFile(node); + if (!file) throw new Error(`Source file not found for declaration`); + const record = file.symbolCache as CachedSourceFile | undefined; + if (!record) throw new Error(`Cached source file not found for declaration`); + const index = parseNodeHandleFromCompiler(getNodeId(node)).index; + if (record.symbolsByDeclarationNodeIndex.has(index)) return record.symbolsByDeclarationNodeIndex.get(index); + return owner.fetchDeclarationSymbol(record, index); + } + function gen(node: Declaration): Generator; + function gen(node: Node): Generator; + function* gen(node: Node): Generator { + const file = getRemoteSourceFile(node); + if (!file) throw new Error(`Source file not found for declaration`); + const record = file.symbolCache as CachedSourceFile | undefined; + if (!record) throw new Error(`Cached source file not found for declaration`); + const index = parseNodeHandleFromCompiler(getNodeId(node)).index; + if (record.symbolsByDeclarationNodeIndex.has(index)) return record.symbolsByDeclarationNodeIndex.get(index); + return yield* owner.fetchDeclarationSymbol.gen(record, index); + } + return cacheGeneratorMethod(owner, "getSymbol", getSymbol, gen); } private get fetchDeclarationSymbol(): { - (record: CachedSourceFile, index: number): Symbol; - gen(record: CachedSourceFile, index: number): Generator; + (record: CachedSourceFile, index: number): Symbol | undefined; + gen(record: CachedSourceFile, index: number): Generator; } { const owner = this; return cacheGeneratorMethod( owner, "fetchDeclarationSymbol", - function (record: CachedSourceFile, index: number): Symbol { + function (record: CachedSourceFile, index: number): Symbol | undefined { const data = owner.client.apiRequest("getSymbolOfDeclaration", { file: record.descriptor, index, }); + if (!data) { + record.symbolsByDeclarationNodeIndex.set(index, undefined); + return undefined; + } validateSymbolResponse(data); const reference = data.reference; if (reference.kind !== SymbolOwnerKind.File) { @@ -478,11 +483,15 @@ export class API implements FormatDiagnosticsHo record.symbolsByDeclarationNodeIndex.set(index, symbol); return symbol; }, - function* (record: CachedSourceFile, index: number): Generator { + function* (record: CachedSourceFile, index: number): Generator { const data = yield* apiRequest("getSymbolOfDeclaration", { file: record.descriptor, index, }); + if (!data) { + record.symbolsByDeclarationNodeIndex.set(index, undefined); + return undefined; + } validateSymbolResponse(data); const reference = data.reference; if (reference.kind !== SymbolOwnerKind.File) { @@ -1575,21 +1584,27 @@ function getNodeAPI(node: Node): API | undefined { return api; } -/** Looks up a remote declaration's binder symbol through its API. Throws for non-remote declarations. */ -export function getSymbol(declaration: Declaration): Symbol { - const api = getNodeAPI(declaration); +/** Looks up a remote node's binder symbol through its API. Throws for non-remote nodes. */ +export function getSymbol(node: Declaration): Symbol; +export function getSymbol(node: Node): Symbol | undefined; +export function getSymbol(node: Node): Symbol | undefined { + const api = getNodeAPI(node); if (!api) throw new Error("Source file not found for declaration"); - return api.getSymbol(declaration); + return api.getSymbol(node); } export declare namespace getSymbol { - function gen(declaration: Declaration): Generator; + function gen(node: Declaration): Generator; + function gen(node: Node): Generator; } -getSymbol.gen = function* (declaration: Declaration): Generator { - const api = getNodeAPI(declaration); +function getSymbolGenerator(node: Declaration): Generator; +function getSymbolGenerator(node: Node): Generator; +function* getSymbolGenerator(node: Node): Generator { + const api = getNodeAPI(node); if (!api) throw new Error("Source file not found for declaration"); - return yield* api.getSymbol.gen(declaration); -}; + return yield* api.getSymbol.gen(node); +} +getSymbol.gen = getSymbolGenerator; /** An independently retained source file and its disposable remote-lifetime lease. */ export class RetainedSourceFile { diff --git a/packages/typescript/src/ast/utils.ts b/packages/typescript/src/ast/utils.ts index 59a61a55eb0fd..299a0eb2edc6d 100644 --- a/packages/typescript/src/ast/utils.ts +++ b/packages/typescript/src/ast/utils.ts @@ -122,7 +122,7 @@ export function hasObjectAssignmentInitializer(node: Node): node is ObjectAssign return "objectAssignmentInitializer" in node; } -export function isExternalModule(file: SourceFile): boolean { +export function isExternalModule(file: SourceFile): file is SourceFile & Declaration { return file.externalModuleIndicator !== undefined; } diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 5e7083d2be396..36ecca9a2d94d 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -15,6 +15,7 @@ import { isClassDeclaration, isConstructorDeclaration, isExpressionStatement, + isExternalModule, isFunctionDeclaration, isIdentifier, isImportDeclaration, @@ -920,6 +921,30 @@ describe("API", { concurrency }, () => { assert.equal("getSymbol" in declaration, false); }); + test("getSymbol accepts arbitrary nodes and narrows external module symbols", async () => { + await using api = spawnAPI(); + await using module = await api.createSourceFile("/module.ts", "export function present() {}"); + await using script = await api.createSourceFile("/script.ts", "function present() {}"); + const declaration = cast(module.sourceFile.statements[0], isFunctionDeclaration); + const node: Node = declaration; + const symbol = await getSymbol(declaration); + assert.equal(symbol.name, "present"); + assert.strictEqual(await getSymbol(node), symbol); + assert.strictEqual(await api.getSymbol(node), symbol); + assert.equal((await api.getSymbol(declaration)).name, "present"); + + assert.equal(await getSymbol(declaration.body!), undefined); + assert.equal(await api.getSymbol(declaration.body!), undefined); + assert.equal(await getSymbol(script.sourceFile), undefined); + assert.equal(await api.getSymbol(script.sourceFile), undefined); + + assert.ok(isExternalModule(module.sourceFile)); + const moduleSymbol = await getSymbol(module.sourceFile); + assert.ok(moduleSymbol.name); + assert.equal((await api.getSymbol(module.sourceFile)).name, moduleSymbol.name); + assert.strictEqual(await api.getSymbol(module.sourceFile), moduleSymbol); + }); + test("source files own separate declaration result and request caches", async () => { await using api = spawnAPI(); await using lease = await api.createSourceFile("/symbols.ts", "function present() {}"); diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index a4ff1f34f5c4a..4e584bcfc6c94 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -479,7 +479,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => }); test("looks up binder symbols through standalone and API generators", () => { - using api = spawnAPI(); + using api = spawnAPI({}, { collectTiming: true }); using lease = api.createSourceFile("/symbols.ts", "function present() {}"); const declaration = cast(lease.sourceFile.statements[0], isFunctionDeclaration); const [symbol] = api.batch(getSymbol.gen(declaration)); @@ -487,6 +487,18 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => assert.equal(symbol.name, "present"); const [cached] = api.batch(api.getSymbol.gen(declaration)); assert.strictEqual(cached, symbol); + const node: Node = declaration; + const [fromNode] = api.batch(getSymbol.gen(node)); + assert.strictEqual(fromNode, symbol); + + api.resetTimingInfo(); + const [missing] = api.batch(getSymbol.gen(declaration.body!)); + assert.equal(missing, undefined); + const [cachedMissing] = api.batch(api.getSymbol.gen(declaration.body!)); + assert.equal(cachedMissing, undefined); + assert.equal(api.getSymbol(declaration.body!), undefined); + assert.equal(api.getTimingInfo().totals.requestCount, 1); + const clone = cloneNode(declaration); assert.throws(() => api.batch(getSymbol.gen(clone)), /Source file not found/); assert.throws(() => api.batch(api.getSymbol.gen(clone)), /Source file not found/); diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index d9e994ddae090..551eff12e572f 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -23,6 +23,7 @@ import { isClassDeclaration, isConstructorDeclaration, isExpressionStatement, + isExternalModule, isFunctionDeclaration, isIdentifier, isImportDeclaration, @@ -909,6 +910,30 @@ describe("API", { concurrency }, () => { assert.equal("getSymbol" in declaration, false); }); + test("getSymbol accepts arbitrary nodes and narrows external module symbols", () => { + using api = spawnAPI(); + using module = api.createSourceFile("/module.ts", "export function present() {}"); + using script = api.createSourceFile("/script.ts", "function present() {}"); + const declaration = cast(module.sourceFile.statements[0], isFunctionDeclaration); + const node: Node = declaration; + const symbol = getSymbol(declaration); + assert.equal(symbol.name, "present"); + assert.strictEqual(getSymbol(node), symbol); + assert.strictEqual(api.getSymbol(node), symbol); + assert.equal((api.getSymbol(declaration)).name, "present"); + + assert.equal(getSymbol(declaration.body!), undefined); + assert.equal(api.getSymbol(declaration.body!), undefined); + assert.equal(getSymbol(script.sourceFile), undefined); + assert.equal(api.getSymbol(script.sourceFile), undefined); + + assert.ok(isExternalModule(module.sourceFile)); + const moduleSymbol = getSymbol(module.sourceFile); + assert.ok(moduleSymbol.name); + assert.equal((api.getSymbol(module.sourceFile)).name, moduleSymbol.name); + assert.strictEqual(api.getSymbol(module.sourceFile), moduleSymbol); + }); + test("source files own separate declaration result and request caches", () => { using api = spawnAPI(); using lease = api.createSourceFile("/symbols.ts", "function present() {}"); diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index a5c4612f44c99..f078a1201aa7f 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -2292,6 +2292,7 @@ func (s *Session) handleGetCachedSourceFile(params *GetCachedSourceFileParams) ( return s.encodeSourceFileResponse(lease.SourceFile()) } +// @gen-proto-nullable func (s *Session) handleGetSymbolOfDeclaration(params *GetSymbolOfDeclarationParams) (*SymbolResponse, error) { lease, err := s.acquireCachedSourceFile(params.File) if err != nil { @@ -2304,12 +2305,12 @@ func (s *Session) handleGetSymbolOfDeclaration(params *GetSymbolOfDeclarationPar return nil, fmt.Errorf("%w: declaration node index %d is out of range", ErrClientError, params.Index) } node := table.Nodes[params.Index] - if node == nil || !ast.IsDeclaration(node) { - return nil, fmt.Errorf("%w: node index %d is not a declaration", ErrClientError, params.Index) + if node == nil { + return nil, fmt.Errorf("%w: node index %d is not a node", ErrClientError, params.Index) } symbol := node.Symbol() if symbol == nil { - return nil, fmt.Errorf("%w: declaration node index %d has no binder symbol", ErrClientError, params.Index) + return nil, nil } return newFileSymbolResponse(symbol), nil } diff --git a/tsc/internal/api/session_createsourcefile_test.go b/tsc/internal/api/session_createsourcefile_test.go index 4f16b16734d1b..c097cdd68bc09 100644 --- a/tsc/internal/api/session_createsourcefile_test.go +++ b/tsc/internal/api/session_createsourcefile_test.go @@ -191,6 +191,13 @@ func TestCreateSourceFile(t *testing.T) { assert.Equal(t, present.Name, "present") assert.Equal(t, present.Reference.Kind, SymbolOwnerKindFile) + missing, err := session.handleGetSymbolOfDeclaration(&GetSymbolOfDeclarationParams{ + File: descriptor, + Index: table.GetIndex(sourceFile.Statements.Nodes[0].AsFunctionDeclaration().Body), + }) + assert.NilError(t, err) + assert.Assert(t, missing == nil) + _, err = session.handleGetSymbolOfDeclaration(&GetSymbolOfDeclarationParams{ File: descriptor, Index: 0,