Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 27 additions & 16 deletions packages/typescript/src/api/async/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,16 +397,17 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
}

/**
* Looks up a remote declaration's binder symbol. Throws for synthesized or configuration ASTs.
* Looks up a remote node's binder symbol. Throws for synthesized or configuration ASTs.
*/
async getSymbol(declaration: Declaration): Promise<Symbol> {
const file = getRemoteSourceFile(declaration);
getSymbol(node: Declaration): Promise<Symbol>;
getSymbol(node: Node): Promise<Symbol | undefined>;
async getSymbol(node: Node): Promise<Symbol | undefined> {
const file = getRemoteSourceFile(node);
if (!file) throw new Error(`Source file not found for declaration`);
const record = file.symbolCache as CachedSourceFile<Symbol> | undefined;
if (!record) throw new Error(`Cached source file not found for declaration`);
const index = parseNodeHandleFromCompiler(getNodeId(declaration)).index;
const cached = record.symbolsByDeclarationNodeIndex.get(index);
if (cached) return cached;
const index = parseNodeHandleFromCompiler(getNodeId(node)).index;
if (record.symbolsByDeclarationNodeIndex.has(index)) return record.symbolsByDeclarationNodeIndex.get(index);
// @sync-only-start
// return this.fetchDeclarationSymbol(record, index);
// @sync-only-end
Expand All @@ -425,11 +426,15 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
// @sync-skip-block-end
}

private async fetchDeclarationSymbol(record: CachedSourceFile<Symbol>, index: number): Promise<Symbol> {
private async fetchDeclarationSymbol(record: CachedSourceFile<Symbol>, index: number): Promise<Symbol | undefined> {
const data = await this.client.apiRequest("getSymbolOfDeclaration", {
file: record.descriptor,
index,
});
if (!data) {
record.symbolsByDeclarationNodeIndex.set(index, undefined);
return undefined;
}
validateSymbolResponse(data);
const reference = data.reference;
if (reference.kind !== SymbolOwnerKind.File) {
Expand Down Expand Up @@ -972,22 +977,28 @@ function getNodeAPI(node: Node): API<boolean> | undefined {
return api;
}

/** Looks up a remote declaration's binder symbol through its API. Throws for non-remote declarations. */
export async function getSymbol(declaration: Declaration): Promise<Symbol> {
const api = getNodeAPI(declaration);
/** Looks up a remote node's binder symbol through its API. Throws for non-remote nodes. */
export function getSymbol(node: Declaration): Promise<Symbol>;
export function getSymbol(node: Node): Promise<Symbol | undefined>;
export async function getSymbol(node: Node): Promise<Symbol | undefined> {
const api = getNodeAPI(node);
if (!api) throw new Error("Source file not found for declaration");
return api.getSymbol(declaration);
return api.getSymbol(node);
}

// @sync-only-start
// export declare namespace getSymbol {
// function gen(declaration: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
// function gen(node: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
// function gen(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]>;
// }
// getSymbol.gen = function* (declaration: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]> {
// const api = getNodeAPI(declaration);
// function getSymbolGenerator(node: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
// function getSymbolGenerator(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]>;
// function* getSymbolGenerator(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]> {
// const api = getNodeAPI(node);
// if (!api) throw new Error("Source file not found for declaration");
// return yield* api.getSymbol.gen(declaration);
// };
// return yield* api.getSymbol.gen(node);
// }
// getSymbol.gen = getSymbolGenerator;
// @sync-only-end

/** An independently retained source file and its disposable remote-lifetime lease. */
Expand Down
2 changes: 1 addition & 1 deletion packages/typescript/src/api/proto.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export interface APIMethodInfo {
releaseSourceFile: APIMethod<ReleaseSourceFileParams, unknown>;
retainSourceFile: APIMethod<RetainSourceFileParams, RetainSourceFileResponse>;
getCachedSourceFile: APIMethod<GetCachedSourceFileParams, SourceFileResponse>;
getSymbolOfDeclaration: APIMethod<GetSymbolOfDeclarationParams, SymbolResponse>;
getSymbolOfDeclaration: APIMethod<GetSymbolOfDeclarationParams, SymbolResponse | null>;
batchRequests: APIMethod<BatchRequestsParams, BatchRequestsResponse>;
initialize: APIMethod<null, InitializeResponse>;
getDefaultFormatCodeSettings: APIMethod<null, FormatCodeSettings>;
Expand Down
8 changes: 4 additions & 4 deletions packages/typescript/src/api/sourceFileCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ export interface CachedSourceFile<TSymbol> {
refs: Set<string>;
/** Binder symbols owned by this exact source-file incarnation. */
readonly symbolsById: Map<number, TSymbol>;
/** Successfully resolved declaration symbols. */
readonly symbolsByDeclarationNodeIndex: Map<number, TSymbol>;
/** In-flight async declaration symbol lookups. */
readonly declarationSymbolRequests: Map<number, Promise<TSymbol>>;
/** Resolved binder symbol lookups, including nodes without symbols. */
readonly symbolsByDeclarationNodeIndex: Map<number, TSymbol | undefined>;
/** In-flight async binder symbol lookups. */
readonly declarationSymbolRequests: Map<number, Promise<TSymbol | undefined>>;
}

/**
Expand Down
95 changes: 55 additions & 40 deletions packages/typescript/src/api/sync/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,52 +417,57 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
}

/**
* Looks up a remote declaration's binder symbol. Throws for synthesized or configuration ASTs.
* Looks up a remote node's binder symbol. Throws for synthesized or configuration ASTs.
*/
get getSymbol(): {
(declaration: Declaration): Symbol;
gen(declaration: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
(node: Declaration): Symbol;
(node: Node): Symbol | undefined;
gen(node: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
gen(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]>;
} {
const owner = this;
return cacheGeneratorMethod(
owner,
"getSymbol",
function (declaration: Declaration): Symbol {
const file = getRemoteSourceFile(declaration);
if (!file) throw new Error(`Source file not found for declaration`);
const record = file.symbolCache as CachedSourceFile<Symbol> | undefined;
if (!record) throw new Error(`Cached source file not found for declaration`);
const index = parseNodeHandleFromCompiler(getNodeId(declaration)).index;
const cached = record.symbolsByDeclarationNodeIndex.get(index);
if (cached) return cached;
return owner.fetchDeclarationSymbol(record, index);
},
function* (declaration: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]> {
const file = getRemoteSourceFile(declaration);
if (!file) throw new Error(`Source file not found for declaration`);
const record = file.symbolCache as CachedSourceFile<Symbol> | undefined;
if (!record) throw new Error(`Cached source file not found for declaration`);
const index = parseNodeHandleFromCompiler(getNodeId(declaration)).index;
const cached = record.symbolsByDeclarationNodeIndex.get(index);
if (cached) return cached;
return yield* owner.fetchDeclarationSymbol.gen(record, index);
},
);
function getSymbol(node: Declaration): Symbol;
function getSymbol(node: Node): Symbol | undefined;
function getSymbol(node: Node): Symbol | undefined {
const file = getRemoteSourceFile(node);
if (!file) throw new Error(`Source file not found for declaration`);
const record = file.symbolCache as CachedSourceFile<Symbol> | undefined;
if (!record) throw new Error(`Cached source file not found for declaration`);
const index = parseNodeHandleFromCompiler(getNodeId(node)).index;
if (record.symbolsByDeclarationNodeIndex.has(index)) return record.symbolsByDeclarationNodeIndex.get(index);
return owner.fetchDeclarationSymbol(record, index);
}
function gen(node: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
function gen(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]>;
function* gen(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]> {
const file = getRemoteSourceFile(node);
if (!file) throw new Error(`Source file not found for declaration`);
const record = file.symbolCache as CachedSourceFile<Symbol> | undefined;
if (!record) throw new Error(`Cached source file not found for declaration`);
const index = parseNodeHandleFromCompiler(getNodeId(node)).index;
if (record.symbolsByDeclarationNodeIndex.has(index)) return record.symbolsByDeclarationNodeIndex.get(index);
return yield* owner.fetchDeclarationSymbol.gen(record, index);
}
return cacheGeneratorMethod(owner, "getSymbol", getSymbol, gen);
}

private get fetchDeclarationSymbol(): {
(record: CachedSourceFile<Symbol>, index: number): Symbol;
gen(record: CachedSourceFile<Symbol>, index: number): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
(record: CachedSourceFile<Symbol>, index: number): Symbol | undefined;
gen(record: CachedSourceFile<Symbol>, index: number): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]>;
} {
const owner = this;
return cacheGeneratorMethod(
owner,
"fetchDeclarationSymbol",
function (record: CachedSourceFile<Symbol>, index: number): Symbol {
function (record: CachedSourceFile<Symbol>, index: number): Symbol | undefined {
const data = owner.client.apiRequest("getSymbolOfDeclaration", {
file: record.descriptor,
index,
});
if (!data) {
record.symbolsByDeclarationNodeIndex.set(index, undefined);
return undefined;
}
validateSymbolResponse(data);
const reference = data.reference;
if (reference.kind !== SymbolOwnerKind.File) {
Expand All @@ -478,11 +483,15 @@ export class API<FromLSP extends boolean = false> implements FormatDiagnosticsHo
record.symbolsByDeclarationNodeIndex.set(index, symbol);
return symbol;
},
function* (record: CachedSourceFile<Symbol>, index: number): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]> {
function* (record: CachedSourceFile<Symbol>, index: number): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]> {
const data = yield* apiRequest("getSymbolOfDeclaration", {
file: record.descriptor,
index,
});
if (!data) {
record.symbolsByDeclarationNodeIndex.set(index, undefined);
return undefined;
}
validateSymbolResponse(data);
const reference = data.reference;
if (reference.kind !== SymbolOwnerKind.File) {
Expand Down Expand Up @@ -1575,21 +1584,27 @@ function getNodeAPI(node: Node): API<boolean> | undefined {
return api;
}

/** Looks up a remote declaration's binder symbol through its API. Throws for non-remote declarations. */
export function getSymbol(declaration: Declaration): Symbol {
const api = getNodeAPI(declaration);
/** Looks up a remote node's binder symbol through its API. Throws for non-remote nodes. */
export function getSymbol(node: Declaration): Symbol;
export function getSymbol(node: Node): Symbol | undefined;
export function getSymbol(node: Node): Symbol | undefined {
const api = getNodeAPI(node);
if (!api) throw new Error("Source file not found for declaration");
return api.getSymbol(declaration);
return api.getSymbol(node);
}

export declare namespace getSymbol {
function gen(declaration: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
function gen(node: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
function gen(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]>;
}
getSymbol.gen = function* (declaration: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]> {
const api = getNodeAPI(declaration);
function getSymbolGenerator(node: Declaration): Generator<ProtocolRequest, Symbol, ProtocolResponse["result"]>;
function getSymbolGenerator(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]>;
function* getSymbolGenerator(node: Node): Generator<ProtocolRequest, Symbol | undefined, ProtocolResponse["result"]> {
const api = getNodeAPI(node);
if (!api) throw new Error("Source file not found for declaration");
return yield* api.getSymbol.gen(declaration);
};
return yield* api.getSymbol.gen(node);
}
getSymbol.gen = getSymbolGenerator;

/** An independently retained source file and its disposable remote-lifetime lease. */
export class RetainedSourceFile {
Expand Down
2 changes: 1 addition & 1 deletion packages/typescript/src/ast/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export function hasObjectAssignmentInitializer(node: Node): node is ObjectAssign
return "objectAssignmentInitializer" in node;
}

export function isExternalModule(file: SourceFile): boolean {
export function isExternalModule(file: SourceFile): file is SourceFile & Declaration {
return file.externalModuleIndicator !== undefined;
}

Expand Down
25 changes: 25 additions & 0 deletions packages/typescript/test/async/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
isClassDeclaration,
isConstructorDeclaration,
isExpressionStatement,
isExternalModule,
isFunctionDeclaration,
isIdentifier,
isImportDeclaration,
Expand Down Expand Up @@ -920,6 +921,30 @@ describe("API", { concurrency }, () => {
assert.equal("getSymbol" in declaration, false);
});

test("getSymbol accepts arbitrary nodes and narrows external module symbols", async () => {
await using api = spawnAPI();
await using module = await api.createSourceFile("/module.ts", "export function present() {}");
await using script = await api.createSourceFile("/script.ts", "function present() {}");
const declaration = cast(module.sourceFile.statements[0], isFunctionDeclaration);
const node: Node = declaration;
const symbol = await getSymbol(declaration);
assert.equal(symbol.name, "present");
assert.strictEqual(await getSymbol(node), symbol);
assert.strictEqual(await api.getSymbol(node), symbol);
assert.equal((await api.getSymbol(declaration)).name, "present");

assert.equal(await getSymbol(declaration.body!), undefined);
assert.equal(await api.getSymbol(declaration.body!), undefined);
assert.equal(await getSymbol(script.sourceFile), undefined);
assert.equal(await api.getSymbol(script.sourceFile), undefined);

assert.ok(isExternalModule(module.sourceFile));
const moduleSymbol = await getSymbol(module.sourceFile);
assert.ok(moduleSymbol.name);
assert.equal((await api.getSymbol(module.sourceFile)).name, moduleSymbol.name);
assert.strictEqual(await api.getSymbol(module.sourceFile), moduleSymbol);
});

test("source files own separate declaration result and request caches", async () => {
await using api = spawnAPI();
await using lease = await api.createSourceFile("/symbols.ts", "function present() {}");
Expand Down
14 changes: 13 additions & 1 deletion packages/typescript/test/sync/api-generators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,14 +479,26 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () =>
});

test("looks up binder symbols through standalone and API generators", () => {
using api = spawnAPI();
using api = spawnAPI({}, { collectTiming: true });
using lease = api.createSourceFile("/symbols.ts", "function present() {}");
const declaration = cast(lease.sourceFile.statements[0], isFunctionDeclaration);
const [symbol] = api.batch(getSymbol.gen(declaration));
assert.ok(symbol);
assert.equal(symbol.name, "present");
const [cached] = api.batch(api.getSymbol.gen(declaration));
assert.strictEqual(cached, symbol);
const node: Node = declaration;
const [fromNode] = api.batch(getSymbol.gen(node));
assert.strictEqual(fromNode, symbol);

api.resetTimingInfo();
const [missing] = api.batch(getSymbol.gen(declaration.body!));
assert.equal(missing, undefined);
const [cachedMissing] = api.batch(api.getSymbol.gen(declaration.body!));
assert.equal(cachedMissing, undefined);
assert.equal(api.getSymbol(declaration.body!), undefined);
assert.equal(api.getTimingInfo().totals.requestCount, 1);

const clone = cloneNode(declaration);
assert.throws(() => api.batch(getSymbol.gen(clone)), /Source file not found/);
assert.throws(() => api.batch(api.getSymbol.gen(clone)), /Source file not found/);
Expand Down
25 changes: 25 additions & 0 deletions packages/typescript/test/sync/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
isClassDeclaration,
isConstructorDeclaration,
isExpressionStatement,
isExternalModule,
isFunctionDeclaration,
isIdentifier,
isImportDeclaration,
Expand Down Expand Up @@ -909,6 +910,30 @@ describe("API", { concurrency }, () => {
assert.equal("getSymbol" in declaration, false);
});

test("getSymbol accepts arbitrary nodes and narrows external module symbols", () => {
using api = spawnAPI();
using module = api.createSourceFile("/module.ts", "export function present() {}");
using script = api.createSourceFile("/script.ts", "function present() {}");
const declaration = cast(module.sourceFile.statements[0], isFunctionDeclaration);
const node: Node = declaration;
const symbol = getSymbol(declaration);
assert.equal(symbol.name, "present");
assert.strictEqual(getSymbol(node), symbol);
assert.strictEqual(api.getSymbol(node), symbol);
assert.equal((api.getSymbol(declaration)).name, "present");

assert.equal(getSymbol(declaration.body!), undefined);
assert.equal(api.getSymbol(declaration.body!), undefined);
assert.equal(getSymbol(script.sourceFile), undefined);
assert.equal(api.getSymbol(script.sourceFile), undefined);

assert.ok(isExternalModule(module.sourceFile));
const moduleSymbol = getSymbol(module.sourceFile);
assert.ok(moduleSymbol.name);
assert.equal((api.getSymbol(module.sourceFile)).name, moduleSymbol.name);
assert.strictEqual(api.getSymbol(module.sourceFile), moduleSymbol);
});

test("source files own separate declaration result and request caches", () => {
using api = spawnAPI();
using lease = api.createSourceFile("/symbols.ts", "function present() {}");
Expand Down
Loading