From bfcf34a9de8f4d3fdc14ab79198d541b2d278fec Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Fri, 4 Dec 2026 00:05:21 +0100 Subject: [PATCH] Keep ambient globals out of lexical capture lists --- .../ts-frontend/src/lowering/exprLowering.ts | 6 ++++- jacodb-ets/ts-frontend/test/closures.spec.ts | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts index acc70e71e..ec4f23a88 100644 --- a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts @@ -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); } } diff --git a/jacodb-ets/ts-frontend/test/closures.spec.ts b/jacodb-ets/ts-frontend/test/closures.spec.ts index e0f38c3f7..817f05cbd 100644 --- a/jacodb-ets/ts-frontend/test/closures.spec.ts +++ b/jacodb-ets/ts-frontend/test/closures.spec.ts @@ -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 {