Skip to content
Draft
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
76 changes: 67 additions & 9 deletions jacodb-ets/ts-frontend/src/lowering/exprLowering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Record<ts.SyntaxKind, RelationOp>> = {
[ts.SyntaxKind.EqualsEqualsToken]: "==",
[ts.SyntaxKind.ExclamationEqualsToken]: "!=",
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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`);
}
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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;
Expand All @@ -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 }
Expand Down Expand Up @@ -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 };
}
Expand Down
2 changes: 1 addition & 1 deletion jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}
Expand Down
144 changes: 144 additions & 0 deletions jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts
Original file line number Diff line number Diff line change
@@ -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)<number>([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<number>();
}
`);
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<number>();
}
`);

expect(diagnostics.messages).toEqual([]);
});

it("retains native construction when the project augments only the Set interface", () => {
const { file, diagnostics } = lower(`
declare global { interface Set<T> { extraProperty?: T; } }
export function make() { return new Set<number>(); }
`);
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 } },
});
});
});
Loading