From 7ad2e0071b8bfdfe7c190a36749643f2ee56efa3 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 20:47:34 +0100 Subject: [PATCH 1/2] [TS] Lower intrinsic Boolean calls through truthiness --- .../ts-frontend/src/lowering/exprLowering.ts | 98 ++++++++++------ .../test/boolean-call-binding.spec.ts | 105 ++++++++++++++++++ .../test/set-constructor-binding.spec.ts | 7 +- 3 files changed, 176 insertions(+), 34 deletions(-) create mode 100644 jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts diff --git a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts index 5e316f918..0e9cceec2 100644 --- a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts @@ -72,7 +72,11 @@ import { syntaxKindName, unsupportedValue } from "./diagnostics"; import { MethodContext } from "./methodBuilder"; import { IteratorLowerer, throwRuntimeError } from "./iteratorLowering"; -const SET_STANDARD_LIBRARY_FILE = "lib.es2015.collection.d.ts"; +const PROTECTED_STANDARD_LIBRARY_VALUES = { + Boolean: "lib.es5.d.ts", + Set: "lib.es2015.collection.d.ts", +} as const; +type ProtectedStandardLibraryValue = keyof typeof PROTECTED_STANDARD_LIBRARY_VALUES; const RELATION_BY_SYNTAX: Partial> = { [ts.SyntaxKind.EqualsEqualsToken]: "==", @@ -330,7 +334,7 @@ export class ExprLowerer { return { _: "AwaitExpr", arg: this.lowerToImmediate(node.expression) }; } if (ts.isDeleteExpression(node)) { - this.ensureSupportedSetMutation(node.expression); + this.ensureSupportedIntrinsicMutation(node.expression); return { _: "DeleteExpr", arg: this.lowerExpr(node.expression) }; } if (ts.isVoidExpression(node)) { @@ -728,7 +732,7 @@ export class ExprLowerer { /** Assignment target. */ lowerLValue(node: ts.Expression, laterExpression?: ts.Expression): LValueDto { - this.ensureSupportedSetMutation(node); + this.ensureSupportedIntrinsicMutation(node); if (ts.isIdentifier(node) && this.m.isUninitializedParameter(node)) { throwRuntimeError(this.m, "ReferenceError", `Cannot access '${node.text}' before initialization`); } @@ -966,10 +970,11 @@ export class ExprLowerer { return rhs; } - if (opKind === ts.SyntaxKind.EqualsToken && this.isGlobalSetTarget(targetNode)) { + const unsupportedMutation = this.intrinsicMutationReason(targetNode); + if (opKind === ts.SyntaxKind.EqualsToken && unsupportedMutation !== undefined) { if (ts.isElementAccessExpression(targetNode)) this.lowerToImmediate(targetNode.argumentExpression); this.lowerToImmediate(node.right); - throw new LoweringError("mutation of the standard-library Set binding is unsupported"); + throw new LoweringError(unsupportedMutation); } let target = this.lowerLValue(node.left, node.right); @@ -1215,6 +1220,15 @@ export class ExprLowerer { } if (ts.isIdentifier(callee)) { + const valueDeclaration = this.m.converter.symbolOf(callee)?.valueDeclaration; + if (this.isStandardLibraryValue(callee, valueDeclaration, "Boolean")) { + const args = this.lowerCallArguments(node); + const value = args[0] ?? constant("undefined", UNDEFINED_TYPE); + // Both operations apply the existing JavaScript truthiness semantics without user code. + const negated = this.materialize({ _: "UnopExpr", op: "!", arg: value }, BOOLEAN_TYPE); + return { _: "UnopExpr", op: "!", arg: negated }; + } + const resolved = this.resolveCalleeDeclaration(node); if (resolved === undefined && !isDeclaredLocalValue(this.m, callee)) { // Fully unresolved global callee — static call with the UNKNOWN class. @@ -2148,52 +2162,74 @@ export class ExprLowerer { return UNKNOWN_CLASS_SIGNATURE; } - private ensureSupportedSetMutation(target: ts.Expression): void { - if (this.isGlobalSetTarget(target)) { - throw new LoweringError("mutation of the standard-library Set binding is unsupported"); - } + private ensureSupportedIntrinsicMutation(target: ts.Expression): void { + const reason = this.intrinsicMutationReason(target); + if (reason !== undefined) throw new LoweringError(reason); } - private isGlobalSetTarget(expression: ts.Expression): boolean { + private intrinsicMutationReason(expression: ts.Expression): string | undefined { const target = unwrapTransparentExpression(expression); if (ts.isIdentifier(target)) { - return this.standardLibrarySetSignature(target, this.m.converter.symbolOf(target)) !== undefined; + const name = target.text; + if (name !== "Boolean" && name !== "Set") return undefined; + + const declaration = this.m.converter.symbolOf(target)?.valueDeclaration; + if (this.isStandardLibraryValue(target, declaration, name)) { + return `mutation of the standard-library ${name} binding is unsupported`; + } + return undefined; } - if (!ts.isPropertyAccessExpression(target) && !ts.isElementAccessExpression(target)) return false; + if (!ts.isPropertyAccessExpression(target) && !ts.isElementAccessExpression(target)) return undefined; const receiver = unwrapTransparentExpression(target.expression); - if (!ts.isIdentifier(receiver) || receiver.text !== "globalThis") return false; + if (!ts.isIdentifier(receiver) || receiver.text !== "globalThis") return undefined; // TypeScript represents the intrinsic global object as a symbol without a source declaration. const globalObject = this.m.converter.symbolOf(receiver); - if (globalObject === undefined || (globalObject.declarations?.length ?? 0) !== 0) return false; + if (globalObject === undefined || (globalObject.declarations?.length ?? 0) !== 0) return undefined; + + let name: string; + if (ts.isPropertyAccessExpression(target)) { + name = target.name.text; + } else { + const key = unwrapTransparentExpression(target.argumentExpression); + if (!ts.isStringLiteralLike(key)) { + return "mutation through an unknown intrinsic globalThis property is unsupported"; + } + name = key.text; + } + return name === "Boolean" || name === "Set" + ? `mutation of the standard-library ${name} binding is unsupported` + : undefined; + } + + private isStandardLibraryValue( + target: ts.Expression, + declaration: ts.Declaration | undefined, + name: ProtectedStandardLibraryValue, + ): boolean { + if (!ts.isIdentifier(target) || target.text !== name) return false; - if (ts.isPropertyAccessExpression(target)) return target.name.text === "Set"; + // A callable type or an interface augmentation does not identify a runtime binding. + if (declaration === undefined || !ts.isVariableDeclaration(declaration)) return false; + if (!ts.isIdentifier(declaration.name) || declaration.name.text !== name) return false; - const key = unwrapTransparentExpression(target.argumentExpression); - return !ts.isStringLiteralLike(key) || key.text === "Set"; + const file = declaration.getSourceFile(); + return basename(file.fileName) === PROTECTED_STANDARD_LIBRARY_VALUES[name] + && this.m.ctx.isDefaultLibrarySourceFile(file); } private standardLibrarySetSignature( target: ts.Expression, symbol: ts.Symbol | undefined, ): ClassSignatureDto | undefined { - if (!ts.isIdentifier(target) || target.text !== "Set") return undefined; - - // A constructor-shaped type (or a library interface augmentation) does - // not identify the runtime binding. Check the actual value declaration. - const declaration = symbol?.valueDeclaration; - if (declaration === undefined || !ts.isVariableDeclaration(declaration)) return undefined; - if (!ts.isIdentifier(declaration.name) || declaration.name.text !== "Set") return undefined; + if (!this.isStandardLibraryValue(target, symbol?.valueDeclaration, "Set")) return undefined; - const file = declaration.getSourceFile(); - const fileName = basename(file.fileName); - if (fileName !== SET_STANDARD_LIBRARY_FILE || !this.m.ctx.isDefaultLibrarySourceFile(file)) { - return undefined; - } - - return { name: "Set", declaringFile: { projectName: "", fileName } }; + return { + name: "Set", + declaringFile: { projectName: "", fileName: PROTECTED_STANDARD_LIBRARY_VALUES.Set }, + }; } /** ClassType for `new X(...)`; unrecognized ambient classes keep the %unk file. */ diff --git a/jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts b/jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts new file mode 100644 index 000000000..7927a6179 --- /dev/null +++ b/jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "vitest"; +import { lower, lowerProject, methodByName, singleBlockStmts } from "./util"; + +describe("Boolean call binding", () => { + it.each([ + ["missing", "Boolean()", { _: "Constant", value: "undefined" }], + ["value", "Boolean(number)", { _: "Local", name: "number" }], + ["parentheses", "(Boolean)(number)", { _: "Local", name: "number" }], + ])("uses intrinsic truthiness for %s", (_name, call, firstOperand) => { + const { file, diagnostics } = lower(` + export function convert(number: number) { return ${call}; } + `); + const statements = singleBlockStmts(methodByName(file, "convert")); + const negations = statements + .filter(stmt => stmt._ === "AssignStmt" && stmt.right._ === "UnopExpr") + .map(stmt => stmt._ === "AssignStmt" ? stmt.right : undefined); + + expect(diagnostics.messages).toEqual([]); + expect(negations).toMatchObject([ + { _: "UnopExpr", op: "!", arg: firstOperand }, + { _: "UnopExpr", op: "!", arg: { _: "Local" } }, + ]); + }); + + it.each([ + ["extra arguments", "Boolean(first(), extra())"], + ["fixed spreads", "Boolean(...[first(), extra()] as const)"], + ])("evaluates %s before converting the first argument", (_name, expression) => { + const { file, diagnostics } = lower(` + export function convert(first: () => number, extra: () => number) { + return ${expression}; + } + `); + const statements = singleBlockStmts(methodByName(file, "convert")); + const operands = statements + .filter(stmt => stmt._ === "AssignStmt" && stmt.right._ === "PtrCallExpr") + .map(stmt => stmt._ === "AssignStmt" ? stmt.right : undefined); + const firstNegationIndex = statements.findIndex(stmt => stmt._ === "AssignStmt" && stmt.right._ === "UnopExpr"); + const lastCallIndex = statements.findLastIndex(stmt => stmt._ === "AssignStmt" && stmt.right._ === "PtrCallExpr"); + + expect(diagnostics.messages).toEqual([]); + expect(operands).toMatchObject([{ method: { name: "first" } }, { method: { name: "extra" } }]); + expect(firstNegationIndex).toBeGreaterThan(lastCallIndex); + }); + + it("preserves evaluation of an unsupported spread argument", () => { + const { file, diagnostics } = lower(` + export function convert(collect: () => number[]) { return Boolean(...collect()); } + `); + const statements = singleBlockStmts(methodByName(file, "convert")); + const call = statements.findIndex(stmt => stmt._ === "AssignStmt" && stmt.right._ === "PtrCallExpr"); + const unsupported = statements.findIndex(stmt => stmt._ === "AssignStmt" && stmt.right._ === "UnsupportedValue"); + + expect(diagnostics.messages).toContainEqual(expect.stringContaining("spread argument has no statically known length")); + expect(call).toBeGreaterThanOrEqual(0); + expect(unsupported).toBeGreaterThan(call); + }); + + it("keeps property-selected Boolean on the ordinary receiver path", () => { + const { file, diagnostics } = lower(` + export function convert(receiver: { Boolean: (value: number) => number }) { + return receiver.Boolean(0); + } + `); + + expect(diagnostics.messages).toEqual([]); + expect(singleBlockStmts(methodByName(file, "convert"))).toContainEqual(expect.objectContaining({ + right: expect.objectContaining({ _: "PtrCallExpr", receiver: expect.anything() }), + })); + }); + + it("leaves local and imported Boolean calls on their ordinary callable path", () => { + const { file, diagnostics } = lowerProject({ + "/entry.ts": ` + import { Boolean } from "./local-bool"; + export function imported() { return Boolean(0); } + export function shadowed(Boolean: (value: number) => number) { return Boolean(0); } + `, + "/local-bool.ts": "export function Boolean(value: number) { return value + 31; }", + }, "/entry.ts"); + + expect(diagnostics.messages).toEqual([]); + for (const name of ["imported", "shadowed"]) { + expect(singleBlockStmts(methodByName(file, name))).toContainEqual(expect.objectContaining({ + right: expect.objectContaining({ _: "PtrCallExpr", method: expect.objectContaining({ name: "Boolean" }) }), + })); + } + }); + + it.each(["Boolean", "globalThis.Boolean", 'globalThis["Boolean"]'])( + "stops at a write to %s", + (target) => { + const { diagnostics } = lower(` + export function replace(replacement: BooleanConstructor) { + ${target} = replacement; + return Boolean(1); + } + `); + + expect(diagnostics.messages).toContainEqual(expect.stringContaining( + "mutation of the standard-library Boolean binding is unsupported", + )); + }, + ); +}); diff --git a/jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts b/jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts index a4abf7ce3..01e45b2c7 100644 --- a/jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts +++ b/jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts @@ -107,9 +107,10 @@ describe("Set constructor binding", () => { stmt._ === "UnsupportedStmt" || (stmt._ === "AssignStmt" && stmt.right._ === "UnsupportedValue"), ); - expect(diagnostics.messages).toContainEqual(expect.stringContaining( - "mutation of the standard-library Set binding is unsupported", - )); + const reason = write.includes("[key]") + ? "mutation through an unknown intrinsic globalThis property is unsupported" + : "mutation of the standard-library Set binding is unsupported"; + expect(diagnostics.messages).toContainEqual(expect.stringContaining(reason)); expect(unsupported).toBe(true); }); From 6127cd5370ed42886ca49ab9addb62ed72dd1a57 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 21:04:25 +0100 Subject: [PATCH 2/2] [TS] Keep global mutations and spread calls at explicit boundaries --- .../ts-frontend/src/lowering/exprLowering.ts | 67 ++++++++++++++++--- .../test/boolean-call-binding.spec.ts | 32 ++++++--- 2 files changed, 80 insertions(+), 19 deletions(-) diff --git a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts index 0e9cceec2..6621099f9 100644 --- a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts @@ -78,6 +78,11 @@ const PROTECTED_STANDARD_LIBRARY_VALUES = { } as const; type ProtectedStandardLibraryValue = keyof typeof PROTECTED_STANDARD_LIBRARY_VALUES; +const REFLECTIVE_GLOBAL_MUTATIONS = { + Object: new Set(["assign", "defineProperty", "defineProperties", "setPrototypeOf"]), + Reflect: new Set(["set", "defineProperty", "deleteProperty", "setPrototypeOf"]), +} as const; + const RELATION_BY_SYNTAX: Partial> = { [ts.SyntaxKind.EqualsEqualsToken]: "==", [ts.SyntaxKind.ExclamationEqualsToken]: "!=", @@ -1188,6 +1193,19 @@ export class ExprLowerer { if (ts.isPropertyAccessExpression(callee)) { const methodName = callee.name.text; + const receiver = unwrapTransparentExpression(callee.expression); + const reflectiveOwner = ts.isIdentifier(receiver) && (receiver.text === "Object" || receiver.text === "Reflect") + ? receiver.text + : undefined; + const target = node.arguments[0]; + const mutatesGlobal = reflectiveOwner !== undefined && ts.isIdentifier(receiver) + && REFLECTIVE_GLOBAL_MUTATIONS[reflectiveOwner].has(methodName) + && this.defaultLibraryGlobalStatus(receiver) === true + && target !== undefined && this.isIntrinsicGlobalObject(target); + if (mutatesGlobal) { + this.lowerCallArguments(node); + throw new LoweringError("reflective mutation of the intrinsic globalThis is unsupported"); + } // `this.m()` inside a static method targets a static member of the // current class, just like `C.m()`. @@ -1222,11 +1240,7 @@ export class ExprLowerer { if (ts.isIdentifier(callee)) { const valueDeclaration = this.m.converter.symbolOf(callee)?.valueDeclaration; if (this.isStandardLibraryValue(callee, valueDeclaration, "Boolean")) { - const args = this.lowerCallArguments(node); - const value = args[0] ?? constant("undefined", UNDEFINED_TYPE); - // Both operations apply the existing JavaScript truthiness semantics without user code. - const negated = this.materialize({ _: "UnopExpr", op: "!", arg: value }, BOOLEAN_TYPE); - return { _: "UnopExpr", op: "!", arg: negated }; + return this.lowerNativeBooleanCall(node); } const resolved = this.resolveCalleeDeclaration(node); @@ -1283,6 +1297,21 @@ export class ExprLowerer { }; } + private lowerNativeBooleanCall(node: ts.CallExpression): ValueDto { + const spread = node.arguments.find(ts.isSpreadElement); + if (spread !== undefined) { + const precedingArguments = node.arguments.slice(0, node.arguments.indexOf(spread)); + this.lowerArguments(precedingArguments); + this.lowerToImmediate(spread.expression); + throw new LoweringError("a spread argument to the intrinsic Boolean call requires iterator expansion"); + } + + const args = this.lowerCallArguments(node); + const value = args[0] ?? constant("undefined", UNDEFINED_TYPE); + const negated = this.materialize({ _: "UnopExpr", op: "!", arg: value }, BOOLEAN_TYPE); + return { _: "UnopExpr", op: "!", arg: negated }; + } + private lowerCallArguments(node: ts.CallExpression): ValueDto[] { return this.lowerArguments(node.arguments); } @@ -2182,12 +2211,7 @@ export class ExprLowerer { if (!ts.isPropertyAccessExpression(target) && !ts.isElementAccessExpression(target)) return undefined; - const receiver = unwrapTransparentExpression(target.expression); - if (!ts.isIdentifier(receiver) || receiver.text !== "globalThis") return undefined; - - // TypeScript represents the intrinsic global object as a symbol without a source declaration. - const globalObject = this.m.converter.symbolOf(receiver); - if (globalObject === undefined || (globalObject.declarations?.length ?? 0) !== 0) return undefined; + if (!this.isIntrinsicGlobalObject(target.expression)) return undefined; let name: string; if (ts.isPropertyAccessExpression(target)) { @@ -2204,6 +2228,27 @@ export class ExprLowerer { : undefined; } + private isIntrinsicGlobalObject(expression: ts.Expression): boolean { + let value = unwrapTransparentExpression(expression); + const visited = new Set(); + while (ts.isIdentifier(value)) { + const symbol = this.m.converter.symbolOf(value); + if (symbol === undefined || visited.has(symbol)) return false; + + // TypeScript represents the global object as a symbol without a source declaration. + if (value.text === "globalThis" && (symbol.declarations?.length ?? 0) === 0) return true; + + visited.add(symbol); + const declaration = symbol.valueDeclaration; + if (declaration === undefined || !ts.isVariableDeclaration(declaration) || declaration.initializer === undefined) { + return false; + } + value = unwrapTransparentExpression(declaration.initializer); + } + + return false; + } + private isStandardLibraryValue( target: ts.Expression, declaration: ts.Declaration | undefined, diff --git a/jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts b/jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts index 7927a6179..01cb0c1b9 100644 --- a/jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts +++ b/jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts @@ -22,13 +22,10 @@ describe("Boolean call binding", () => { ]); }); - it.each([ - ["extra arguments", "Boolean(first(), extra())"], - ["fixed spreads", "Boolean(...[first(), extra()] as const)"], - ])("evaluates %s before converting the first argument", (_name, expression) => { + it("evaluates extra arguments before converting the first argument", () => { const { file, diagnostics } = lower(` export function convert(first: () => number, extra: () => number) { - return ${expression}; + return Boolean(first(), extra()); } `); const statements = singleBlockStmts(methodByName(file, "convert")); @@ -43,15 +40,15 @@ describe("Boolean call binding", () => { expect(firstNegationIndex).toBeGreaterThan(lastCallIndex); }); - it("preserves evaluation of an unsupported spread argument", () => { + it.each(["collect()", "[collect()]"])("preserves evaluation before stopping at spread of %s", (spread) => { const { file, diagnostics } = lower(` - export function convert(collect: () => number[]) { return Boolean(...collect()); } + export function convert(collect: () => number[]) { return Boolean(...${spread}); } `); const statements = singleBlockStmts(methodByName(file, "convert")); const call = statements.findIndex(stmt => stmt._ === "AssignStmt" && stmt.right._ === "PtrCallExpr"); const unsupported = statements.findIndex(stmt => stmt._ === "AssignStmt" && stmt.right._ === "UnsupportedValue"); - expect(diagnostics.messages).toContainEqual(expect.stringContaining("spread argument has no statically known length")); + expect(diagnostics.messages).toContainEqual(expect.stringContaining("a spread argument to the intrinsic Boolean call requires iterator expansion")); expect(call).toBeGreaterThanOrEqual(0); expect(unsupported).toBeGreaterThan(call); }); @@ -102,4 +99,23 @@ describe("Boolean call binding", () => { )); }, ); + it.each([ + ["const alias = globalThis; alias.Boolean = replacement", "mutation of the standard-library Boolean binding"], + ["const alias = globalThis; Reflect.set(alias, 'Boolean', replacement)", "reflective mutation"], + ["Object.defineProperty(globalThis, 'Boolean', { value: replacement })", "reflective mutation"], + ])("reports a supported-to-detect global mutation via %s", (mutation, reason) => { + const { file, diagnostics } = lower(` + export function mutate(replacement: BooleanConstructor) { + ${mutation}; + return Boolean(1); + } + `); + const statements = singleBlockStmts(methodByName(file, "mutate")); + + expect(diagnostics.messages).toContainEqual(expect.stringContaining(reason)); + expect(statements).toContainEqual(expect.objectContaining({ + right: expect.objectContaining({ _: "UnsupportedValue" }), + })); + }); + });