Skip to content
Open
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
6 changes: 5 additions & 1 deletion jacodb-ets/ts-frontend/src/lowering/exprLowering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2486,7 +2486,11 @@ function collectCapturedIdentifiers(
}
if (symbol !== undefined && !seen.has(symbol)) {
seen.add(symbol);
if (symbol.declarations?.some(isCapturableDeclaration)) {
// Ambient declarations describe runtime names, not slots in the enclosing lexical environment.
// Resolving a name during closure creation would incorrectly move its read out of the body.
const hasLexicalDeclaration = symbol.declarations?.some((declaration) =>
isCapturableDeclaration(declaration) && !declaration.getSourceFile().isDeclarationFile);
if (hasLexicalDeclaration) {
captures.set(symbol, node);
}
}
Expand Down
22 changes: 22 additions & 0 deletions jacodb-ets/ts-frontend/test/closures.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,28 @@ describe("closures", () => {
);
});

it("leaves ambient globals in the closure body and captures actual shadows", () => {
const { file } = lower(`
export const run = (fail: boolean): number => {
if (fail) throw new Error("failure");
return 1;
};
function makeShadow(Error: (message: string) => string) {
return () => Error("shadow");
}
`);
const ambient = methodByName(file, "%AM0$%dflt");
const shadow = methodByName(file, "%AM1$makeShadow");

expect(ambient.signature.parameters).toEqual([{ name: "fail", type: { _: "BooleanType" } }]);
expect(ambient.body?.cfg.blocks.flatMap((block) => block.stmts)).toContainEqual(
expect.objectContaining({ _: "ThrowStmt" }),
);
expect(shadow.signature.parameters[0]).toMatchObject({
type: { _: "LexicalEnvType", closures: [{ name: "Error" }] },
});
});

it("lowers function expressions and block bodies", () => {
const { file } = lower(`
const f = function (a: number): number {
Expand Down
Loading