diff --git a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts index acc70e71e..5e316f918 100644 --- a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts @@ -28,6 +28,7 @@ * - unresolved callees get a method signature with the UNKNOWN class. */ +import { basename } from "node:path"; import * as ts from "typescript"; import { isStrictMode } from "./strictMode"; import { @@ -71,6 +72,8 @@ 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 RELATION_BY_SYNTAX: Partial> = { [ts.SyntaxKind.EqualsEqualsToken]: "==", [ts.SyntaxKind.ExclamationEqualsToken]: "!=", @@ -327,6 +330,7 @@ export class ExprLowerer { return { _: "AwaitExpr", arg: this.lowerToImmediate(node.expression) }; } if (ts.isDeleteExpression(node)) { + this.ensureSupportedSetMutation(node.expression); return { _: "DeleteExpr", arg: this.lowerExpr(node.expression) }; } if (ts.isVoidExpression(node)) { @@ -724,6 +728,7 @@ export class ExprLowerer { /** Assignment target. */ lowerLValue(node: ts.Expression, laterExpression?: ts.Expression): LValueDto { + this.ensureSupportedSetMutation(node); if (ts.isIdentifier(node) && this.m.isUninitializedParameter(node)) { throwRuntimeError(this.m, "ReferenceError", `Cannot access '${node.text}' before initialization`); } @@ -961,6 +966,12 @@ export class ExprLowerer { return rhs; } + if (opKind === ts.SyntaxKind.EqualsToken && this.isGlobalSetTarget(targetNode)) { + if (ts.isElementAccessExpression(targetNode)) this.lowerToImmediate(targetNode.argumentExpression); + this.lowerToImmediate(node.right); + throw new LoweringError("mutation of the standard-library Set binding is unsupported"); + } + let target = this.lowerLValue(node.left, node.right); if ( @@ -1392,15 +1403,15 @@ export class ExprLowerer { } const target = unwrapTransparentExpression(node.expression); - const declarations = ts.isIdentifier(target) - ? this.m.converter.symbolOf(target)?.declarations - : undefined; + const constructorSymbol = ts.isIdentifier(target) ? this.m.converter.symbolOf(target) : undefined; + const declaredClass = this.standardLibrarySetSignature(target, constructorSymbol) + ?? this.classLikeSignatureOf(node.expression); // Keep the existing static lowering for built-in globals such as Date and Array. // Their symbols may also contain declarations from library augmentations. - const standardLibraryIdentifier = declarations?.some( + const standardLibraryIdentifier = constructorSymbol?.declarations?.some( (declaration) => this.m.ctx.isDefaultLibrarySourceFile(declaration.getSourceFile()), ) === true; - const staticConstructor = this.classLikeSignatureOf(node.expression) !== undefined || standardLibraryIdentifier; + const staticConstructor = declaredClass !== undefined || standardLibraryIdentifier; const inferredType = this.safeTypeOf(node); const lengthType = args.length === 1 ? this.safeTypeOf(args[0]) : undefined; @@ -1426,7 +1437,7 @@ export class ExprLowerer { } const loweredArgs = this.lowerArguments(args); - const classType = staticConstructor ? this.newTargetClassType(node.expression) : inferredType; + const classType = staticConstructor ? this.newTargetClassType(node.expression, declaredClass) : inferredType; const temp = this.m.newTemp(classType); const allocation = constructorValue === undefined ? { _: "NewExpr" as const, classType } @@ -2137,9 +2148,56 @@ export class ExprLowerer { return UNKNOWN_CLASS_SIGNATURE; } - /** ClassType for `new X(...)`; ambient classes get the %unk file (ArkAnalyzer convention). */ - private newTargetClassType(callee: ts.Expression): ClassTypeDto { - const signature = this.classLikeSignatureOf(callee); + private ensureSupportedSetMutation(target: ts.Expression): void { + if (this.isGlobalSetTarget(target)) { + throw new LoweringError("mutation of the standard-library Set binding is unsupported"); + } + } + + private isGlobalSetTarget(expression: ts.Expression): boolean { + const target = unwrapTransparentExpression(expression); + if (ts.isIdentifier(target)) { + return this.standardLibrarySetSignature(target, this.m.converter.symbolOf(target)) !== undefined; + } + + if (!ts.isPropertyAccessExpression(target) && !ts.isElementAccessExpression(target)) return false; + + const receiver = unwrapTransparentExpression(target.expression); + if (!ts.isIdentifier(receiver) || receiver.text !== "globalThis") return false; + + // 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 (ts.isPropertyAccessExpression(target)) return target.name.text === "Set"; + + const key = unwrapTransparentExpression(target.argumentExpression); + return !ts.isStringLiteralLike(key) || key.text === "Set"; + } + + 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; + + 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 } }; + } + + /** ClassType for `new X(...)`; unrecognized ambient classes keep the %unk file. */ + private newTargetClassType(callee: ts.Expression, signature: ClassSignatureDto | undefined): ClassTypeDto { if (signature !== undefined) { return { _: "ClassType", signature }; } diff --git a/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts b/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts index e295a0126..b2764e8b0 100644 --- a/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts @@ -763,7 +763,7 @@ export class StmtLowerer { if (ts.isIdentifier(initializer)) { const type = this.m.converter.typeOfNode(initializer); return { - target: this.m.moduleFieldForIdentifier(initializer) ?? this.m.localForIdentifier(initializer, type), + target: this.expr.lowerLValue(initializer), type, }; } diff --git a/jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts b/jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts new file mode 100644 index 000000000..a4abf7ce3 --- /dev/null +++ b/jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts @@ -0,0 +1,144 @@ +import { describe, expect, it } from "vitest"; +import type { EtsFileDto } from "../src/dto/model"; +import { lower, lowerProject, methodByName, singleBlockStmts } from "./util"; + +const nativeSetSignature = { + name: "Set", + declaringFile: { projectName: "", fileName: "lib.es2015.collection.d.ts" }, +}; + +function constructorStatements(file: EtsFileDto, methodName: string) { + const statements = singleBlockStmts(methodByName(file, methodName)); + const allocation = statements.find(stmt => stmt._ === "AssignStmt" && stmt.right._ === "NewExpr"); + const call = statements.find(stmt => + stmt._ === "AssignStmt" && stmt.right._ === "InstanceCallExpr" && stmt.right.method.name === "constructor", + ); + return { allocation, call }; +} + +describe("Set constructor binding", () => { + it("assigns the native owner to the allocation and constructor while a project class has the same name", () => { + const { file, diagnostics } = lowerProject({ + "/native.ts": ` + export function empty() { return new Set(); } + export function withValues() { return new (Set)([1, 2]); } + `, + "/local-set.ts": "export class Set { marker = 7; }", + }, "/native.ts"); + + expect(diagnostics.messages).toEqual([]); + for (const methodName of ["empty", "withValues"]) { + const { allocation, call } = constructorStatements(file, methodName); + + expect(allocation).toMatchObject({ + right: { _: "NewExpr", classType: { _: "ClassType", signature: nativeSetSignature } }, + }); + expect(call).toMatchObject({ + right: { + _: "InstanceCallExpr", + method: { declaringClass: nativeSetSignature }, + }, + }); + } + }); + + it("retains the project owner for an imported Set and its renamed import", () => { + const { file, diagnostics } = lowerProject({ + "/entry.ts": ` + import { Set, Set as ImportedSet } from "./local-set"; + export function exact() { return new Set(); } + export function alias() { return new ImportedSet(); } + `, + "/local-set.ts": "export class Set { marker = 7; }", + }, "/entry.ts"); + const projectOwner = { name: "Set", declaringFile: { projectName: "proj", fileName: "/local-set.ts" } }; + + expect(diagnostics.messages).toEqual([]); + for (const methodName of ["exact", "alias"]) { + const { allocation, call } = constructorStatements(file, methodName); + + expect(allocation).toMatchObject({ + right: { _: "NewExpr", classType: { _: "ClassType", signature: projectOwner } }, + }); + expect(call).toMatchObject({ + right: { _: "InstanceCallExpr", method: { declaringClass: projectOwner } }, + }); + } + }); + + it("keeps a module-local class and a shadowing parameter on their original construction paths", () => { + const { file, diagnostics } = lower(` + class Set { marker = 4; } + export function declared() { return new Set(); } + export function dynamic(Set: SetConstructor) { return new Set(); } + `); + const declared = constructorStatements(file, "declared"); + const dynamic = constructorStatements(file, "dynamic"); + const projectOwner = { name: "Set", declaringFile: { projectName: "proj", fileName: "test.ts" } }; + + expect(diagnostics.messages).toEqual([]); + expect(declared.allocation).toMatchObject({ + right: { _: "NewExpr", classType: { _: "ClassType", signature: projectOwner } }, + }); + expect(declared.call).toMatchObject({ + right: { _: "InstanceCallExpr", method: { declaringClass: projectOwner } }, + }); + expect(dynamic.allocation).toMatchObject({ + right: { _: "NewExpr", constructorValue: { _: "Local", name: "Set" } }, + }); + }); + + it.each([ + "Set = replacement()", + "globalThis.Set = replacement()", + 'globalThis["Set"] = replacement()', + "globalThis[key] = replacement()", + 'delete globalThis["Set"]', + "for (Set of replacements) {}", + ])("reports overwriting the native binding by %s as unsupported", (write) => { + const { file, diagnostics } = lower(` + export function mutate(replacement: () => SetConstructor, replacements: SetConstructor[], key: string) { + ${write}; + return new Set(); + } + `); + const statements = methodByName(file, "mutate").body!.cfg.blocks.flatMap(block => block.stmts); + const unsupported = statements.some(stmt => + stmt._ === "UnsupportedStmt" || (stmt._ === "AssignStmt" && stmt.right._ === "UnsupportedValue"), + ); + + expect(diagnostics.messages).toContainEqual(expect.stringContaining( + "mutation of the standard-library Set binding is unsupported", + )); + expect(unsupported).toBe(true); + }); + + it("allows writes to a shadowing Set parameter and to a local property named Set", () => { + const { diagnostics } = lower(` + export function shadow(Set: SetConstructor, other: SetConstructor) { + Set = other; + const globalThis = { Set }; + globalThis.Set = other; + return new Set(); + } + `); + + expect(diagnostics.messages).toEqual([]); + }); + + it("retains native construction when the project augments only the Set interface", () => { + const { file, diagnostics } = lower(` + declare global { interface Set { extraProperty?: T; } } + export function make() { return new Set(); } + `); + const { allocation, call } = constructorStatements(file, "make"); + + expect(diagnostics.messages).toEqual([]); + expect(allocation).toMatchObject({ + right: { _: "NewExpr", classType: { _: "ClassType", signature: nativeSetSignature } }, + }); + expect(call).toMatchObject({ + right: { _: "InstanceCallExpr", method: { declaringClass: nativeSetSignature } }, + }); + }); +});