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
149 changes: 115 additions & 34 deletions jacodb-ets/ts-frontend/src/lowering/exprLowering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,16 @@ 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 REFLECTIVE_GLOBAL_MUTATIONS = {
Object: new Set(["assign", "defineProperty", "defineProperties", "setPrototypeOf"]),
Reflect: new Set(["set", "defineProperty", "deleteProperty", "setPrototypeOf"]),
} as const;

const RELATION_BY_SYNTAX: Partial<Record<ts.SyntaxKind, RelationOp>> = {
[ts.SyntaxKind.EqualsEqualsToken]: "==",
Expand Down Expand Up @@ -330,7 +339,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)) {
Expand Down Expand Up @@ -728,7 +737,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`);
}
Expand Down Expand Up @@ -966,10 +975,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);
Expand Down Expand Up @@ -1183,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()`.
Expand Down Expand Up @@ -1215,6 +1238,11 @@ export class ExprLowerer {
}

if (ts.isIdentifier(callee)) {
const valueDeclaration = this.m.converter.symbolOf(callee)?.valueDeclaration;
if (this.isStandardLibraryValue(callee, valueDeclaration, "Boolean")) {
return this.lowerNativeBooleanCall(node);
}

const resolved = this.resolveCalleeDeclaration(node);
if (resolved === undefined && !isDeclaredLocalValue(this.m, callee)) {
// Fully unresolved global callee — static call with the UNKNOWN class.
Expand Down Expand Up @@ -1269,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);
}
Expand Down Expand Up @@ -2148,52 +2191,90 @@ 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 undefined;

if (!this.isIntrinsicGlobalObject(target.expression)) 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;
}

if (!ts.isPropertyAccessExpression(target) && !ts.isElementAccessExpression(target)) return false;
private isIntrinsicGlobalObject(expression: ts.Expression): boolean {
let value = unwrapTransparentExpression(expression);
const visited = new Set<ts.Symbol>();
while (ts.isIdentifier(value)) {
const symbol = this.m.converter.symbolOf(value);
if (symbol === undefined || visited.has(symbol)) return false;

const receiver = unwrapTransparentExpression(target.expression);
if (!ts.isIdentifier(receiver) || receiver.text !== "globalThis") 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;
}

// 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;
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. */
Expand Down
121 changes: 121 additions & 0 deletions jacodb-ets/ts-frontend/test/boolean-call-binding.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
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("evaluates extra arguments before converting the first argument", () => {
const { file, diagnostics } = lower(`
export function convert(first: () => number, extra: () => number) {
return Boolean(first(), extra());
}
`);
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.each(["collect()", "[collect()]"])("preserves evaluation before stopping at spread of %s", (spread) => {
const { file, diagnostics } = lower(`
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("a spread argument to the intrinsic Boolean call requires iterator expansion"));
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",
));
},
);
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" }),
}));
});

});
7 changes: 4 additions & 3 deletions jacodb-ets/ts-frontend/test/set-constructor-binding.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down