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
1 change: 1 addition & 0 deletions jacodb-ets/src/main/kotlin/org/jacodb/ets/dto/Convert.kt
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,7 @@ fun MethodSignatureDto.toEtsMethodSignature(): EtsMethodSignature {
private fun String?.toEtsWellKnownSymbol(): EtsWellKnownSymbol? = when (this) {
null -> null
"iterator" -> EtsWellKnownSymbol.ITERATOR
"nodeInspectCustom" -> EtsWellKnownSymbol.NODE_INSPECT_CUSTOM
else -> error("Unknown intrinsic symbol key: $this")
}

Expand Down
2 changes: 1 addition & 1 deletion jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Expr.kt
Original file line number Diff line number Diff line change
Expand Up @@ -851,7 +851,7 @@ interface EtsCallExpr : EtsExpr, CommonCallExpr {
}

/** Intrinsic symbol keys selected by language operations, independent of source bindings named Symbol. */
enum class EtsWellKnownSymbol { ITERATOR }
enum class EtsWellKnownSymbol { ITERATOR, NODE_INSPECT_CUSTOM }

data class EtsInstanceCallExpr(
override val instance: EtsLocal,
Expand Down
6 changes: 4 additions & 2 deletions jacodb-ets/ts-frontend/src/dto/signatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,14 @@ export interface ClassSignatureDto {
declaringNamespace?: NamespaceSignatureDto;
}

export type KnownSymbolKey = "iterator" | "nodeInspectCustom";

export interface FieldSignatureDto {
declaringClass: ClassSignatureDto;
name: string;
type: TypeDto;
/** Symbol keys remain distinct from string-named lookalikes. */
wellKnownSymbol?: "iterator";
wellKnownSymbol?: KnownSymbolKey;
}

export interface MethodParameterDto {
Expand All @@ -63,7 +65,7 @@ export interface MethodSignatureDto {
name: string;
parameters: MethodParameterDto[];
returnType: TypeDto;
wellKnownSymbol?: "iterator";
wellKnownSymbol?: KnownSymbolKey;
}

export interface LocalSignatureDto {
Expand Down
53 changes: 50 additions & 3 deletions jacodb-ets/ts-frontend/src/lowering/astUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import * as ts from "typescript";
import { COMPUTED_MEMBER_NAME, CONSTRUCTOR_NAME, DEFAULT_ARK_CLASS_NAME, INSTANCE_INIT_METHOD_NAME, Modifier, PATTERN_PARAMETER_PREFIX, STATIC_INIT_METHOD_NAME } from "../dto/constants";
import { DecoratorDto } from "../dto/model";
import { MethodParameterDto, MethodSignatureDto } from "../dto/signatures";
import { KnownSymbolKey, MethodParameterDto, MethodSignatureDto } from "../dto/signatures";
import { FunctionTypeDto, TypeDto, UNKNOWN_TYPE } from "../dto/types";
import type { LoweringContext } from "./methodBuilder";

Expand All @@ -35,10 +35,10 @@ export function memberName(name: ts.PropertyName | ts.BindingName | ts.EntityNam

export interface ClassMemberKey {
name: string;
wellKnownSymbol?: "iterator";
wellKnownSymbol?: KnownSymbolKey;
}

/** Literal keys and the unshadowed standard-library iterator key. */
/** Literal keys and known Symbol identities. */
export function classMemberKey(name: ts.PropertyName, checker: ts.TypeChecker): ClassMemberKey | undefined {
if (!ts.isComputedPropertyName(name)) return { name: memberName(name) };

Expand All @@ -53,6 +53,10 @@ export function classMemberKey(name: ts.PropertyName, checker: ts.TypeChecker):
&& ts.isNumericLiteral(expression.operand);
if (isNegativeNumber) return literalClassMemberKey(String(-Number(expression.operand.text)));

if (ts.isMethodDeclaration(name.parent) && isNodeInspectCustom(expression, checker)) {
return { name: "nodejs.util.inspect.custom", wellKnownSymbol: "nodeInspectCustom" };
}

const isIteratorAccess = ts.isPropertyAccessExpression(expression)
&& expression.name.text === "iterator"
&& ts.isIdentifier(expression.expression)
Expand All @@ -73,6 +77,49 @@ export function classMemberKey(name: ts.PropertyName, checker: ts.TypeChecker):
return { name: "Symbol.iterator", wellKnownSymbol: "iterator" };
}

function isNodeInspectCustom(expression: ts.Expression, checker: ts.TypeChecker): boolean {
if (!ts.isPropertyAccessExpression(expression) || expression.questionDotToken !== undefined
|| expression.name.text !== "custom") return false;

const inspect = expression.expression;
try {
if (ts.isIdentifier(inspect)) {
const binding = checker.getSymbolAtLocation(inspect)?.declarations?.find(ts.isImportSpecifier);
if (binding === undefined || binding.isTypeOnly) return false;
if ((binding.propertyName ?? binding.name).text !== "inspect") return false;
return isNodeUtilImport(binding.parent.parent, checker);
}

const isNamespaceAccess = ts.isPropertyAccessExpression(inspect) && inspect.questionDotToken === undefined
&& inspect.name.text === "inspect" && ts.isIdentifier(inspect.expression);
if (!isNamespaceAccess) return false;

const binding = checker.getSymbolAtLocation(inspect.expression)?.declarations?.find(ts.isNamespaceImport);
return binding !== undefined && isNodeUtilImport(binding.parent, checker);
} catch {
return false;
}
}

function isNodeUtilImport(clause: ts.ImportClause, checker: ts.TypeChecker): boolean {
const declaration = clause.parent;
if (clause.isTypeOnly || !ts.isImportDeclaration(declaration)) return false;

const specifier = declaration.moduleSpecifier;
if (!ts.isStringLiteral(specifier) || (specifier.text !== "node:util" && specifier.text !== "util")) return false;

// Node itself provides this module when the project omits Node's type
// declarations. A resolved project replacement is outside that contract.
const moduleSymbol = checker.getSymbolAtLocation(specifier);
if (moduleSymbol === undefined) return true;

const moduleDeclarations = moduleSymbol.declarations ?? [];
return moduleDeclarations.length > 0 && moduleDeclarations.every((member) => {
const file = member.getSourceFile();
return file.isDeclarationFile && /(?:^|[/\\])@types[/\\]node[/\\]util\.d\.ts$/.test(file.fileName);
});
}

function literalClassMemberKey(name: string): ClassMemberKey | undefined {
const isLifecycleName = [CONSTRUCTOR_NAME, INSTANCE_INIT_METHOD_NAME, STATIC_INIT_METHOD_NAME].includes(name);
return isLifecycleName ? undefined : { name };
Expand Down
58 changes: 58 additions & 0 deletions jacodb-ets/ts-frontend/src/lowering/exprLowering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,7 @@ export class ExprLowerer {
return { _: "AwaitExpr", arg: this.lowerToImmediate(node.expression) };
}
if (ts.isDeleteExpression(node)) {
this.ensureSupportedSymbolMutation(node.expression);
return { _: "DeleteExpr", arg: this.lowerExpr(node.expression) };
}
if (ts.isVoidExpression(node)) {
Expand Down Expand Up @@ -724,6 +725,7 @@ export class ExprLowerer {

/** Assignment target. */
lowerLValue(node: ts.Expression, laterExpression?: ts.Expression): LValueDto {
this.ensureSupportedSymbolMutation(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 +963,11 @@ export class ExprLowerer {
return rhs;
}

if (opKind === ts.SyntaxKind.EqualsToken && this.isIntrinsicSymbolTarget(targetNode)) {
this.lowerToImmediate(node.right);
throw new LoweringError("mutation of the standard-library Symbol binding is unsupported");
}

let target = this.lowerLValue(node.left, node.right);

if (
Expand Down Expand Up @@ -1231,6 +1238,17 @@ export class ExprLowerer {
}

const receiver = this.snapshotToLocal(callee.expression);
if (node.arguments.length === 0 && this.isStandardIteratorKey(callee.argumentExpression)) {
this.ensureSupportedClassMemberLookup(callee);
return {
_: "InstanceCallExpr",
instance: receiver,
method: this.methodSignatureForCall(node, "Symbol.iterator", UNKNOWN_CLASS_SIGNATURE),
args: [],
wellKnownSymbol: "iterator",
};
}

const key = this.propertyAccessKey(this.lowerToImmediate(callee.argumentExpression), receiver);
this.ensureSupportedClassMemberLookup(callee);
const ptr = this.materialize({
Expand Down Expand Up @@ -1258,6 +1276,46 @@ export class ExprLowerer {
};
}

private ensureSupportedSymbolMutation(target: ts.Expression): void {
if (this.isIntrinsicSymbolTarget(target)) {
throw new LoweringError("mutation of the standard-library Symbol binding is unsupported");
}
}

private isIntrinsicSymbolTarget(expression: ts.Expression): boolean {
const target = unwrapTransparentExpression(expression);
if (ts.isIdentifier(target)) {
return target.text === "Symbol" && this.defaultLibraryGlobalStatus(target) === true;
}

if (!ts.isPropertyAccessExpression(target) && !ts.isElementAccessExpression(target)) return false;

const receiver = unwrapTransparentExpression(target.expression);
if (!ts.isIdentifier(receiver) || receiver.text !== "globalThis") return false;

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 === "Symbol";

const key = unwrapTransparentExpression(target.argumentExpression);
return ts.isStringLiteralLike(key) && key.text === "Symbol";
}

private isStandardIteratorKey(expression: ts.Expression): boolean {
const key = unwrapTransparentExpression(expression);
if (!ts.isPropertyAccessExpression(key) || key.questionDotToken !== undefined) return false;
if (!ts.isIdentifier(key.expression) || key.expression.text !== "Symbol" || key.name.text !== "iterator") {
return false;
}

const propertyDeclarations = this.m.converter.symbolOf(key.name)?.declarations ?? [];
return this.defaultLibraryGlobalStatus(key.expression) === true && propertyDeclarations.length > 0
&& propertyDeclarations.every((declaration) =>
this.m.ctx.isDefaultLibrarySourceFile(declaration.getSourceFile()),
);
}

private lowerCallArguments(node: ts.CallExpression): ValueDto[] {
return this.lowerArguments(node.arguments);
}
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
48 changes: 48 additions & 0 deletions jacodb-ets/ts-frontend/test/explicit-iterator-call.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { lower, methodByName, singleBlockStmts } from "./util";

describe("explicit iterator calls", () => {
it("distinguishes the intrinsic iterator key from a string or a shadowed Symbol", () => {
const { file, diagnostics } = lower(`
export class Source {
[Symbol.iterator]() { return this; }
"Symbol.iterator"() { return 31; }
}
export function intrinsic(source: Source) { return source[Symbol.iterator](); }
export function stringKey(source: Source) { return source["Symbol.iterator"](); }
export function shadowed(source: Source) {
const Symbol = { iterator: "Symbol.iterator" as const };
return source[Symbol.iterator]();
}
`);
const calls = (name: string) => singleBlockStmts(methodByName(file, name)).filter(stmt =>
stmt._ === "AssignStmt" && (stmt.right._ === "InstanceCallExpr" || stmt.right._ === "PtrCallExpr"),
);

expect(diagnostics.messages).toEqual([]);
expect(calls("intrinsic")).toContainEqual(expect.objectContaining({
right: expect.objectContaining({ _: "InstanceCallExpr", wellKnownSymbol: "iterator" }),
}));
for (const name of ["stringKey", "shadowed"]) {
expect(calls(name)).toContainEqual(expect.objectContaining({
right: expect.objectContaining({ _: "PtrCallExpr" }),
}));
}
});
it.each(["Symbol", "globalThis.Symbol", 'globalThis["Symbol"]'])(
"keeps replacement of %s an explicit boundary",
(target) => {
const { diagnostics } = lower(`
export function mutate(replacement: SymbolConstructor) {
${target} = replacement;
return [1][Symbol.iterator]();
}
`);

expect(diagnostics.messages).toContainEqual(expect.stringContaining(
"mutation of the standard-library Symbol binding is unsupported",
));
},
);

});
118 changes: 118 additions & 0 deletions jacodb-ets/ts-frontend/test/node-inspect-class-key.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { describe, expect, it } from "vitest";
import { lower, lowerProject, methodByName, singleBlockStmts } from "./util";

describe("Node inspect custom class methods", () => {
const baseSource = `
import * as nodeUtil from "util";
export class Base {
args = [1];
get body() { return this.args; }
[nodeUtil.inspect.custom]() { return "custom inspection"; }
"nodejs.util.inspect.custom"() { return "ordinary string key"; }
}
`;

it("keeps the custom method separate from a string-named method and retains lifecycle code", () => {
const { file, diagnostics } = lower(baseSource);
const base = file.classes.find(clazz => clazz.signature.name === "Base");
const sameSpelling = base?.methods.filter(method => method.signature.name === "nodejs.util.inspect.custom");

expect(diagnostics.messages).toEqual([]);
expect(sameSpelling?.map(method => method.signature.wellKnownSymbol)).toEqual(["nodeInspectCustom", undefined]);
const instanceInit = methodByName(file, "%instInit");
expect(singleBlockStmts(instanceInit)).toContainEqual(expect.objectContaining({
left: expect.objectContaining({ _: "InstanceFieldRef", field: expect.objectContaining({ name: "args" }) }),
}));
});

it("retains inherited data and getter access and the class value through a re-export", () => {
const { file, diagnostics } = lowerProject({
"/base.ts": baseSource,
"/barrel.ts": "export { Base as Container } from './base';",
"/derived.ts": `
import { Container } from "./barrel";
export class Derived extends Container {}
`,
"/entry.ts": `
import { Container } from "./barrel";
import { Derived } from "./derived";
export function construct() { return new Derived(); }
export function isContainer(value: unknown) { return value instanceof Container; }
export function inherited(value: Derived) { return value.args.length + value.body.length; }
`,
}, "/entry.ts");

expect(diagnostics.messages).toEqual([]);
expect(singleBlockStmts(methodByName(file, "construct"))).toContainEqual(expect.objectContaining({
right: expect.objectContaining({
_: "NewExpr",
classType: expect.objectContaining({
signature: expect.objectContaining({
name: "Derived",
declaringFile: expect.objectContaining({ fileName: "/derived.ts" }),
}),
}),
}),
}));
expect(singleBlockStmts(methodByName(file, "isContainer"))).toContainEqual(expect.objectContaining({
right: expect.objectContaining({
_: "InstanceOfExpr",
checkType: expect.objectContaining({
signature: expect.objectContaining({
name: "Base",
declaringFile: expect.objectContaining({ fileName: "/base.ts" }),
}),
}),
}),
}));
const inherited = singleBlockStmts(methodByName(file, "inherited"));
for (const name of ["args", "body"]) {
expect(inherited).toContainEqual(expect.objectContaining({
right: expect.objectContaining({ _: "InstanceFieldRef", field: expect.objectContaining({ name }) }),
}));
}
});

it("also identifies a named inspect import from node:util", () => {
const { file, diagnostics } = lower(`
import { inspect as display } from "node:util";
export class NodeLike {
static [display.custom]() { return "custom inspection"; }
}
`);
const hook = methodByName(file, "nodejs.util.inspect.custom");

expect(diagnostics.messages).toEqual([]);
expect(hook.signature.wellKnownSymbol).toBe("nodeInspectCustom");
});

it.each([
[
"same-shaped local namespace",
`import * as util from "./replacement";`,
],
[
"local binding",
`const util = { inspect: { custom: "body" } };`,
],
[
"project ambient replacement of util",
`import * as util from "util";`,
],
])("keeps the definition bound for a %s", (_name, importSource) => {
const { file, diagnostics } = lowerProject({
"/entry.ts": `
${importSource}
export class Unresolved {
[util.inspect.custom]() { return "shadow"; }
}
`,
"/replacement.ts": `export const inspect = { custom: "body" };`,
"/replacement-util.d.ts": `declare module "util" { const inspect: { custom: string }; }`,
}, "/entry.ts");
const unresolved = file.classes.find(clazz => clazz.signature.name === "Unresolved");

expect(unresolved?.methods.some(method => method.signature.wellKnownSymbol !== undefined)).toBe(false);
expect(diagnostics.messages).toContainEqual(expect.stringContaining("computed class member needs definition-time key evaluation"));
});
});
Loading