From c783b4f0b419507d571e9c970cf2279a2b3ac0ac Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:17:04 -0800 Subject: [PATCH 1/8] Expose optional parameter checker query Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 9 +++++++ .../typescript/src/api/proto.generated.ts | 17 +++++++----- packages/typescript/src/api/sync/api.ts | 26 +++++++++++++++++++ packages/typescript/test/async/api.test.ts | 26 +++++++++++++++++++ .../test/sync/api-generators.test.ts | 1 + packages/typescript/test/sync/api.test.ts | 26 +++++++++++++++++++ tsc/internal/api/proto.go | 2 ++ tsc/internal/api/session.go | 19 ++++++++++++++ tsc/internal/checker/services.go | 4 +++ 9 files changed, 123 insertions(+), 7 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 7256e47c0da36..071b143b4e798 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -2331,6 +2331,15 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Whether a parameter may be omitted, including defaults and untyped IIFE parameters. */ + async isOptionalParameter(node: ParameterDeclaration): Promise { + return this.client.apiRequest("isOptionalParameter", { + snapshot: this.snapshotId, + project: this.project.handle, + location: getNodeRequestHandle(node), + }); + } + private snapshotId: number; private project: Project; private objectRegistry: ProjectObjectRegistry; diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index a86805e142df9..8e53b63d7d9ff 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -128,6 +128,7 @@ export interface APIMethodInfo { getParametersOfSignature: APIMethod; getThisParameterOfSignature: APIMethod; getTargetOfSignature: APIMethod; + isOptionalParameter: APIMethod; getContextualType: APIMethod; getContextualTypeForArgument: APIMethod; getAwaitedType: APIMethod; @@ -798,6 +799,13 @@ export interface GetSignaturePropertyParams { objectId: number; } +/** CheckerNodeParams are parameters for checker methods that operate on a node location. */ +export interface CheckerNodeParams { + snapshot: number; + project: number; + location: string; +} + /** GetContextualTypeParams returns the contextual type for a node. */ export interface GetContextualTypeParams { snapshot: number; @@ -864,13 +872,6 @@ export interface GetIntrinsicTypeParams { project: number; } -/** CheckerNodeParams are parameters for checker methods that operate on a node location. */ -export interface CheckerNodeParams { - snapshot: number; - project: number; - location: string; -} - export interface GetPrivateIdentifierPropertyOfTypeParams { snapshot: number; project: number; @@ -1379,6 +1380,7 @@ export interface BatchRequest { | "isArrayType" | "isContextSensitive" | "isImplementationOfOverload" + | "isOptionalParameter" | "isReadonlySymbol" | "isTypeAssignableTo" | "parseCommandLine" @@ -1574,6 +1576,7 @@ export interface BatchResponse { | "isArrayType" | "isContextSensitive" | "isImplementationOfOverload" + | "isOptionalParameter" | "isReadonlySymbol" | "isTypeAssignableTo" | "parseCommandLine" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 5534ffd53e1df..f12462011fe52 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -4215,6 +4215,32 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Whether a parameter may be omitted, including defaults and untyped IIFE parameters. */ + get isOptionalParameter(): { + (node: ParameterDeclaration): boolean; + gen(node: ParameterDeclaration): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "isOptionalParameter", + function (node: ParameterDeclaration): boolean { + return owner.client.apiRequest("isOptionalParameter", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + }); + }, + function* (node: ParameterDeclaration): Generator { + return yield* apiRequest("isOptionalParameter", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + }); + }, + ); + } + private snapshotId: number; private project: Project; private objectRegistry: ProjectObjectRegistry; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 3f303868a73cc..1ec678920f5bd 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -22,6 +22,7 @@ import { isModuleDeclaration, isNamedImports, isObjectLiteralExpression, + isParameterDeclaration, isPrivateIdentifier, isPropertyAccessExpression, isPropertyAssignment, @@ -39,6 +40,7 @@ import { type Node, type NodeArray, NodeFlags, + type ParameterDeclaration, type PathKey, type RootedFilePath, type SourceFile, @@ -169,6 +171,30 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - isOptionalParameter", { concurrency }, () => { + test("distinguishes defaults before required parameters and omitted IIFE arguments", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +function f(required: number, optional?: string) {} +function g(before = 1, required: number, after = 2, ...rest: number[]) {} +(function (provided, omitted, ...rest) {})(1); +`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const parameters: ParameterDeclaration[] = []; + file.forEachChild(function visit(node) { + if (isParameterDeclaration(node)) parameters.push(node); + node.forEachChild(visit); + }); + const optional = await Promise.all(parameters.map(node => project.checker.isOptionalParameter(node))); + assert.deepEqual(optional, [false, true, false, false, true, false, false, true, false]); + }); +}); + describe("API", { concurrency }, () => { test("getCurrentLanguageServerSnapshot is LSP-only", async () => { if (!!false) { diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 32122666a9e48..0b88c104e73e8 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1712,6 +1712,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Checker", "signatureToSignatureDeclaration", checker.signatureToSignatureDeclaration, assertOptionalNodesEquivalent, signature, SyntaxKind.FunctionDeclaration, combineDeclaration), parityCase("Checker", "typeToString", checker.typeToString, assertDeepEquivalent, interfaceType, interfaceDeclaration), parityCase("Checker", "isContextSensitive", checker.isContextSensitive, assertDeepEquivalent, boxDeclaration.initializer!), + parityCase("Checker", "isOptionalParameter", checker.isOptionalParameter, assertDeepEquivalent, combineDeclaration.parameters[1]), parityCase("Checker", "isArrayType", checker.isArrayType, assertDeepEquivalent, arrayType), parityCase("Checker", "isTupleType", checker.isTupleType, assertDeepEquivalent, tupleType), parityCase("Checker", "isTupleTypeTarget", checker.isTupleTypeTarget, assertDeepEquivalent, tupleType), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index c57ca53e905bc..d74ee3b28afbd 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -30,6 +30,7 @@ import { isModuleDeclaration, isNamedImports, isObjectLiteralExpression, + isParameterDeclaration, isPrivateIdentifier, isPropertyAccessExpression, isPropertyAssignment, @@ -47,6 +48,7 @@ import { type Node, type NodeArray, NodeFlags, + type ParameterDeclaration, type PathKey, type RootedFilePath, type SourceFile, @@ -177,6 +179,30 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - isOptionalParameter", { concurrency }, () => { + test("distinguishes defaults before required parameters and omitted IIFE arguments", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +function f(required: number, optional?: string) {} +function g(before = 1, required: number, after = 2, ...rest: number[]) {} +(function (provided, omitted, ...rest) {})(1); +`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const parameters: ParameterDeclaration[] = []; + file.forEachChild(function visit(node) { + if (isParameterDeclaration(node)) parameters.push(node); + node.forEachChild(visit); + }); + const optional = parameters.map(node => project.checker.isOptionalParameter(node)); + assert.deepEqual(optional, [false, true, false, false, true, false, false, true, false]); + }); +}); + describe("API", { concurrency }, () => { test("getCurrentLanguageServerSnapshot is LSP-only", () => { if (!!false) { diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index bd3e25f6d929e..9f0ae7a1f484f 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -167,6 +167,7 @@ const ( MethodGetTargetOfSignature Method = "getTargetOfSignature" // Checker methods + MethodIsOptionalParameter Method = "isOptionalParameter" MethodGetContextualType Method = "getContextualType" MethodGetContextualTypeForArgument Method = "getContextualTypeForArgument" MethodGetAwaitedType Method = "getAwaitedType" @@ -705,6 +706,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetTargetOfSignature: unmarshallerFor[GetSignaturePropertyParams], MethodGetContextualType: unmarshallerFor[GetContextualTypeParams], + MethodIsOptionalParameter: unmarshallerFor[CheckerNodeParams], MethodGetContextualTypeForArgument: unmarshallerFor[GetContextualTypeForArgumentParams], MethodGetAwaitedType: unmarshallerFor[CheckerTypeParams], MethodGetBaseTypeOfLiteralType: unmarshallerFor[GetBaseTypeOfLiteralTypeParams], diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index 7916279532872..3e51bc563b3d3 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1073,6 +1073,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetTargetOfSignature(ctx, parsed.(*GetSignaturePropertyParams)) case string(MethodGetContextualType): return s.handleGetContextualType(ctx, parsed.(*GetContextualTypeParams)) + case string(MethodIsOptionalParameter): + return s.handleIsOptionalParameter(ctx, parsed.(*CheckerNodeParams)) case string(MethodGetContextualTypeForArgument): return s.handleGetContextualTypeForArgument(ctx, parsed.(*GetContextualTypeForArgumentParams)) case string(MethodGetAwaitedType): @@ -3954,6 +3956,23 @@ func (s *Session) handleGetTypeParameterAtPosition(ctx context.Context, params * return setup.sd.newTypeResponse(setup.projectID, setup.checker.GetTypeParameterAtPosition(sig, int(params.Index)), setup.checker), nil } +func (s *Session) handleIsOptionalParameter(ctx context.Context, params *CheckerNodeParams) (bool, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return false, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return false, err + } + if !ast.IsParameterDeclaration(node) { + return false, fmt.Errorf("%w: expected a parameter declaration", ErrInvalidRequest) + } + return setup.checker.IsOptionalParameter(node), nil +} + func (s *Session) handleIsArrayLikeType(ctx context.Context, params *IsArrayLikeTypeParams) (bool, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) if err != nil { diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index ecc28ea2b2b44..c049d3dd6e56b 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -158,6 +158,10 @@ func (c *Checker) ForEachExportAndPropertyOfModule(moduleSymbol *ast.Symbol, cb } } +func (c *Checker) IsOptionalParameter(node *ast.Node) bool { + return c.isOptionalParameter(node) +} + func (c *Checker) IsValidPropertyAccess(node *ast.Node, propertyName string) bool { return c.isValidPropertyAccess(node, propertyName) } From fe32a0e2af09d5e5c5cebb099e75cbae505594e9 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:18:24 -0800 Subject: [PATCH 2/8] Expose property access validity query Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 13 +++++++ .../typescript/src/api/proto.generated.ts | 10 ++++++ packages/typescript/src/api/sync/api.ts | 31 +++++++++++++++++ packages/typescript/test/async/api.test.ts | 34 +++++++++++++++++++ .../test/sync/api-generators.test.ts | 2 ++ packages/typescript/test/sync/api.test.ts | 34 +++++++++++++++++++ tsc/internal/api/proto.go | 9 +++++ tsc/internal/api/session.go | 21 ++++++++++++ 8 files changed, 154 insertions(+) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 071b143b4e798..aadc28a50431b 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -25,12 +25,15 @@ import { type Expression, type FileReference, type Identifier, + type ImportTypeNode, type IndexSignatureDeclaration, ModifierFlags, type NamedTupleMember, type Node, type ParameterDeclaration, type PathKey, + type PropertyAccessExpression, + type QualifiedName, type RootedDirectoryPath, type RootedFilePath, type SourceFile, @@ -2331,6 +2334,16 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Whether the named property exists and is accessible at this access location. */ + async isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): Promise { + return this.client.apiRequest("isValidPropertyAccess", { + snapshot: this.snapshotId, + project: this.project.handle, + location: getNodeRequestHandle(node), + propertyName, + }); + } + /** Whether a parameter may be omitted, including defaults and untyped IIFE parameters. */ async isOptionalParameter(node: ParameterDeclaration): Promise { return this.client.apiRequest("isOptionalParameter", { diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index 8e53b63d7d9ff..b75ecf03b7ace 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -129,6 +129,7 @@ export interface APIMethodInfo { getThisParameterOfSignature: APIMethod; getTargetOfSignature: APIMethod; isOptionalParameter: APIMethod; + isValidPropertyAccess: APIMethod; getContextualType: APIMethod; getContextualTypeForArgument: APIMethod; getAwaitedType: APIMethod; @@ -806,6 +807,13 @@ export interface CheckerNodeParams { location: string; } +export interface IsValidPropertyAccessParams { + snapshot: number; + project: number; + location: string; + propertyName: string; +} + /** GetContextualTypeParams returns the contextual type for a node. */ export interface GetContextualTypeParams { snapshot: number; @@ -1383,6 +1391,7 @@ export interface BatchRequest { | "isOptionalParameter" | "isReadonlySymbol" | "isTypeAssignableTo" + | "isValidPropertyAccess" | "parseCommandLine" | "parseConfigFile" | "parseConfigFileTextToJson" @@ -1579,6 +1588,7 @@ export interface BatchResponse { | "isOptionalParameter" | "isReadonlySymbol" | "isTypeAssignableTo" + | "isValidPropertyAccess" | "parseCommandLine" | "parseConfigFile" | "parseConfigFileTextToJson" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index f12462011fe52..89008fce949a7 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -44,12 +44,15 @@ import { type Expression, type FileReference, type Identifier, + type ImportTypeNode, type IndexSignatureDeclaration, ModifierFlags, type NamedTupleMember, type Node, type ParameterDeclaration, type PathKey, + type PropertyAccessExpression, + type QualifiedName, type RootedDirectoryPath, type RootedFilePath, type SourceFile, @@ -4215,6 +4218,34 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Whether the named property exists and is accessible at this access location. */ + get isValidPropertyAccess(): { + (node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; + gen(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "isValidPropertyAccess", + function (node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean { + return owner.client.apiRequest("isValidPropertyAccess", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + propertyName, + }); + }, + function* (node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): Generator { + return yield* apiRequest("isValidPropertyAccess", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + propertyName, + }); + }, + ); + } + /** Whether a parameter may be omitted, including defaults and untyped IIFE parameters. */ get isOptionalParameter(): { (node: ParameterDeclaration): boolean; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 1ec678920f5bd..485054a51a6f2 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -42,6 +42,7 @@ import { NodeFlags, type ParameterDeclaration, type PathKey, + type PropertyAccessExpression, type RootedFilePath, type SourceFile, SyntaxKind, @@ -171,6 +172,39 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - isValidPropertyAccess", { concurrency }, () => { + test("checks existence and private/protected accessibility without changing the accessed name", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +class C { + public visible = 1; + private secret = 2; + protected inherited = 3; + method() { this.visible; } +} +new C().visible; +declare const anything: any; +anything.unknown; +`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const accesses: PropertyAccessExpression[] = []; + file.forEachChild(function visit(node) { + if (isPropertyAccessExpression(node)) accesses.push(node); + node.forEachChild(visit); + }); + assert.equal(accesses.length, 3); + for (const name of ["visible", "secret", "inherited", "missing"]) { + const results = await Promise.all(accesses.map(node => project.checker.isValidPropertyAccess(node, name))); + assert.deepEqual(results, name === "visible" ? [true, true, true] : name === "missing" ? [false, false, true] : [true, false, true]); + } + }); +}); + describe("Checker - isOptionalParameter", { concurrency }, () => { test("distinguishes defaults before required parameters and omitted IIFE arguments", async () => { await using api = spawnAPI({ diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 0b88c104e73e8..8209ae7354935 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -12,6 +12,7 @@ import { isNamedExports, isNamedImports, isObjectLiteralExpression, + isPropertyAccessExpression, isShorthandPropertyAssignment, isStringLiteral, isTypeAliasDeclaration, @@ -1693,6 +1694,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Checker", "getWidenedType", checker.getWidenedType, assertTypesEquivalent, literalType), parityCase("Checker", "getParameterType", checker.getParameterType, assertTypesEquivalent, signature, 0), parityCase("Checker", "isArrayLikeType", checker.isArrayLikeType, assertDeepEquivalent, arrayType), + parityCase("Checker", "isValidPropertyAccess", checker.isValidPropertyAccess, assertDeepEquivalent, cast(callExpression.expression, isPropertyAccessExpression), "call"), parityCase("Checker", "isTypeAssignableTo", checker.isTypeAssignableTo, assertDeepEquivalent, derivedType, interfaceType), parityCase("Checker", "getShorthandAssignmentValueSymbol", checker.getShorthandAssignmentValueSymbol, assertOptionalSymbolsEquivalent, shorthand), parityCase("Checker", "getTypeOfSymbolAtLocation", checker.getTypeOfSymbolAtLocation, assertTypesEquivalent, derivedSymbol, shorthand), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index d74ee3b28afbd..63128918c3d5e 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -50,6 +50,7 @@ import { NodeFlags, type ParameterDeclaration, type PathKey, + type PropertyAccessExpression, type RootedFilePath, type SourceFile, SyntaxKind, @@ -179,6 +180,39 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - isValidPropertyAccess", { concurrency }, () => { + test("checks existence and private/protected accessibility without changing the accessed name", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +class C { + public visible = 1; + private secret = 2; + protected inherited = 3; + method() { this.visible; } +} +new C().visible; +declare const anything: any; +anything.unknown; +`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const accesses: PropertyAccessExpression[] = []; + file.forEachChild(function visit(node) { + if (isPropertyAccessExpression(node)) accesses.push(node); + node.forEachChild(visit); + }); + assert.equal(accesses.length, 3); + for (const name of ["visible", "secret", "inherited", "missing"]) { + const results = accesses.map(node => project.checker.isValidPropertyAccess(node, name)); + assert.deepEqual(results, name === "visible" ? [true, true, true] : name === "missing" ? [false, false, true] : [true, false, true]); + } + }); +}); + describe("Checker - isOptionalParameter", { concurrency }, () => { test("distinguishes defaults before required parameters and omitted IIFE arguments", () => { using api = spawnAPI({ diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index 9f0ae7a1f484f..f265111fed16c 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -168,6 +168,7 @@ const ( // Checker methods MethodIsOptionalParameter Method = "isOptionalParameter" + MethodIsValidPropertyAccess Method = "isValidPropertyAccess" MethodGetContextualType Method = "getContextualType" MethodGetContextualTypeForArgument Method = "getContextualTypeForArgument" MethodGetAwaitedType Method = "getAwaitedType" @@ -707,6 +708,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetContextualType: unmarshallerFor[GetContextualTypeParams], MethodIsOptionalParameter: unmarshallerFor[CheckerNodeParams], + MethodIsValidPropertyAccess: unmarshallerFor[IsValidPropertyAccessParams], MethodGetContextualTypeForArgument: unmarshallerFor[GetContextualTypeForArgumentParams], MethodGetAwaitedType: unmarshallerFor[CheckerTypeParams], MethodGetBaseTypeOfLiteralType: unmarshallerFor[GetBaseTypeOfLiteralTypeParams], @@ -1955,6 +1957,13 @@ type CheckerNodeParams struct { Location NodeHandle `json:"location"` } +type IsValidPropertyAccessParams struct { + Snapshot SnapshotID `json:"snapshot"` + Project project.Handle `json:"project"` + Location NodeHandle `json:"location"` + PropertyName string `json:"propertyName"` +} + // CheckerSymbolParams are parameters for checker methods that operate on a symbol. type CheckerSymbolParams struct { Snapshot SnapshotID `json:"snapshot"` diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index 3e51bc563b3d3..5d63ccd07791d 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1075,6 +1075,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetContextualType(ctx, parsed.(*GetContextualTypeParams)) case string(MethodIsOptionalParameter): return s.handleIsOptionalParameter(ctx, parsed.(*CheckerNodeParams)) + case string(MethodIsValidPropertyAccess): + return s.handleIsValidPropertyAccess(ctx, parsed.(*IsValidPropertyAccessParams)) case string(MethodGetContextualTypeForArgument): return s.handleGetContextualTypeForArgument(ctx, parsed.(*GetContextualTypeForArgumentParams)) case string(MethodGetAwaitedType): @@ -3973,6 +3975,25 @@ func (s *Session) handleIsOptionalParameter(ctx context.Context, params *Checker return setup.checker.IsOptionalParameter(node), nil } +func (s *Session) handleIsValidPropertyAccess(ctx context.Context, params *IsValidPropertyAccessParams) (bool, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return false, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return false, err + } + switch node.Kind { + case ast.KindPropertyAccessExpression, ast.KindQualifiedName, ast.KindImportType: + return setup.checker.IsValidPropertyAccess(node, params.PropertyName), nil + default: + return false, fmt.Errorf("%w: expected a property access, qualified name, or import type", ErrInvalidRequest) + } +} + func (s *Session) handleIsArrayLikeType(ctx context.Context, params *IsArrayLikeTypeParams) (bool, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) if err != nil { From 3abec2487878d55f620f83c7dfb3f77214785667 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:20:28 -0800 Subject: [PATCH 3/8] Expose parameter property symbol query Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 13 +++++++ .../typescript/src/api/proto.generated.ts | 8 +++++ packages/typescript/src/api/sync/api.ts | 34 +++++++++++++++++++ packages/typescript/test/async/api.test.ts | 27 +++++++++++++++ .../test/sync/api-generators.test.ts | 5 +++ packages/typescript/test/sync/api.test.ts | 27 +++++++++++++++ tsc/internal/api/proto.go | 7 ++++ tsc/internal/api/session.go | 23 +++++++++++++ 8 files changed, 144 insertions(+) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index aadc28a50431b..98b6f0652a380 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -2334,6 +2334,19 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get the distinct constructor parameter and instance property symbols of a parameter property. */ + async getSymbolsOfParameterPropertyDeclaration(node: ParameterDeclaration): Promise<{ parameter: Symbol; property: Symbol; }> { + const data = await this.client.apiRequest("getSymbolsOfParameterPropertyDeclaration", { + snapshot: this.snapshotId, + project: this.project.handle, + location: getNodeRequestHandle(node), + }); + return { + parameter: this.objectRegistry.getOrCreateSymbol(data.parameter), + property: this.objectRegistry.getOrCreateSymbol(data.property), + }; + } + /** Whether the named property exists and is accessible at this access location. */ async isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): Promise { return this.client.apiRequest("isValidPropertyAccess", { diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index b75ecf03b7ace..858611dd0a4db 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -130,6 +130,7 @@ export interface APIMethodInfo { getTargetOfSignature: APIMethod; isOptionalParameter: APIMethod; isValidPropertyAccess: APIMethod; + getSymbolsOfParameterPropertyDeclaration: APIMethod; getContextualType: APIMethod; getContextualTypeForArgument: APIMethod; getAwaitedType: APIMethod; @@ -814,6 +815,11 @@ export interface IsValidPropertyAccessParams { propertyName: string; } +export interface ParameterPropertySymbolsResponse { + parameter: SymbolResponse; + property: SymbolResponse; +} + /** GetContextualTypeParams returns the contextual type for a node. */ export interface GetContextualTypeParams { snapshot: number; @@ -1351,6 +1357,7 @@ export interface BatchRequest { | "getSymbolsAtLocations" | "getSymbolsAtPositions" | "getSymbolsInScope" + | "getSymbolsOfParameterPropertyDeclaration" | "getSymbolsOfSourceFiles" | "getSyntacticDiagnostics" | "getTargetOfSignature" @@ -1548,6 +1555,7 @@ export interface BatchResponse { | "getSymbolsAtLocations" | "getSymbolsAtPositions" | "getSymbolsInScope" + | "getSymbolsOfParameterPropertyDeclaration" | "getSymbolsOfSourceFiles" | "getSyntacticDiagnostics" | "getTargetOfSignature" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 89008fce949a7..5cdbb4da53314 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -4218,6 +4218,40 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get the distinct constructor parameter and instance property symbols of a parameter property. */ + get getSymbolsOfParameterPropertyDeclaration(): { + (node: ParameterDeclaration): { parameter: Symbol; property: Symbol; }; + gen(node: ParameterDeclaration): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "getSymbolsOfParameterPropertyDeclaration", + function (node: ParameterDeclaration): { parameter: Symbol; property: Symbol; } { + const data = owner.client.apiRequest("getSymbolsOfParameterPropertyDeclaration", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + }); + return { + parameter: owner.objectRegistry.getOrCreateSymbol(data.parameter), + property: owner.objectRegistry.getOrCreateSymbol(data.property), + }; + }, + function* (node: ParameterDeclaration): Generator { + const data = yield* apiRequest("getSymbolsOfParameterPropertyDeclaration", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + }); + return { + parameter: owner.objectRegistry.getOrCreateSymbol(data.parameter), + property: owner.objectRegistry.getOrCreateSymbol(data.property), + }; + }, + ); + } + /** Whether the named property exists and is accessible at this access location. */ get isValidPropertyAccess(): { (node: PropertyAccessExpression | QualifiedName | ImportTypeNode, propertyName: string): boolean; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 485054a51a6f2..e2f5c38928fc6 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -11,6 +11,7 @@ import { InternalSymbolName, isCallExpression, isClassDeclaration, + isConstructorDeclaration, isExpressionStatement, isFunctionDeclaration, isIdentifier, @@ -172,6 +173,32 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getSymbolsOfParameterPropertyDeclaration", { concurrency }, () => { + test("returns distinct parameter and property symbols with canonical identities", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": `class C { constructor(public __value: string) { __value; this.__value; } }`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const cls = file.statements[0]; + assert.ok(isClassDeclaration(cls)); + const ctor = cls.members[0]; + assert.ok(isConstructorDeclaration(ctor)); + const node = ctor.parameters[0]; + const result = await project.checker.getSymbolsOfParameterPropertyDeclaration(node); + assert.notStrictEqual(result.parameter, result.property); + assert.equal(result.parameter.name, "__value"); + assert.equal(result.property.name, "__value"); + assert.strictEqual(result.parameter, await project.checker.getSymbolAtPosition("/index.ts", file.text.indexOf("__value;"))); + assert.strictEqual(result.property, await project.checker.getSymbolAtLocation(node.name)); + const type = await project.checker.getDeclaredTypeOfSymbol(await project.checker.getSymbolOfDeclaration(cls)); + assert.strictEqual(result.property, await type.getProperty("__value")); + }); +}); + describe("Checker - isValidPropertyAccess", { concurrency }, () => { test("checks existence and private/protected accessibility without changing the accessed name", async () => { await using api = spawnAPI({ diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 8209ae7354935..d9b9435fae08c 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -3,6 +3,7 @@ import { type Identifier, isCallExpression, isClassDeclaration, + isConstructorDeclaration, isEnumDeclaration, isExportDeclaration, isFunctionDeclaration, @@ -113,6 +114,7 @@ export type Union = Derived | string; export enum Choice { First = 1, Second = "second" } export class Unimported { value = "extra"; } export type Mapped = { [K in keyof T as \`get\${Capitalize}\`]: T[K] }; +export class ParameterProperty { constructor(public parameter: string) {} } `, "/src/index.ts": ` /// @@ -1492,6 +1494,8 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => const unionAlias = cast(modelsFile.statements[9], isTypeAliasDeclaration); const enumDeclaration = cast(modelsFile.statements[10], isEnumDeclaration); const mappedAlias = cast(modelsFile.statements[12], isTypeAliasDeclaration); + const parameterPropertyClass = cast(modelsFile.statements[13], isClassDeclaration); + const parameterProperty = cast(parameterPropertyClass.members[0], isConstructorDeclaration).parameters[0]; const importedDerivedSymbol = checker.getSymbolAtLocation(importedDerived)!; const combineSymbol = checker.getSymbolAtLocation(combineDeclaration.name!)!; @@ -1663,6 +1667,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Checker", "getSymbolOfNode", checker.getSymbolOfNode, assertOptionalSymbolsEquivalent, interfaceDeclaration), parityCase("Checker", "getSymbolOfNode", checker.getSymbolOfNode, assertOptionalSymbolsEquivalent, interfaceDeclaration.name), parityCase("Checker", "getSymbolOfDeclaration", checker.getSymbolOfDeclaration, assertSymbolsEquivalent, interfaceDeclaration), + parityCase("Checker", "getSymbolsOfParameterPropertyDeclaration", checker.getSymbolsOfParameterPropertyDeclaration, assertDeepEquivalent, parameterProperty), parityCase("Checker", "getParentOfSymbol", checker.getParentOfSymbol, assertOptionalSymbolsEquivalent, unimportedSymbol), parityCase("Checker", "getSymbolAtLocation", selectGeneratorMethod<[node: Node], Symbol | undefined>(checker.getSymbolAtLocation), assertOptionalSymbolsEquivalent, importedDerived), parityCase("Checker", "getSymbolAtLocation", checker.getSymbolAtLocation, assertOptionalSymbolArraysEquivalent, [importedDerived, combineDeclaration.name!]), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 63128918c3d5e..347b65833d345 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -19,6 +19,7 @@ import { InternalSymbolName, isCallExpression, isClassDeclaration, + isConstructorDeclaration, isExpressionStatement, isFunctionDeclaration, isIdentifier, @@ -180,6 +181,32 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getSymbolsOfParameterPropertyDeclaration", { concurrency }, () => { + test("returns distinct parameter and property symbols with canonical identities", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": `class C { constructor(public __value: string) { __value; this.__value; } }`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const cls = file.statements[0]; + assert.ok(isClassDeclaration(cls)); + const ctor = cls.members[0]; + assert.ok(isConstructorDeclaration(ctor)); + const node = ctor.parameters[0]; + const result = project.checker.getSymbolsOfParameterPropertyDeclaration(node); + assert.notStrictEqual(result.parameter, result.property); + assert.equal(result.parameter.name, "__value"); + assert.equal(result.property.name, "__value"); + assert.strictEqual(result.parameter, project.checker.getSymbolAtPosition("/index.ts", file.text.indexOf("__value;"))); + assert.strictEqual(result.property, project.checker.getSymbolAtLocation(node.name)); + const type = project.checker.getDeclaredTypeOfSymbol(project.checker.getSymbolOfDeclaration(cls)); + assert.strictEqual(result.property, type.getProperty("__value")); + }); +}); + describe("Checker - isValidPropertyAccess", { concurrency }, () => { test("checks existence and private/protected accessibility without changing the accessed name", () => { using api = spawnAPI({ diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index f265111fed16c..0a6e1e90ac9d7 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -169,6 +169,7 @@ const ( // Checker methods MethodIsOptionalParameter Method = "isOptionalParameter" MethodIsValidPropertyAccess Method = "isValidPropertyAccess" + MethodGetSymbolsOfParameterPropertyDeclaration Method = "getSymbolsOfParameterPropertyDeclaration" MethodGetContextualType Method = "getContextualType" MethodGetContextualTypeForArgument Method = "getContextualTypeForArgument" MethodGetAwaitedType Method = "getAwaitedType" @@ -709,6 +710,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetContextualType: unmarshallerFor[GetContextualTypeParams], MethodIsOptionalParameter: unmarshallerFor[CheckerNodeParams], MethodIsValidPropertyAccess: unmarshallerFor[IsValidPropertyAccessParams], + MethodGetSymbolsOfParameterPropertyDeclaration: unmarshallerFor[CheckerNodeParams], MethodGetContextualTypeForArgument: unmarshallerFor[GetContextualTypeForArgumentParams], MethodGetAwaitedType: unmarshallerFor[CheckerTypeParams], MethodGetBaseTypeOfLiteralType: unmarshallerFor[GetBaseTypeOfLiteralTypeParams], @@ -1964,6 +1966,11 @@ type IsValidPropertyAccessParams struct { PropertyName string `json:"propertyName"` } +type ParameterPropertySymbolsResponse struct { + Parameter *SymbolResponse `json:"parameter" nonnil:"true"` + Property *SymbolResponse `json:"property" nonnil:"true"` +} + // CheckerSymbolParams are parameters for checker methods that operate on a symbol. type CheckerSymbolParams struct { Snapshot SnapshotID `json:"snapshot"` diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index 5d63ccd07791d..efb8a8e458aae 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1077,6 +1077,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleIsOptionalParameter(ctx, parsed.(*CheckerNodeParams)) case string(MethodIsValidPropertyAccess): return s.handleIsValidPropertyAccess(ctx, parsed.(*IsValidPropertyAccessParams)) + case string(MethodGetSymbolsOfParameterPropertyDeclaration): + return s.handleGetSymbolsOfParameterPropertyDeclaration(ctx, parsed.(*CheckerNodeParams)) case string(MethodGetContextualTypeForArgument): return s.handleGetContextualTypeForArgument(ctx, parsed.(*GetContextualTypeForArgumentParams)) case string(MethodGetAwaitedType): @@ -3975,6 +3977,27 @@ func (s *Session) handleIsOptionalParameter(ctx context.Context, params *Checker return setup.checker.IsOptionalParameter(node), nil } +func (s *Session) handleGetSymbolsOfParameterPropertyDeclaration(ctx context.Context, params *CheckerNodeParams) (*ParameterPropertySymbolsResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return nil, err + } + if !ast.IsParameterPropertyDeclaration(node, node.Parent) || !ast.IsIdentifier(node.Name()) { + return nil, fmt.Errorf("%w: expected a parameter property with an identifier name", ErrInvalidRequest) + } + parameter, property := setup.checker.GetSymbolsOfParameterPropertyDeclaration(node, node.Name().Text()) + return &ParameterPropertySymbolsResponse{ + Parameter: setup.newSymbolResponse(parameter), + Property: setup.newSymbolResponse(property), + }, nil +} + func (s *Session) handleIsValidPropertyAccess(ctx context.Context, params *IsValidPropertyAccessParams) (bool, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) if err != nil { From 753502cdbd7e8ba0d73717d9994f558f4a628b4d Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:25:17 -0800 Subject: [PATCH 4/8] Expose assignment pattern type query Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 12 +++++ .../typescript/src/api/proto.generated.ts | 3 ++ packages/typescript/src/api/sync/api.ts | 30 ++++++++++++ packages/typescript/test/async/api.test.ts | 49 +++++++++++++++++++ .../test/sync/api-generators.test.ts | 9 ++++ packages/typescript/test/sync/api.test.ts | 49 +++++++++++++++++++ tsc/internal/api/proto.go | 2 + tsc/internal/api/session.go | 43 ++++++++++++++++ tsc/internal/checker/services.go | 4 ++ 9 files changed, 201 insertions(+) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 98b6f0652a380..6f7bab02c8242 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -20,6 +20,7 @@ import { TypeFormatFlags } from "../../../enums/typeFormatFlags.js"; import { TypePredicateKind } from "../../../enums/typePredicateKind.js"; import { type __String, + type ArrayLiteralExpression, type CallLikeExpression, type Declaration, type Expression, @@ -30,6 +31,7 @@ import { ModifierFlags, type NamedTupleMember, type Node, + type ObjectLiteralExpression, type ParameterDeclaration, type PathKey, type PropertyAccessExpression, @@ -2334,6 +2336,16 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get the source type of an object/array assignment pattern, including nested patterns and for-of initializers. */ + async getTypeOfAssignmentPattern(node: ObjectLiteralExpression | ArrayLiteralExpression): Promise { + const data = await this.client.apiRequest("getTypeOfAssignmentPattern", { + snapshot: this.snapshotId, + project: this.project.handle, + location: getNodeRequestHandle(node), + }); + return data ? this.objectRegistry.getOrCreateType(data) : undefined; + } + /** Get the distinct constructor parameter and instance property symbols of a parameter property. */ async getSymbolsOfParameterPropertyDeclaration(node: ParameterDeclaration): Promise<{ parameter: Symbol; property: Symbol; }> { const data = await this.client.apiRequest("getSymbolsOfParameterPropertyDeclaration", { diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index 858611dd0a4db..7c97f087b4184 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -129,6 +129,7 @@ export interface APIMethodInfo { getThisParameterOfSignature: APIMethod; getTargetOfSignature: APIMethod; isOptionalParameter: APIMethod; + getTypeOfAssignmentPattern: APIMethod; isValidPropertyAccess: APIMethod; getSymbolsOfParameterPropertyDeclaration: APIMethod; getContextualType: APIMethod; @@ -1373,6 +1374,7 @@ export interface BatchRequest { | "getTypeAtLocations" | "getTypeAtPosition" | "getTypeFromTypeNode" + | "getTypeOfAssignmentPattern" | "getTypeOfPropertyOfType" | "getTypeOfSymbol" | "getTypeOfSymbolAtLocation" @@ -1571,6 +1573,7 @@ export interface BatchResponse { | "getTypeAtLocations" | "getTypeAtPosition" | "getTypeFromTypeNode" + | "getTypeOfAssignmentPattern" | "getTypeOfPropertyOfType" | "getTypeOfSymbol" | "getTypeOfSymbolAtLocation" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 5cdbb4da53314..b7c6e0fe11b05 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -39,6 +39,7 @@ import { TypeFormatFlags } from "../../../enums/typeFormatFlags.js"; import { TypePredicateKind } from "../../../enums/typePredicateKind.js"; import { type __String, + type ArrayLiteralExpression, type CallLikeExpression, type Declaration, type Expression, @@ -49,6 +50,7 @@ import { ModifierFlags, type NamedTupleMember, type Node, + type ObjectLiteralExpression, type ParameterDeclaration, type PathKey, type PropertyAccessExpression, @@ -4218,6 +4220,34 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get the source type of an object/array assignment pattern, including nested patterns and for-of initializers. */ + get getTypeOfAssignmentPattern(): { + (node: ObjectLiteralExpression | ArrayLiteralExpression): Type | undefined; + gen(node: ObjectLiteralExpression | ArrayLiteralExpression): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "getTypeOfAssignmentPattern", + function (node: ObjectLiteralExpression | ArrayLiteralExpression): Type | undefined { + const data = owner.client.apiRequest("getTypeOfAssignmentPattern", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + }); + return data ? owner.objectRegistry.getOrCreateType(data) : undefined; + }, + function* (node: ObjectLiteralExpression | ArrayLiteralExpression): Generator { + const data = yield* apiRequest("getTypeOfAssignmentPattern", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + }); + return data ? owner.objectRegistry.getOrCreateType(data) : undefined; + }, + ); + } + /** Get the distinct constructor parameter and instance property symbols of a parameter property. */ get getSymbolsOfParameterPropertyDeclaration(): { (node: ParameterDeclaration): { parameter: Symbol; property: Symbol; }; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index e2f5c38928fc6..2a7e05dc830ad 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -1,5 +1,6 @@ import { type __String, + type ArrayLiteralExpression, cast, escapeLeadingUnderscores, type Expression, @@ -9,6 +10,7 @@ import { getTextOfJSDocComment, type Identifier, InternalSymbolName, + isArrayLiteralExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -41,6 +43,7 @@ import { type Node, type NodeArray, NodeFlags, + type ObjectLiteralExpression, type ParameterDeclaration, type PathKey, type PropertyAccessExpression, @@ -173,6 +176,52 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getTypeOfAssignmentPattern", { concurrency }, () => { + test("rejects object literals that are not assignment patterns", async () => { + await using api = spawnAPI({ "/tsconfig.json": "{}", "/index.ts": "const value = {};" }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const statement = file.statements[0]; + assert.ok(isVariableStatement(statement)); + const node = statement.declarationList.declarations[0].initializer; + assert.ok(node && isObjectLiteralExpression(node)); + await assert.rejects(project.checker.getTypeOfAssignmentPattern(node), /expected an object or array assignment pattern/); // @sync: assert.throws(() => project.checker.getTypeOfAssignmentPattern(node), /expected an object or array assignment pattern/); + }); + + test("gets source types of object, nested object, array, and for-of patterns", async () => { + await using api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/index.ts": ` +declare const source: { nested: { value: number } }; +declare const tuple: [string, { value: number }]; +declare const items: { value: number }[]; +let value: number, text: string; +({ nested: { value } } = source); +[text, { value }] = tuple; +for ({ value } of items) {} +`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const types: string[] = []; + const patterns: (ObjectLiteralExpression | ArrayLiteralExpression)[] = []; + file.forEachChild(function visit(node) { + if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) patterns.push(node); + node.forEachChild(visit); + }); + for (const pattern of patterns) { + const type = await project.checker.getTypeOfAssignmentPattern(pattern); + assert.ok(type); + types.push(await project.checker.typeToString(type)); + } + assert.deepEqual(types, ["{ nested: { value: number; }; }", "{ value: number; }", "[string, { value: number; }]", "{ value: number; }", "{ value: number; }"]); + }); +}); + describe("Checker - getSymbolsOfParameterPropertyDeclaration", { concurrency }, () => { test("returns distinct parameter and property symbols with canonical identities", async () => { await using api = spawnAPI({ diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index d9b9435fae08c..03ac48d4eaf2c 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1,11 +1,13 @@ import { cast, type Identifier, + isBinaryExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, isEnumDeclaration, isExportDeclaration, + isExpressionStatement, isFunctionDeclaration, isIdentifier, isImportDeclaration, @@ -13,6 +15,7 @@ import { isNamedExports, isNamedImports, isObjectLiteralExpression, + isParenthesizedExpression, isPropertyAccessExpression, isShorthandPropertyAssignment, isStringLiteral, @@ -137,6 +140,8 @@ export const badCall = derived(); export function getArguments() { return arguments; } import { absent } from "./absent.js"; export const missingValue = absent; +let assigned: Base; +({ value: assigned } = box); `, "/node_modules/@types/parity/index.d.ts": `export {};`, "/src/syntax.ts": `export const broken: = 1;`, @@ -1483,6 +1488,9 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => isVariableDeclaration, ); const callExpression = cast(calledDeclaration.initializer, isCallExpression); + const assignmentStatement = cast(indexFile.statements.find(isExpressionStatement), isExpressionStatement); + const assignment = cast(cast(assignmentStatement.expression, isParenthesizedExpression).expression, isBinaryExpression); + const assignmentPattern = cast(assignment.left, isObjectLiteralExpression); const interfaceDeclaration = cast(modelsFile.statements[0], isInterfaceDeclaration); const derivedClassDeclaration = cast(modelsFile.statements[2], isClassDeclaration); const boxedAlias = cast(modelsFile.statements[3], isTypeAliasDeclaration); @@ -1702,6 +1710,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Checker", "isValidPropertyAccess", checker.isValidPropertyAccess, assertDeepEquivalent, cast(callExpression.expression, isPropertyAccessExpression), "call"), parityCase("Checker", "isTypeAssignableTo", checker.isTypeAssignableTo, assertDeepEquivalent, derivedType, interfaceType), parityCase("Checker", "getShorthandAssignmentValueSymbol", checker.getShorthandAssignmentValueSymbol, assertOptionalSymbolsEquivalent, shorthand), + parityCase("Checker", "getTypeOfAssignmentPattern", checker.getTypeOfAssignmentPattern, assertOptionalTypesEquivalent, assignmentPattern), parityCase("Checker", "getTypeOfSymbolAtLocation", checker.getTypeOfSymbolAtLocation, assertTypesEquivalent, derivedSymbol, shorthand), parityCase("Checker", "getAnyType", checker.getAnyType, assertTypesEquivalent), parityCase("Checker", "getStringType", checker.getStringType, assertTypesEquivalent), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 347b65833d345..57499534df475 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -8,6 +8,7 @@ // import { type __String, + type ArrayLiteralExpression, cast, escapeLeadingUnderscores, type Expression, @@ -17,6 +18,7 @@ import { getTextOfJSDocComment, type Identifier, InternalSymbolName, + isArrayLiteralExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -49,6 +51,7 @@ import { type Node, type NodeArray, NodeFlags, + type ObjectLiteralExpression, type ParameterDeclaration, type PathKey, type PropertyAccessExpression, @@ -181,6 +184,52 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getTypeOfAssignmentPattern", { concurrency }, () => { + test("rejects object literals that are not assignment patterns", () => { + using api = spawnAPI({ "/tsconfig.json": "{}", "/index.ts": "const value = {};" }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const statement = file.statements[0]; + assert.ok(isVariableStatement(statement)); + const node = statement.declarationList.declarations[0].initializer; + assert.ok(node && isObjectLiteralExpression(node)); + assert.throws(() => project.checker.getTypeOfAssignmentPattern(node), /expected an object or array assignment pattern/); + }); + + test("gets source types of object, nested object, array, and for-of patterns", () => { + using api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/index.ts": ` +declare const source: { nested: { value: number } }; +declare const tuple: [string, { value: number }]; +declare const items: { value: number }[]; +let value: number, text: string; +({ nested: { value } } = source); +[text, { value }] = tuple; +for ({ value } of items) {} +`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const types: string[] = []; + const patterns: (ObjectLiteralExpression | ArrayLiteralExpression)[] = []; + file.forEachChild(function visit(node) { + if (isObjectLiteralExpression(node) || isArrayLiteralExpression(node)) patterns.push(node); + node.forEachChild(visit); + }); + for (const pattern of patterns) { + const type = project.checker.getTypeOfAssignmentPattern(pattern); + assert.ok(type); + types.push(project.checker.typeToString(type)); + } + assert.deepEqual(types, ["{ nested: { value: number; }; }", "{ value: number; }", "[string, { value: number; }]", "{ value: number; }", "{ value: number; }"]); + }); +}); + describe("Checker - getSymbolsOfParameterPropertyDeclaration", { concurrency }, () => { test("returns distinct parameter and property symbols with canonical identities", () => { using api = spawnAPI({ diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index 0a6e1e90ac9d7..b17ba69e9423a 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -168,6 +168,7 @@ const ( // Checker methods MethodIsOptionalParameter Method = "isOptionalParameter" + MethodGetTypeOfAssignmentPattern Method = "getTypeOfAssignmentPattern" MethodIsValidPropertyAccess Method = "isValidPropertyAccess" MethodGetSymbolsOfParameterPropertyDeclaration Method = "getSymbolsOfParameterPropertyDeclaration" MethodGetContextualType Method = "getContextualType" @@ -709,6 +710,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetContextualType: unmarshallerFor[GetContextualTypeParams], MethodIsOptionalParameter: unmarshallerFor[CheckerNodeParams], + MethodGetTypeOfAssignmentPattern: unmarshallerFor[CheckerNodeParams], MethodIsValidPropertyAccess: unmarshallerFor[IsValidPropertyAccessParams], MethodGetSymbolsOfParameterPropertyDeclaration: unmarshallerFor[CheckerNodeParams], MethodGetContextualTypeForArgument: unmarshallerFor[GetContextualTypeForArgumentParams], diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index efb8a8e458aae..9e05cf484aad5 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1075,6 +1075,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetContextualType(ctx, parsed.(*GetContextualTypeParams)) case string(MethodIsOptionalParameter): return s.handleIsOptionalParameter(ctx, parsed.(*CheckerNodeParams)) + case string(MethodGetTypeOfAssignmentPattern): + return s.handleGetTypeOfAssignmentPattern(ctx, parsed.(*CheckerNodeParams)) case string(MethodIsValidPropertyAccess): return s.handleIsValidPropertyAccess(ctx, parsed.(*IsValidPropertyAccessParams)) case string(MethodGetSymbolsOfParameterPropertyDeclaration): @@ -3977,6 +3979,47 @@ func (s *Session) handleIsOptionalParameter(ctx context.Context, params *Checker return setup.checker.IsOptionalParameter(node), nil } +// @gen-proto-nullable +func (s *Session) handleGetTypeOfAssignmentPattern(ctx context.Context, params *CheckerNodeParams) (*TypeResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return nil, err + } + if !isSupportedAssignmentPattern(node) { + return nil, fmt.Errorf("%w: expected an object or array assignment pattern in an assignment or for-of initializer", ErrInvalidRequest) + } + t := setup.checker.GetTypeOfAssignmentPattern(node) + if t == nil { + return nil, nil + } + return setup.sd.newTypeResponse(setup.projectID, t, setup.checker), nil +} + +func isSupportedAssignmentPattern(node *ast.Node) bool { + if !ast.IsAssignmentPattern(node) { + return false + } + parent := node.Parent + switch parent.Kind { + case ast.KindBinaryExpression: + return parent.AsBinaryExpression().OperatorToken.Kind == ast.KindEqualsToken && parent.AsBinaryExpression().Left == node + case ast.KindForOfStatement: + return parent.Initializer() == node + case ast.KindPropertyAssignment: + return parent.Initializer() == node && isSupportedAssignmentPattern(parent.Parent) + case ast.KindArrayLiteralExpression: + return isSupportedAssignmentPattern(parent) + default: + return false + } +} + func (s *Session) handleGetSymbolsOfParameterPropertyDeclaration(ctx context.Context, params *CheckerNodeParams) (*ParameterPropertySymbolsResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) if err != nil { diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index c049d3dd6e56b..3831bd15eeed6 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -1032,6 +1032,10 @@ func (c *Checker) GetPropertySymbolOfDestructuringAssignment(location *ast.Node) // [ a ] from // // [a] = [ some array ...] +func (c *Checker) GetTypeOfAssignmentPattern(expr *ast.Node) *Type { + return c.getTypeOfAssignmentPattern(expr) +} + func (c *Checker) getTypeOfAssignmentPattern(expr *ast.Node) *Type { // If this is from "for of" // for ( { a } of elems) { From 2c22dc633ad1a86ab5ff33d46b8ba123e54ee627 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:28:31 -0800 Subject: [PATCH 5/8] Expose resolved signature type arguments Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 14 +++++++ .../typescript/src/api/proto.generated.ts | 3 ++ packages/typescript/src/api/sync/api.ts | 42 +++++++++++++++++++ packages/typescript/test/async/api.test.ts | 33 +++++++++++++++ .../test/sync/api-generators.test.ts | 2 + packages/typescript/test/sync/api.test.ts | 33 +++++++++++++++ tsc/internal/api/proto.go | 18 ++++---- tsc/internal/api/session.go | 21 ++++++++++ tsc/internal/checker/services.go | 8 ++++ 9 files changed, 166 insertions(+), 8 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 6f7bab02c8242..521c344190f09 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -2336,6 +2336,11 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get inferred or explicit signature type arguments; empty when the signature has no instantiation. */ + async getTypeArgumentsForResolvedSignature(signature: Signature): Promise { + return signature.getTypeArguments(); + } + /** Get the source type of an object/array assignment pattern, including nested patterns and for-of initializers. */ async getTypeOfAssignmentPattern(node: ObjectLiteralExpression | ArrayLiteralExpression): Promise { const data = await this.client.apiRequest("getTypeOfAssignmentPattern", { @@ -4161,6 +4166,7 @@ export class Signature { readonly thisParameter?: CompactSymbolReference | undefined; readonly target?: number | undefined; private returnType: number | false; + private typeArguments: readonly number[] | false; constructor(data: SignatureResponse, project: Project, objectRegistry: ProjectObjectRegistry) { this.id = data.id; @@ -4174,6 +4180,7 @@ export class Signature { this.thisParameter = data.thisParameter; this.target = data.target; this.returnType = false; + this.typeArguments = false; } get declaration(): NodeHandle | undefined { @@ -4187,6 +4194,13 @@ export class Signature { return this.objectRegistry.fetchTypes(this, "getTypeParametersOfSignature", this.typeParameters) as Promise; } + /** Get inferred or explicit type arguments; empty when this signature has no instantiation. */ + async getTypeArguments(): Promise { + const result = await this.objectRegistry.fetchTypes(this, "getTypeArgumentsForResolvedSignature", this.typeArguments || undefined); + this.typeArguments = result.map(type => type.id); + return result; + } + async getParameters(): Promise { return this.objectRegistry.fetchSymbols(this, "getParametersOfSignature", this.parameters); } diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index 7c97f087b4184..04b26b4929b5c 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -125,6 +125,7 @@ export interface APIMethodInfo { getNameTypeOfMappedType: APIMethod; getTemplateTypeOfMappedType: APIMethod; getTypeParametersOfSignature: APIMethod; + getTypeArgumentsForResolvedSignature: APIMethod; getParametersOfSignature: APIMethod; getThisParameterOfSignature: APIMethod; getTargetOfSignature: APIMethod; @@ -1370,6 +1371,7 @@ export interface BatchRequest { | "getTrueType" | "getTrueTypeOfConditionalType" | "getTypeArguments" + | "getTypeArgumentsForResolvedSignature" | "getTypeAtLocation" | "getTypeAtLocations" | "getTypeAtPosition" @@ -1569,6 +1571,7 @@ export interface BatchResponse { | "getTrueType" | "getTrueTypeOfConditionalType" | "getTypeArguments" + | "getTypeArgumentsForResolvedSignature" | "getTypeAtLocation" | "getTypeAtLocations" | "getTypeAtPosition" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index b7c6e0fe11b05..d9a5b797cb554 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -4220,6 +4220,24 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get inferred or explicit signature type arguments; empty when the signature has no instantiation. */ + get getTypeArgumentsForResolvedSignature(): { + (signature: Signature): readonly Type[]; + gen(signature: Signature): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "getTypeArgumentsForResolvedSignature", + function (signature: Signature): readonly Type[] { + return signature.getTypeArguments(); + }, + function* (signature: Signature): Generator { + return yield* signature.getTypeArguments.gen(); + }, + ); + } + /** Get the source type of an object/array assignment pattern, including nested patterns and for-of initializers. */ get getTypeOfAssignmentPattern(): { (node: ObjectLiteralExpression | ArrayLiteralExpression): Type | undefined; @@ -8566,6 +8584,7 @@ export class Signature { readonly thisParameter?: CompactSymbolReference | undefined; readonly target?: number | undefined; private returnType: number | false; + private typeArguments: readonly number[] | false; constructor(data: SignatureResponse, project: Project, objectRegistry: ProjectObjectRegistry) { this.id = data.id; @@ -8579,6 +8598,7 @@ export class Signature { this.thisParameter = data.thisParameter; this.target = data.target; this.returnType = false; + this.typeArguments = false; } get declaration(): NodeHandle | undefined { @@ -8605,6 +8625,28 @@ export class Signature { ); } + /** Get inferred or explicit type arguments; empty when this signature has no instantiation. */ + get getTypeArguments(): { + (): readonly Type[]; + gen(): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "getTypeArguments", + function (): readonly Type[] { + const result = owner.objectRegistry.fetchTypes(owner, "getTypeArgumentsForResolvedSignature", owner.typeArguments || undefined); + owner.typeArguments = result.map(type => type.id); + return result; + }, + function* (): Generator { + const result = yield* owner.objectRegistry.fetchTypes.gen(owner, "getTypeArgumentsForResolvedSignature", owner.typeArguments || undefined); + owner.typeArguments = result.map(type => type.id); + return result; + }, + ); + } + get getParameters(): { (): readonly Symbol[]; gen(): Generator; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 2a7e05dc830ad..c52507bcfe60e 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -176,6 +176,39 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getTypeArgumentsForResolvedSignature", { concurrency }, () => { + test("instantiates inferred, explicit, and defaulted type arguments and handles non-generic calls", async () => { + await using api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/index.ts": ` +declare function f(value?: T): [T, U]; +declare function plain(): void; +f("inferred"); +f(true); +f(); +plain(); +`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const calls: Node[] = []; + file.forEachChild(function visit(node) { + if (isCallExpression(node)) calls.push(node); + node.forEachChild(visit); + }); + const results: string[][] = []; + for (const call of calls) { + const signature = await project.checker.getResolvedSignature(call); + const types = await project.checker.getTypeArgumentsForResolvedSignature(signature); + assert.deepEqual(await signature.getTypeArguments(), types); + results.push(await Promise.all(types.map(type => project.checker.typeToString(type)))); + } + assert.deepEqual(results, [["string", "number"], ["boolean", "number"], ["unknown", "number"], []]); + }); +}); + describe("Checker - getTypeOfAssignmentPattern", { concurrency }, () => { test("rejects object literals that are not assignment patterns", async () => { await using api = spawnAPI({ "/tsconfig.json": "{}", "/index.ts": "const value = {};" }); diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 03ac48d4eaf2c..b3a3e9f992d55 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1733,6 +1733,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Checker", "isTupleType", checker.isTupleType, assertDeepEquivalent, tupleType), parityCase("Checker", "isTupleTypeTarget", checker.isTupleTypeTarget, assertDeepEquivalent, tupleType), parityCase("Checker", "getReturnTypeOfSignature", checker.getReturnTypeOfSignature, assertTypesEquivalent, signature), + parityCase("Checker", "getTypeArgumentsForResolvedSignature", checker.getTypeArgumentsForResolvedSignature, assertTypeArraysEquivalent, checker.getResolvedSignature(callExpression)), parityCase("Checker", "getRestTypeOfSignature", checker.getRestTypeOfSignature, assertOptionalTypesEquivalent, signature), parityCase("Checker", "getTypePredicateOfSignature", checker.getTypePredicateOfSignature, assertOptionalTypePredicatesEquivalent, predicateSignature), parityCase("Checker", "getBaseTypes", checker.getBaseTypes, assertTypeArraysEquivalent, derivedType), @@ -1828,6 +1829,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Type", "getBaseTypes", derivedType.getBaseTypes, assertOptionalTypeArrayEquivalent), parityCase("Signature", "getTypeParameters", signature.getTypeParameters, assertTypeArraysEquivalent), + parityCase("Signature", "getTypeArguments", signature.getTypeArguments, assertTypeArraysEquivalent), parityCase("Signature", "getParameters", signature.getParameters, assertSymbolArraysEquivalent), parityCase("Signature", "getThisParameter", signature.getThisParameter, assertOptionalSymbolsEquivalent), parityCase("Signature", "getTarget", constructSignature.getTarget, assertOptionalSignaturesEquivalent), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 57499534df475..38311a99219bf 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -184,6 +184,39 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getTypeArgumentsForResolvedSignature", { concurrency }, () => { + test("instantiates inferred, explicit, and defaulted type arguments and handles non-generic calls", () => { + using api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/index.ts": ` +declare function f(value?: T): [T, U]; +declare function plain(): void; +f("inferred"); +f(true); +f(); +plain(); +`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const calls: Node[] = []; + file.forEachChild(function visit(node) { + if (isCallExpression(node)) calls.push(node); + node.forEachChild(visit); + }); + const results: string[][] = []; + for (const call of calls) { + const signature = project.checker.getResolvedSignature(call); + const types = project.checker.getTypeArgumentsForResolvedSignature(signature); + assert.deepEqual(signature.getTypeArguments(), types); + results.push(types.map(type => project.checker.typeToString(type))); + } + assert.deepEqual(results, [["string", "number"], ["boolean", "number"], ["unknown", "number"], []]); + }); +}); + describe("Checker - getTypeOfAssignmentPattern", { concurrency }, () => { test("rejects object literals that are not assignment patterns", () => { using api = spawnAPI({ "/tsconfig.json": "{}", "/index.ts": "const value = {};" }); diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index b17ba69e9423a..248c48c334377 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -161,10 +161,11 @@ const ( MethodGetTemplateTypeOfMappedType Method = "getTemplateTypeOfMappedType" // Signature sub-property methods - MethodGetTypeParametersOfSignature Method = "getTypeParametersOfSignature" - MethodGetParametersOfSignature Method = "getParametersOfSignature" - MethodGetThisParameterOfSignature Method = "getThisParameterOfSignature" - MethodGetTargetOfSignature Method = "getTargetOfSignature" + MethodGetTypeParametersOfSignature Method = "getTypeParametersOfSignature" + MethodGetTypeArgumentsForResolvedSignature Method = "getTypeArgumentsForResolvedSignature" + MethodGetParametersOfSignature Method = "getParametersOfSignature" + MethodGetThisParameterOfSignature Method = "getThisParameterOfSignature" + MethodGetTargetOfSignature Method = "getTargetOfSignature" // Checker methods MethodIsOptionalParameter Method = "isOptionalParameter" @@ -703,10 +704,11 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetTrueTypeOfConditionalType: unmarshallerFor[GetTypePropertyParams], MethodGetFalseTypeOfConditionalType: unmarshallerFor[GetTypePropertyParams], - MethodGetTypeParametersOfSignature: unmarshallerFor[GetSignaturePropertyParams], - MethodGetParametersOfSignature: unmarshallerFor[GetSignaturePropertyParams], - MethodGetThisParameterOfSignature: unmarshallerFor[GetSignaturePropertyParams], - MethodGetTargetOfSignature: unmarshallerFor[GetSignaturePropertyParams], + MethodGetTypeParametersOfSignature: unmarshallerFor[GetSignaturePropertyParams], + MethodGetTypeArgumentsForResolvedSignature: unmarshallerFor[GetSignaturePropertyParams], + MethodGetParametersOfSignature: unmarshallerFor[GetSignaturePropertyParams], + MethodGetThisParameterOfSignature: unmarshallerFor[GetSignaturePropertyParams], + MethodGetTargetOfSignature: unmarshallerFor[GetSignaturePropertyParams], MethodGetContextualType: unmarshallerFor[GetContextualTypeParams], MethodIsOptionalParameter: unmarshallerFor[CheckerNodeParams], diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index 9e05cf484aad5..b8c48b82813eb 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1065,6 +1065,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetFalseTypeOfConditionalType(ctx, parsed.(*GetTypePropertyParams)) case string(MethodGetTypeParametersOfSignature): return s.handleGetTypeParametersOfSignature(ctx, parsed.(*GetSignaturePropertyParams)) + case string(MethodGetTypeArgumentsForResolvedSignature): + return s.handleGetTypeArgumentsForResolvedSignature(ctx, parsed.(*GetSignaturePropertyParams)) case string(MethodGetParametersOfSignature): return s.handleGetParametersOfSignature(ctx, parsed.(*GetSignaturePropertyParams)) case string(MethodGetThisParameterOfSignature): @@ -3979,6 +3981,25 @@ func (s *Session) handleIsOptionalParameter(ctx context.Context, params *Checker return setup.checker.IsOptionalParameter(node), nil } +func (s *Session) handleGetTypeArgumentsForResolvedSignature(ctx context.Context, params *GetSignaturePropertyParams) ([]*TypeResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + signature, err := setup.resolveSignatureHandle(params.Signature) + if err != nil { + return nil, err + } + types := setup.checker.GetTypeArgumentsForResolvedSignature(signature) + result := make([]*TypeResponse, len(types)) + for i, t := range types { + result[i] = setup.sd.newTypeResponse(setup.projectID, t, setup.checker) + } + return result, nil +} + // @gen-proto-nullable func (s *Session) handleGetTypeOfAssignmentPattern(ctx context.Context, params *CheckerNodeParams) (*TypeResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index 3831bd15eeed6..c36f873dfc5e2 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -162,6 +162,14 @@ func (c *Checker) IsOptionalParameter(node *ast.Node) bool { return c.isOptionalParameter(node) } +func (c *Checker) GetTypeArgumentsForResolvedSignature(signature *Signature) []*Type { + if signature.mapper == nil { + return nil + } + target := core.OrElse(signature.target, signature) + return c.instantiateTypes(target.TypeParameters(), signature.mapper) +} + func (c *Checker) IsValidPropertyAccess(node *ast.Node, propertyName string) bool { return c.isValidPropertyAccess(node, propertyName) } From dfabb5a097e5773b847e9216058b43b493a4661f Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:29:40 -0800 Subject: [PATCH 6/8] Expose checker root symbol query Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 10 ++++ .../typescript/src/api/proto.generated.ts | 3 ++ packages/typescript/src/api/sync/api.ts | 28 +++++++++++ packages/typescript/test/async/api.test.ts | 50 +++++++++++++++++++ .../test/sync/api-generators.test.ts | 1 + packages/typescript/test/sync/api.test.ts | 50 +++++++++++++++++++ tsc/internal/api/proto.go | 2 + tsc/internal/api/session.go | 21 ++++++++ 8 files changed, 165 insertions(+) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 521c344190f09..3d24d431ab580 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -2336,6 +2336,16 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ + async getRootSymbols(symbol: Symbol): Promise { + const data = await this.client.apiRequest("getRootSymbols", { + snapshot: this.snapshotId, + project: this.project.handle, + symbol: symbol.reference, + }); + return data ? data.map(symbol => this.objectRegistry.getOrCreateSymbol(symbol)) : []; + } + /** Get inferred or explicit signature type arguments; empty when the signature has no instantiation. */ async getTypeArgumentsForResolvedSignature(signature: Signature): Promise { return signature.getTypeArguments(); diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index 04b26b4929b5c..bc920ff97ef13 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -184,6 +184,7 @@ export interface APIMethodInfo { getImmediateAliasedSymbol: APIMethod; getTargetSymbol: APIMethod; getMergedSymbol: APIMethod; + getRootSymbols: APIMethod; getSymbolOfNode: APIMethod; getSymbolOfDeclarationForChecker: APIMethod; getParentOfSymbolForChecker: APIMethod; @@ -1338,6 +1339,7 @@ export interface BatchRequest { | "getResolvedTypeReferenceDirectiveFromTypeReferenceDirective" | "getRestTypeOfSignature" | "getReturnTypeOfSignature" + | "getRootSymbols" | "getSemanticDiagnostics" | "getShorthandAssignmentValueSymbol" | "getSignatureFromDeclaration" @@ -1538,6 +1540,7 @@ export interface BatchResponse { | "getResolvedTypeReferenceDirectiveFromTypeReferenceDirective" | "getRestTypeOfSignature" | "getReturnTypeOfSignature" + | "getRootSymbols" | "getSemanticDiagnostics" | "getShorthandAssignmentValueSymbol" | "getSignatureFromDeclaration" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index d9a5b797cb554..34a860a61b1d2 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -4220,6 +4220,34 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ + get getRootSymbols(): { + (symbol: Symbol): readonly Symbol[]; + gen(symbol: Symbol): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "getRootSymbols", + function (symbol: Symbol): readonly Symbol[] { + const data = owner.client.apiRequest("getRootSymbols", { + snapshot: owner.snapshotId, + project: owner.project.handle, + symbol: symbol.reference, + }); + return data ? data.map(symbol => owner.objectRegistry.getOrCreateSymbol(symbol)) : []; + }, + function* (symbol: Symbol): Generator { + const data = yield* apiRequest("getRootSymbols", { + snapshot: owner.snapshotId, + project: owner.project.handle, + symbol: symbol.reference, + }); + return data ? data.map(symbol => owner.objectRegistry.getOrCreateSymbol(symbol)) : []; + }, + ); + } + /** Get inferred or explicit signature type arguments; empty when the signature has no instantiation. */ get getTypeArgumentsForResolvedSignature(): { (signature: Signature): readonly Type[]; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index c52507bcfe60e..4158937b6650d 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -176,6 +176,56 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getRootSymbols", { concurrency }, () => { + test("follows synthetic union and mapped properties to their original declarations", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +interface A { value: string } +interface B { value: number } +declare const union: A | B; +declare const mapped: { [K in keyof A]: A[K] }; +union.value; +mapped.value; +`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const a = await project.checker.getSymbolAtPosition("/index.ts", "\ninterface ".length); + assert.ok(a); + const aValue = await (await project.checker.getDeclaredTypeOfSymbol(a)).getProperty("value"); + assert.ok(aValue); + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const union = await project.checker.getSymbolAtPosition("/index.ts", file.text.indexOf("union.value") + "union.".length); + const mapped = await project.checker.getSymbolAtPosition("/index.ts", file.text.indexOf("mapped.value") + "mapped.".length); + assert.ok(union && mapped); + const roots = await project.checker.getRootSymbols(union); + assert.equal(roots.length, 2); + assert.strictEqual(roots[0], aValue); + assert.equal(roots[1].name, "value"); + assert.notStrictEqual(roots[1], aValue); + assert.deepEqual(await project.checker.getRootSymbols(mapped), [aValue]); + assert.deepEqual(await project.checker.getRootSymbols(aValue), [aValue]); + }); + + test("queries a shared file-owned symbol through each requesting checker", async () => { + await using api = spawnAPI({ + "/a/tsconfig.json": JSON.stringify({ files: ["../shared.ts"] }), + "/b/tsconfig.json": JSON.stringify({ files: ["../shared.ts"] }), + "/shared.ts": "export interface Shared { value: string }", + }); + const snapshot = await api.createSnapshot({ openProjects: ["/a/tsconfig.json", "/b/tsconfig.json"] }); + const first = snapshot.getConfiguredProject("/a/tsconfig.json")!; + const second = snapshot.getConfiguredProject("/b/tsconfig.json")!; + const symbol = await first.checker.getSymbolAtPosition("/shared.ts", "export interface Shared { ".length); + assert.ok(symbol); + assert.strictEqual(symbol, await second.checker.getSymbolAtPosition("/shared.ts", "export interface Shared { ".length)); + assert.deepEqual(await first.checker.getRootSymbols(symbol), [symbol]); + assert.deepEqual(await second.checker.getRootSymbols(symbol), [symbol]); + }); +}); + describe("Checker - getTypeArgumentsForResolvedSignature", { concurrency }, () => { test("instantiates inferred, explicit, and defaulted type arguments and handles non-generic calls", async () => { await using api = spawnAPI({ diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index b3a3e9f992d55..8c93e0d812272 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1672,6 +1672,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Program", "getDeclarationEmit", program.getDeclarationEmit, assertDeepEquivalent, ["/src/index.ts"]), parityCase("Checker", "getMergedSymbol", checker.getMergedSymbol, assertSymbolsEquivalent, interfaceSymbol), + parityCase("Checker", "getRootSymbols", checker.getRootSymbols, assertSymbolArraysEquivalent, boxedOptSymbol), parityCase("Checker", "getSymbolOfNode", checker.getSymbolOfNode, assertOptionalSymbolsEquivalent, interfaceDeclaration), parityCase("Checker", "getSymbolOfNode", checker.getSymbolOfNode, assertOptionalSymbolsEquivalent, interfaceDeclaration.name), parityCase("Checker", "getSymbolOfDeclaration", checker.getSymbolOfDeclaration, assertSymbolsEquivalent, interfaceDeclaration), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 38311a99219bf..4a4c0323d280a 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -184,6 +184,56 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getRootSymbols", { concurrency }, () => { + test("follows synthetic union and mapped properties to their original declarations", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +interface A { value: string } +interface B { value: number } +declare const union: A | B; +declare const mapped: { [K in keyof A]: A[K] }; +union.value; +mapped.value; +`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const a = project.checker.getSymbolAtPosition("/index.ts", "\ninterface ".length); + assert.ok(a); + const aValue = (project.checker.getDeclaredTypeOfSymbol(a)).getProperty("value"); + assert.ok(aValue); + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const union = project.checker.getSymbolAtPosition("/index.ts", file.text.indexOf("union.value") + "union.".length); + const mapped = project.checker.getSymbolAtPosition("/index.ts", file.text.indexOf("mapped.value") + "mapped.".length); + assert.ok(union && mapped); + const roots = project.checker.getRootSymbols(union); + assert.equal(roots.length, 2); + assert.strictEqual(roots[0], aValue); + assert.equal(roots[1].name, "value"); + assert.notStrictEqual(roots[1], aValue); + assert.deepEqual(project.checker.getRootSymbols(mapped), [aValue]); + assert.deepEqual(project.checker.getRootSymbols(aValue), [aValue]); + }); + + test("queries a shared file-owned symbol through each requesting checker", () => { + using api = spawnAPI({ + "/a/tsconfig.json": JSON.stringify({ files: ["../shared.ts"] }), + "/b/tsconfig.json": JSON.stringify({ files: ["../shared.ts"] }), + "/shared.ts": "export interface Shared { value: string }", + }); + const snapshot = api.createSnapshot({ openProjects: ["/a/tsconfig.json", "/b/tsconfig.json"] }); + const first = snapshot.getConfiguredProject("/a/tsconfig.json")!; + const second = snapshot.getConfiguredProject("/b/tsconfig.json")!; + const symbol = first.checker.getSymbolAtPosition("/shared.ts", "export interface Shared { ".length); + assert.ok(symbol); + assert.strictEqual(symbol, second.checker.getSymbolAtPosition("/shared.ts", "export interface Shared { ".length)); + assert.deepEqual(first.checker.getRootSymbols(symbol), [symbol]); + assert.deepEqual(second.checker.getRootSymbols(symbol), [symbol]); + }); +}); + describe("Checker - getTypeArgumentsForResolvedSignature", { concurrency }, () => { test("instantiates inferred, explicit, and defaulted type arguments and handles non-generic calls", () => { using api = spawnAPI({ diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index 248c48c334377..fcbf35d6d5a57 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -223,6 +223,7 @@ const ( MethodGetImmediateAliasedSymbol Method = "getImmediateAliasedSymbol" MethodGetTargetSymbol Method = "getTargetSymbol" MethodGetMergedSymbol Method = "getMergedSymbol" + MethodGetRootSymbols Method = "getRootSymbols" MethodGetSymbolOfNode Method = "getSymbolOfNode" MethodGetSymbolOfDeclarationForChecker Method = "getSymbolOfDeclarationForChecker" MethodGetParentOfSymbolForChecker Method = "getParentOfSymbolForChecker" @@ -763,6 +764,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetImmediateAliasedSymbol: unmarshallerFor[CheckerSymbolParams], MethodGetTargetSymbol: unmarshallerFor[CheckerSymbolParams], MethodGetMergedSymbol: unmarshallerFor[CheckerSymbolParams], + MethodGetRootSymbols: unmarshallerFor[CheckerSymbolParams], MethodGetSymbolOfNode: unmarshallerFor[CheckerNodeParams], MethodGetSymbolOfDeclarationForChecker: unmarshallerFor[CheckerNodeParams], MethodGetParentOfSymbolForChecker: unmarshallerFor[CheckerSymbolParams], diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index b8c48b82813eb..27bf3b1d6f24c 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1185,6 +1185,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleMethodGetTargetSymbol(ctx, parsed.(*CheckerSymbolParams)) case string(MethodGetMergedSymbol): return s.handleGetMergedSymbol(ctx, parsed.(*CheckerSymbolParams)) + case string(MethodGetRootSymbols): + return s.handleGetRootSymbols(ctx, parsed.(*CheckerSymbolParams)) case string(MethodGetSymbolOfNode): return s.handleGetSymbolOfNode(ctx, parsed.(*CheckerNodeParams)) case string(MethodGetSymbolOfDeclarationForChecker): @@ -3981,6 +3983,25 @@ func (s *Session) handleIsOptionalParameter(ctx context.Context, params *Checker return setup.checker.IsOptionalParameter(node), nil } +func (s *Session) handleGetRootSymbols(ctx context.Context, params *CheckerSymbolParams) ([]*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + symbol, err := setup.resolveSymbolHandle(params.Symbol) + if err != nil { + return nil, err + } + roots := setup.checker.GetRootSymbols(symbol) + result := make([]*SymbolResponse, len(roots)) + for i, root := range roots { + result[i] = setup.newSymbolResponse(root) + } + return result, nil +} + func (s *Session) handleGetTypeArgumentsForResolvedSignature(ctx context.Context, params *GetSignaturePropertyParams) ([]*TypeResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) if err != nil { From ab2f55e362bf7319b56853ace4a9be3b2c3e864a Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 18 Nov 2026 14:51:29 -0800 Subject: [PATCH 7/8] Expose native expando symbol query Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 15 ++++ .../typescript/src/api/proto.generated.ts | 10 +++ packages/typescript/src/api/sync/api.ts | 34 +++++++++ packages/typescript/test/async/api.test.ts | 75 +++++++++++++++++++ .../test/sync/api-generators.test.ts | 1 + packages/typescript/test/sync/api.test.ts | 75 +++++++++++++++++++ tsc/internal/api/proto.go | 9 +++ tsc/internal/api/session.go | 21 ++++++ tsc/internal/checker/services.go | 28 +++++++ 9 files changed, 268 insertions(+) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 3d24d431ab580..4f19c9731e0e1 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -2336,6 +2336,21 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** + * Find the symbol initialized by a function/arrow expression, or by a class or + * unannotated empty object literal in JavaScript. TypeScript variables must be const-like. + * With `allowDeclaration`, also accept function declarations and assignment declaration sides. + */ + async getSymbolOfExpando(node: Node, allowDeclaration: boolean = false): Promise { + const data = await this.client.apiRequest("getSymbolOfExpando", { + snapshot: this.snapshotId, + project: this.project.handle, + location: getNodeRequestHandle(node), + allowDeclaration, + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ async getRootSymbols(symbol: Symbol): Promise { const data = await this.client.apiRequest("getRootSymbols", { diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index bc920ff97ef13..9f776ff1494cd 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -185,6 +185,7 @@ export interface APIMethodInfo { getTargetSymbol: APIMethod; getMergedSymbol: APIMethod; getRootSymbols: APIMethod; + getSymbolOfExpando: APIMethod; getSymbolOfNode: APIMethod; getSymbolOfDeclarationForChecker: APIMethod; getParentOfSymbolForChecker: APIMethod; @@ -1019,6 +1020,13 @@ export interface CheckerSymbolParams { symbol: SymbolReference; } +export interface GetSymbolOfExpandoParams { + snapshot: number; + project: number; + location: string; + allowDeclaration: boolean; +} + /** GetMemberInModuleExportsParams are parameters for getMemberInModuleExports. */ export interface GetMemberInModuleExportsParams { snapshot: number; @@ -1355,6 +1363,7 @@ export interface BatchRequest { | "getSymbolAtPosition" | "getSymbolOfDeclaration" | "getSymbolOfDeclarationForChecker" + | "getSymbolOfExpando" | "getSymbolOfNode" | "getSymbolOfSourceFile" | "getSymbolOfType" @@ -1556,6 +1565,7 @@ export interface BatchResponse { | "getSymbolAtPosition" | "getSymbolOfDeclaration" | "getSymbolOfDeclarationForChecker" + | "getSymbolOfExpando" | "getSymbolOfNode" | "getSymbolOfSourceFile" | "getSymbolOfType" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 34a860a61b1d2..003aa2f65962d 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -4220,6 +4220,40 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { + /** + * Find the symbol initialized by a function/arrow expression, or by a class or + * unannotated empty object literal in JavaScript. TypeScript variables must be const-like. + * With `allowDeclaration`, also accept function declarations and assignment declaration sides. + */ + get getSymbolOfExpando(): { + (node: Node, allowDeclaration?: boolean): Symbol | undefined; + gen(node: Node, allowDeclaration?: boolean): Generator; + } { + const owner = this; + return cacheGeneratorMethod( + owner, + "getSymbolOfExpando", + function (node: Node, allowDeclaration: boolean = false): Symbol | undefined { + const data = owner.client.apiRequest("getSymbolOfExpando", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + allowDeclaration, + }); + return data ? owner.objectRegistry.getOrCreateSymbol(data) : undefined; + }, + function* (node: Node, allowDeclaration: boolean = false): Generator { + const data = yield* apiRequest("getSymbolOfExpando", { + snapshot: owner.snapshotId, + project: owner.project.handle, + location: getNodeRequestHandle(node), + allowDeclaration, + }); + return data ? owner.objectRegistry.getOrCreateSymbol(data) : undefined; + }, + ); + } + /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ get getRootSymbols(): { (symbol: Symbol): readonly Symbol[]; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 4158937b6650d..69abc99ee868f 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -11,6 +11,7 @@ import { type Identifier, InternalSymbolName, isArrayLiteralExpression, + isBinaryExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -176,6 +177,80 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getSymbolOfExpando", { concurrency }, () => { + test("recognizes const-like function initializers and optionally function declarations", async () => { + await using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +const arrow = () => {}; +const expression = function () {}; +let mutable = () => {}; +const object = {}; +function declaration() {} +`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.ts"); + assert.ok(file); + const results: (string | undefined)[] = []; + for (const statement of file.statements) { + if (isVariableStatement(statement)) { + const declaration = statement.declarationList.declarations[0]; + assert.ok(declaration.initializer); + const symbol = await project.checker.getSymbolOfExpando(declaration.initializer); + results.push(symbol?.name); + if (symbol) assert.strictEqual(symbol, await project.checker.getSymbolAtLocation(declaration.name)); + } + else { + assert.ok(isFunctionDeclaration(statement)); + assert.equal(await project.checker.getSymbolOfExpando(statement), undefined); + const symbol = await project.checker.getSymbolOfExpando(statement, true); + assert.strictEqual(symbol, await project.checker.getSymbolOfDeclaration(statement)); + } + } + assert.deepEqual(results, ["arrow", "expression", undefined, undefined]); + }); + + test("recognizes JavaScript class/object initializers and assignment declarations", async () => { + await using api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { allowJs: true } }), + "/index.js": ` +var fn = function () {}; +var cls = class {}; +var empty = {}; +var populated = { value: 1 }; +/** @type {{}} */ +var annotated = {}; +exports.assigned = function () {}; +`, + }); + const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = await project.program.getSourceFile("/index.js"); + assert.ok(file); + const results: (string | undefined)[] = []; + for (const statement of file.statements) { + if (isVariableStatement(statement)) { + const node = statement.declarationList.declarations[0].initializer; + assert.ok(node); + results.push((await project.checker.getSymbolOfExpando(node))?.name); + } + else { + assert.ok(isExpressionStatement(statement)); + const node = statement.expression; + assert.ok(isBinaryExpression(node)); + const symbol = await project.checker.getSymbolOfExpando(node.right); + assert.ok(symbol); + assert.equal(symbol.name, "assigned"); + assert.equal(await project.checker.getSymbolOfExpando(node.left), undefined); + assert.strictEqual(await project.checker.getSymbolOfExpando(node.left, true), symbol); + } + } + assert.deepEqual(results, ["fn", "cls", "empty", undefined, undefined]); + }); +}); + describe("Checker - getRootSymbols", { concurrency }, () => { test("follows synthetic union and mapped properties to their original declarations", async () => { await using api = spawnAPI({ diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 8c93e0d812272..dc5b7096cfeb7 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1779,6 +1779,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Checker", "getAmbientModules", checker.getAmbientModules, assertSymbolArraysEquivalent), parityCase("Checker", "getTargetSymbol", checker.getTargetSymbol, assertOptionalSymbolsEquivalent, boxedOptSymbol), parityCase("Checker", "getExportSymbolOfSymbol", checker.getExportSymbolOfSymbol, assertSymbolsEquivalent, localCombineSymbol), + parityCase("Checker", "getSymbolOfExpando", checker.getSymbolOfExpando, assertOptionalSymbolsEquivalent, combineDeclaration, true), parityCase("Printer", "printNode", printer.printNode, assertDeepEquivalent, combineDeclaration, { preserveSourceNewlines: true }), parityCase("Printer", "printFile", printer.printFile, assertDeepEquivalent, indexFile, { preserveSourceNewlines: true }), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index 4a4c0323d280a..c1bbe1c712807 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -19,6 +19,7 @@ import { type Identifier, InternalSymbolName, isArrayLiteralExpression, + isBinaryExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -184,6 +185,80 @@ import { const concurrency = areTestsFiltered(); +describe("Checker - getSymbolOfExpando", { concurrency }, () => { + test("recognizes const-like function initializers and optionally function declarations", () => { + using api = spawnAPI({ + "/tsconfig.json": "{}", + "/index.ts": ` +const arrow = () => {}; +const expression = function () {}; +let mutable = () => {}; +const object = {}; +function declaration() {} +`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.ts"); + assert.ok(file); + const results: (string | undefined)[] = []; + for (const statement of file.statements) { + if (isVariableStatement(statement)) { + const declaration = statement.declarationList.declarations[0]; + assert.ok(declaration.initializer); + const symbol = project.checker.getSymbolOfExpando(declaration.initializer); + results.push(symbol?.name); + if (symbol) assert.strictEqual(symbol, project.checker.getSymbolAtLocation(declaration.name)); + } + else { + assert.ok(isFunctionDeclaration(statement)); + assert.equal(project.checker.getSymbolOfExpando(statement), undefined); + const symbol = project.checker.getSymbolOfExpando(statement, true); + assert.strictEqual(symbol, project.checker.getSymbolOfDeclaration(statement)); + } + } + assert.deepEqual(results, ["arrow", "expression", undefined, undefined]); + }); + + test("recognizes JavaScript class/object initializers and assignment declarations", () => { + using api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { allowJs: true } }), + "/index.js": ` +var fn = function () {}; +var cls = class {}; +var empty = {}; +var populated = { value: 1 }; +/** @type {{}} */ +var annotated = {}; +exports.assigned = function () {}; +`, + }); + const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); + const project = snapshot.getConfiguredProject("/tsconfig.json")!; + const file = project.program.getSourceFile("/index.js"); + assert.ok(file); + const results: (string | undefined)[] = []; + for (const statement of file.statements) { + if (isVariableStatement(statement)) { + const node = statement.declarationList.declarations[0].initializer; + assert.ok(node); + results.push((project.checker.getSymbolOfExpando(node))?.name); + } + else { + assert.ok(isExpressionStatement(statement)); + const node = statement.expression; + assert.ok(isBinaryExpression(node)); + const symbol = project.checker.getSymbolOfExpando(node.right); + assert.ok(symbol); + assert.equal(symbol.name, "assigned"); + assert.equal(project.checker.getSymbolOfExpando(node.left), undefined); + assert.strictEqual(project.checker.getSymbolOfExpando(node.left, true), symbol); + } + } + assert.deepEqual(results, ["fn", "cls", "empty", undefined, undefined]); + }); +}); + describe("Checker - getRootSymbols", { concurrency }, () => { test("follows synthetic union and mapped properties to their original declarations", () => { using api = spawnAPI({ diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index fcbf35d6d5a57..455de37ce0cec 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -224,6 +224,7 @@ const ( MethodGetTargetSymbol Method = "getTargetSymbol" MethodGetMergedSymbol Method = "getMergedSymbol" MethodGetRootSymbols Method = "getRootSymbols" + MethodGetSymbolOfExpando Method = "getSymbolOfExpando" MethodGetSymbolOfNode Method = "getSymbolOfNode" MethodGetSymbolOfDeclarationForChecker Method = "getSymbolOfDeclarationForChecker" MethodGetParentOfSymbolForChecker Method = "getParentOfSymbolForChecker" @@ -765,6 +766,7 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetTargetSymbol: unmarshallerFor[CheckerSymbolParams], MethodGetMergedSymbol: unmarshallerFor[CheckerSymbolParams], MethodGetRootSymbols: unmarshallerFor[CheckerSymbolParams], + MethodGetSymbolOfExpando: unmarshallerFor[GetSymbolOfExpandoParams], MethodGetSymbolOfNode: unmarshallerFor[CheckerNodeParams], MethodGetSymbolOfDeclarationForChecker: unmarshallerFor[CheckerNodeParams], MethodGetParentOfSymbolForChecker: unmarshallerFor[CheckerSymbolParams], @@ -1965,6 +1967,13 @@ type CheckerNodeParams struct { Location NodeHandle `json:"location"` } +type GetSymbolOfExpandoParams struct { + Snapshot SnapshotID `json:"snapshot"` + Project project.Handle `json:"project"` + Location NodeHandle `json:"location"` + AllowDeclaration bool `json:"allowDeclaration"` +} + type IsValidPropertyAccessParams struct { Snapshot SnapshotID `json:"snapshot"` Project project.Handle `json:"project"` diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index 27bf3b1d6f24c..c068db8dda87e 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1187,6 +1187,8 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetMergedSymbol(ctx, parsed.(*CheckerSymbolParams)) case string(MethodGetRootSymbols): return s.handleGetRootSymbols(ctx, parsed.(*CheckerSymbolParams)) + case string(MethodGetSymbolOfExpando): + return s.handleGetSymbolOfExpando(ctx, parsed.(*GetSymbolOfExpandoParams)) case string(MethodGetSymbolOfNode): return s.handleGetSymbolOfNode(ctx, parsed.(*CheckerNodeParams)) case string(MethodGetSymbolOfDeclarationForChecker): @@ -3983,6 +3985,25 @@ func (s *Session) handleIsOptionalParameter(ctx context.Context, params *Checker return setup.checker.IsOptionalParameter(node), nil } +// @gen-proto-nullable +func (s *Session) handleGetSymbolOfExpando(ctx context.Context, params *GetSymbolOfExpandoParams) (*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return nil, err + } + symbol := setup.checker.GetSymbolOfExpando(node, params.AllowDeclaration) + if symbol == nil { + return nil, nil + } + return setup.newSymbolResponse(symbol), nil +} + func (s *Session) handleGetRootSymbols(ctx context.Context, params *CheckerSymbolParams) ([]*SymbolResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) if err != nil { diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index c36f873dfc5e2..a92bd61436cf8 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -162,6 +162,34 @@ func (c *Checker) IsOptionalParameter(node *ast.Node) bool { return c.isOptionalParameter(node) } +// GetSymbolOfExpando finds the declaration whose initializer can acquire expando properties. +// With allowDeclaration, it also accepts the declaration side of assignments and function declarations. +func (c *Checker) GetSymbolOfExpando(node *ast.Node, allowDeclaration bool) *ast.Symbol { + parent := node.Parent + if parent == nil { + return nil + } + var declaration *ast.Node + switch { + case ast.IsVariableDeclaration(parent) && parent.Initializer() == node: + if !ast.IsInJSFile(node) && !(ast.IsVarConstLike(parent) && ast.IsFunctionLikeDeclaration(node)) { + return nil + } + declaration = parent + case ast.IsBinaryExpression(parent): + binary := parent.AsBinaryExpression() + if binary.OperatorToken.Kind == ast.KindEqualsToken && (allowDeclaration || binary.Right == node) { + declaration = parent + } + case allowDeclaration && ast.IsFunctionDeclaration(node): + declaration = node + } + if declaration == nil || !allowDeclaration && !ast.IsExpandoInitializer(declaration, node) { + return nil + } + return c.getSymbolOfNode(declaration) +} + func (c *Checker) GetTypeArgumentsForResolvedSignature(signature *Signature) []*Type { if signature.mapper == nil { return nil From 60d17f38caf3cdb4fbdbe71acc3edbfa9c34b5d0 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Thu, 19 Nov 2026 16:30:59 -0800 Subject: [PATCH 8/8] Remove expando symbol query API Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/typescript/src/api/async/api.ts | 15 ---- .../typescript/src/api/proto.generated.ts | 10 --- packages/typescript/src/api/sync/api.ts | 34 --------- packages/typescript/test/async/api.test.ts | 75 ------------------- .../test/sync/api-generators.test.ts | 1 - packages/typescript/test/sync/api.test.ts | 75 ------------------- tsc/internal/api/proto.go | 9 --- tsc/internal/api/session.go | 21 ------ tsc/internal/checker/services.go | 28 ------- 9 files changed, 268 deletions(-) diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 4f19c9731e0e1..3d24d431ab580 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -2336,21 +2336,6 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { - /** - * Find the symbol initialized by a function/arrow expression, or by a class or - * unannotated empty object literal in JavaScript. TypeScript variables must be const-like. - * With `allowDeclaration`, also accept function declarations and assignment declaration sides. - */ - async getSymbolOfExpando(node: Node, allowDeclaration: boolean = false): Promise { - const data = await this.client.apiRequest("getSymbolOfExpando", { - snapshot: this.snapshotId, - project: this.project.handle, - location: getNodeRequestHandle(node), - allowDeclaration, - }); - return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; - } - /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ async getRootSymbols(symbol: Symbol): Promise { const data = await this.client.apiRequest("getRootSymbols", { diff --git a/packages/typescript/src/api/proto.generated.ts b/packages/typescript/src/api/proto.generated.ts index 9f776ff1494cd..bc920ff97ef13 100644 --- a/packages/typescript/src/api/proto.generated.ts +++ b/packages/typescript/src/api/proto.generated.ts @@ -185,7 +185,6 @@ export interface APIMethodInfo { getTargetSymbol: APIMethod; getMergedSymbol: APIMethod; getRootSymbols: APIMethod; - getSymbolOfExpando: APIMethod; getSymbolOfNode: APIMethod; getSymbolOfDeclarationForChecker: APIMethod; getParentOfSymbolForChecker: APIMethod; @@ -1020,13 +1019,6 @@ export interface CheckerSymbolParams { symbol: SymbolReference; } -export interface GetSymbolOfExpandoParams { - snapshot: number; - project: number; - location: string; - allowDeclaration: boolean; -} - /** GetMemberInModuleExportsParams are parameters for getMemberInModuleExports. */ export interface GetMemberInModuleExportsParams { snapshot: number; @@ -1363,7 +1355,6 @@ export interface BatchRequest { | "getSymbolAtPosition" | "getSymbolOfDeclaration" | "getSymbolOfDeclarationForChecker" - | "getSymbolOfExpando" | "getSymbolOfNode" | "getSymbolOfSourceFile" | "getSymbolOfType" @@ -1565,7 +1556,6 @@ export interface BatchResponse { | "getSymbolAtPosition" | "getSymbolOfDeclaration" | "getSymbolOfDeclarationForChecker" - | "getSymbolOfExpando" | "getSymbolOfNode" | "getSymbolOfSourceFile" | "getSymbolOfType" diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index 003aa2f65962d..34a860a61b1d2 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -4220,40 +4220,6 @@ function encodeNumberLiteralValue(value: number): number | string { } export class Checker { - /** - * Find the symbol initialized by a function/arrow expression, or by a class or - * unannotated empty object literal in JavaScript. TypeScript variables must be const-like. - * With `allowDeclaration`, also accept function declarations and assignment declaration sides. - */ - get getSymbolOfExpando(): { - (node: Node, allowDeclaration?: boolean): Symbol | undefined; - gen(node: Node, allowDeclaration?: boolean): Generator; - } { - const owner = this; - return cacheGeneratorMethod( - owner, - "getSymbolOfExpando", - function (node: Node, allowDeclaration: boolean = false): Symbol | undefined { - const data = owner.client.apiRequest("getSymbolOfExpando", { - snapshot: owner.snapshotId, - project: owner.project.handle, - location: getNodeRequestHandle(node), - allowDeclaration, - }); - return data ? owner.objectRegistry.getOrCreateSymbol(data) : undefined; - }, - function* (node: Node, allowDeclaration: boolean = false): Generator { - const data = yield* apiRequest("getSymbolOfExpando", { - snapshot: owner.snapshotId, - project: owner.project.handle, - location: getNodeRequestHandle(node), - allowDeclaration, - }); - return data ? owner.objectRegistry.getOrCreateSymbol(data) : undefined; - }, - ); - } - /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ get getRootSymbols(): { (symbol: Symbol): readonly Symbol[]; diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 69abc99ee868f..4158937b6650d 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -11,7 +11,6 @@ import { type Identifier, InternalSymbolName, isArrayLiteralExpression, - isBinaryExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -177,80 +176,6 @@ import { const concurrency = areTestsFiltered(); -describe("Checker - getSymbolOfExpando", { concurrency }, () => { - test("recognizes const-like function initializers and optionally function declarations", async () => { - await using api = spawnAPI({ - "/tsconfig.json": "{}", - "/index.ts": ` -const arrow = () => {}; -const expression = function () {}; -let mutable = () => {}; -const object = {}; -function declaration() {} -`, - }); - const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; - const file = await project.program.getSourceFile("/index.ts"); - assert.ok(file); - const results: (string | undefined)[] = []; - for (const statement of file.statements) { - if (isVariableStatement(statement)) { - const declaration = statement.declarationList.declarations[0]; - assert.ok(declaration.initializer); - const symbol = await project.checker.getSymbolOfExpando(declaration.initializer); - results.push(symbol?.name); - if (symbol) assert.strictEqual(symbol, await project.checker.getSymbolAtLocation(declaration.name)); - } - else { - assert.ok(isFunctionDeclaration(statement)); - assert.equal(await project.checker.getSymbolOfExpando(statement), undefined); - const symbol = await project.checker.getSymbolOfExpando(statement, true); - assert.strictEqual(symbol, await project.checker.getSymbolOfDeclaration(statement)); - } - } - assert.deepEqual(results, ["arrow", "expression", undefined, undefined]); - }); - - test("recognizes JavaScript class/object initializers and assignment declarations", async () => { - await using api = spawnAPI({ - "/tsconfig.json": JSON.stringify({ compilerOptions: { allowJs: true } }), - "/index.js": ` -var fn = function () {}; -var cls = class {}; -var empty = {}; -var populated = { value: 1 }; -/** @type {{}} */ -var annotated = {}; -exports.assigned = function () {}; -`, - }); - const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; - const file = await project.program.getSourceFile("/index.js"); - assert.ok(file); - const results: (string | undefined)[] = []; - for (const statement of file.statements) { - if (isVariableStatement(statement)) { - const node = statement.declarationList.declarations[0].initializer; - assert.ok(node); - results.push((await project.checker.getSymbolOfExpando(node))?.name); - } - else { - assert.ok(isExpressionStatement(statement)); - const node = statement.expression; - assert.ok(isBinaryExpression(node)); - const symbol = await project.checker.getSymbolOfExpando(node.right); - assert.ok(symbol); - assert.equal(symbol.name, "assigned"); - assert.equal(await project.checker.getSymbolOfExpando(node.left), undefined); - assert.strictEqual(await project.checker.getSymbolOfExpando(node.left, true), symbol); - } - } - assert.deepEqual(results, ["fn", "cls", "empty", undefined, undefined]); - }); -}); - describe("Checker - getRootSymbols", { concurrency }, () => { test("follows synthetic union and mapped properties to their original declarations", async () => { await using api = spawnAPI({ diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index dc5b7096cfeb7..8c93e0d812272 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -1779,7 +1779,6 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => parityCase("Checker", "getAmbientModules", checker.getAmbientModules, assertSymbolArraysEquivalent), parityCase("Checker", "getTargetSymbol", checker.getTargetSymbol, assertOptionalSymbolsEquivalent, boxedOptSymbol), parityCase("Checker", "getExportSymbolOfSymbol", checker.getExportSymbolOfSymbol, assertSymbolsEquivalent, localCombineSymbol), - parityCase("Checker", "getSymbolOfExpando", checker.getSymbolOfExpando, assertOptionalSymbolsEquivalent, combineDeclaration, true), parityCase("Printer", "printNode", printer.printNode, assertDeepEquivalent, combineDeclaration, { preserveSourceNewlines: true }), parityCase("Printer", "printFile", printer.printFile, assertDeepEquivalent, indexFile, { preserveSourceNewlines: true }), diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index c1bbe1c712807..4a4c0323d280a 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -19,7 +19,6 @@ import { type Identifier, InternalSymbolName, isArrayLiteralExpression, - isBinaryExpression, isCallExpression, isClassDeclaration, isConstructorDeclaration, @@ -185,80 +184,6 @@ import { const concurrency = areTestsFiltered(); -describe("Checker - getSymbolOfExpando", { concurrency }, () => { - test("recognizes const-like function initializers and optionally function declarations", () => { - using api = spawnAPI({ - "/tsconfig.json": "{}", - "/index.ts": ` -const arrow = () => {}; -const expression = function () {}; -let mutable = () => {}; -const object = {}; -function declaration() {} -`, - }); - const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; - const file = project.program.getSourceFile("/index.ts"); - assert.ok(file); - const results: (string | undefined)[] = []; - for (const statement of file.statements) { - if (isVariableStatement(statement)) { - const declaration = statement.declarationList.declarations[0]; - assert.ok(declaration.initializer); - const symbol = project.checker.getSymbolOfExpando(declaration.initializer); - results.push(symbol?.name); - if (symbol) assert.strictEqual(symbol, project.checker.getSymbolAtLocation(declaration.name)); - } - else { - assert.ok(isFunctionDeclaration(statement)); - assert.equal(project.checker.getSymbolOfExpando(statement), undefined); - const symbol = project.checker.getSymbolOfExpando(statement, true); - assert.strictEqual(symbol, project.checker.getSymbolOfDeclaration(statement)); - } - } - assert.deepEqual(results, ["arrow", "expression", undefined, undefined]); - }); - - test("recognizes JavaScript class/object initializers and assignment declarations", () => { - using api = spawnAPI({ - "/tsconfig.json": JSON.stringify({ compilerOptions: { allowJs: true } }), - "/index.js": ` -var fn = function () {}; -var cls = class {}; -var empty = {}; -var populated = { value: 1 }; -/** @type {{}} */ -var annotated = {}; -exports.assigned = function () {}; -`, - }); - const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; - const file = project.program.getSourceFile("/index.js"); - assert.ok(file); - const results: (string | undefined)[] = []; - for (const statement of file.statements) { - if (isVariableStatement(statement)) { - const node = statement.declarationList.declarations[0].initializer; - assert.ok(node); - results.push((project.checker.getSymbolOfExpando(node))?.name); - } - else { - assert.ok(isExpressionStatement(statement)); - const node = statement.expression; - assert.ok(isBinaryExpression(node)); - const symbol = project.checker.getSymbolOfExpando(node.right); - assert.ok(symbol); - assert.equal(symbol.name, "assigned"); - assert.equal(project.checker.getSymbolOfExpando(node.left), undefined); - assert.strictEqual(project.checker.getSymbolOfExpando(node.left, true), symbol); - } - } - assert.deepEqual(results, ["fn", "cls", "empty", undefined, undefined]); - }); -}); - describe("Checker - getRootSymbols", { concurrency }, () => { test("follows synthetic union and mapped properties to their original declarations", () => { using api = spawnAPI({ diff --git a/tsc/internal/api/proto.go b/tsc/internal/api/proto.go index 455de37ce0cec..fcbf35d6d5a57 100644 --- a/tsc/internal/api/proto.go +++ b/tsc/internal/api/proto.go @@ -224,7 +224,6 @@ const ( MethodGetTargetSymbol Method = "getTargetSymbol" MethodGetMergedSymbol Method = "getMergedSymbol" MethodGetRootSymbols Method = "getRootSymbols" - MethodGetSymbolOfExpando Method = "getSymbolOfExpando" MethodGetSymbolOfNode Method = "getSymbolOfNode" MethodGetSymbolOfDeclarationForChecker Method = "getSymbolOfDeclarationForChecker" MethodGetParentOfSymbolForChecker Method = "getParentOfSymbolForChecker" @@ -766,7 +765,6 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetTargetSymbol: unmarshallerFor[CheckerSymbolParams], MethodGetMergedSymbol: unmarshallerFor[CheckerSymbolParams], MethodGetRootSymbols: unmarshallerFor[CheckerSymbolParams], - MethodGetSymbolOfExpando: unmarshallerFor[GetSymbolOfExpandoParams], MethodGetSymbolOfNode: unmarshallerFor[CheckerNodeParams], MethodGetSymbolOfDeclarationForChecker: unmarshallerFor[CheckerNodeParams], MethodGetParentOfSymbolForChecker: unmarshallerFor[CheckerSymbolParams], @@ -1967,13 +1965,6 @@ type CheckerNodeParams struct { Location NodeHandle `json:"location"` } -type GetSymbolOfExpandoParams struct { - Snapshot SnapshotID `json:"snapshot"` - Project project.Handle `json:"project"` - Location NodeHandle `json:"location"` - AllowDeclaration bool `json:"allowDeclaration"` -} - type IsValidPropertyAccessParams struct { Snapshot SnapshotID `json:"snapshot"` Project project.Handle `json:"project"` diff --git a/tsc/internal/api/session.go b/tsc/internal/api/session.go index c068db8dda87e..27bf3b1d6f24c 100644 --- a/tsc/internal/api/session.go +++ b/tsc/internal/api/session.go @@ -1187,8 +1187,6 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetMergedSymbol(ctx, parsed.(*CheckerSymbolParams)) case string(MethodGetRootSymbols): return s.handleGetRootSymbols(ctx, parsed.(*CheckerSymbolParams)) - case string(MethodGetSymbolOfExpando): - return s.handleGetSymbolOfExpando(ctx, parsed.(*GetSymbolOfExpandoParams)) case string(MethodGetSymbolOfNode): return s.handleGetSymbolOfNode(ctx, parsed.(*CheckerNodeParams)) case string(MethodGetSymbolOfDeclarationForChecker): @@ -3985,25 +3983,6 @@ func (s *Session) handleIsOptionalParameter(ctx context.Context, params *Checker return setup.checker.IsOptionalParameter(node), nil } -// @gen-proto-nullable -func (s *Session) handleGetSymbolOfExpando(ctx context.Context, params *GetSymbolOfExpandoParams) (*SymbolResponse, error) { - setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) - if err != nil { - return nil, err - } - defer setup.done() - - node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) - if err != nil { - return nil, err - } - symbol := setup.checker.GetSymbolOfExpando(node, params.AllowDeclaration) - if symbol == nil { - return nil, nil - } - return setup.newSymbolResponse(symbol), nil -} - func (s *Session) handleGetRootSymbols(ctx context.Context, params *CheckerSymbolParams) ([]*SymbolResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) if err != nil { diff --git a/tsc/internal/checker/services.go b/tsc/internal/checker/services.go index a92bd61436cf8..c36f873dfc5e2 100644 --- a/tsc/internal/checker/services.go +++ b/tsc/internal/checker/services.go @@ -162,34 +162,6 @@ func (c *Checker) IsOptionalParameter(node *ast.Node) bool { return c.isOptionalParameter(node) } -// GetSymbolOfExpando finds the declaration whose initializer can acquire expando properties. -// With allowDeclaration, it also accepts the declaration side of assignments and function declarations. -func (c *Checker) GetSymbolOfExpando(node *ast.Node, allowDeclaration bool) *ast.Symbol { - parent := node.Parent - if parent == nil { - return nil - } - var declaration *ast.Node - switch { - case ast.IsVariableDeclaration(parent) && parent.Initializer() == node: - if !ast.IsInJSFile(node) && !(ast.IsVarConstLike(parent) && ast.IsFunctionLikeDeclaration(node)) { - return nil - } - declaration = parent - case ast.IsBinaryExpression(parent): - binary := parent.AsBinaryExpression() - if binary.OperatorToken.Kind == ast.KindEqualsToken && (allowDeclaration || binary.Right == node) { - declaration = parent - } - case allowDeclaration && ast.IsFunctionDeclaration(node): - declaration = node - } - if declaration == nil || !allowDeclaration && !ast.IsExpandoInitializer(declaration, node) { - return nil - } - return c.getSymbolOfNode(declaration) -} - func (c *Checker) GetTypeArgumentsForResolvedSignature(signature *Signature) []*Type { if signature.mapper == nil { return nil