From 6edf4f787494b2929826b2e1d3b002f4ec1cbc0e Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 20:10:36 +0100 Subject: [PATCH 1/2] [TS] Lower object literal methods and preserve shared mutable captures --- .../kotlin/org/jacodb/ets/model/Method.kt | 3 + .../kotlin/org/jacodb/ets/model/Modifiers.kt | 3 +- .../org/jacodb/ets/test/EtsTsFrontendTest.kt | 17 ++- jacodb-ets/ts-frontend/src/dto/constants.ts | 1 + .../ts-frontend/src/lowering/diagnostics.ts | 3 + .../ts-frontend/src/lowering/exprLowering.ts | 111 ++++++++++++---- .../ts-frontend/src/lowering/methodBuilder.ts | 43 +++++- .../src/lowering/mutableCaptures.ts | 97 ++++++++++++++ .../ts-frontend/src/lowering/stmtLowering.ts | 12 +- jacodb-ets/ts-frontend/test/closures.spec.ts | 43 +++++- jacodb-ets/ts-frontend/test/corpus.spec.ts | 21 --- .../ts-frontend/test/export-default.spec.ts | 11 +- .../ts-frontend/test/object-accessors.spec.ts | 44 +------ .../ts-frontend/test/object-methods.spec.ts | 124 ++++++++++++++++++ jacodb-ets/ts-frontend/test/object-runtime.ts | 25 +++- .../ts-frontend/test/strictMode.spec.ts | 14 +- 16 files changed, 446 insertions(+), 126 deletions(-) create mode 100644 jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts create mode 100644 jacodb-ets/ts-frontend/test/object-methods.spec.ts diff --git a/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Method.kt b/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Method.kt index 3378de4ec..f8b9d539b 100644 --- a/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Method.kt +++ b/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Method.kt @@ -24,6 +24,9 @@ interface EtsMethod : Base, CommonMethod { val signature: EtsMethodSignature val typeParameters: List + val isObjectLiteralMethod: Boolean + get() = hasModifier(EtsModifier.OBJECT_LITERAL_METHOD) + /** Null preserves unknown strictness for legacy or synthetic methods. */ val isStrictMode: Boolean? get() = null diff --git a/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Modifiers.kt b/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Modifiers.kt index 88b38e07f..959157e2b 100644 --- a/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Modifiers.kt +++ b/jacodb-ets/src/main/kotlin/org/jacodb/ets/model/Modifiers.kt @@ -31,7 +31,8 @@ enum class EtsModifier(val value: Int, val string: String) { READONLY(value = 1 shl 11, string = "readonly"), OUT(value = 1 shl 12, string = "out"), OVERRIDE(value = 1 shl 13, string = "override"), - DECLARE(value = 1 shl 14, string = "declare"); + DECLARE(value = 1 shl 14, string = "declare"), + OBJECT_LITERAL_METHOD(value = 1 shl 15, string = "object-literal-method"), } interface WithModifiers { diff --git a/jacodb-ets/src/test/kotlin/org/jacodb/ets/test/EtsTsFrontendTest.kt b/jacodb-ets/src/test/kotlin/org/jacodb/ets/test/EtsTsFrontendTest.kt index 7e11b6ab8..f1e889288 100644 --- a/jacodb-ets/src/test/kotlin/org/jacodb/ets/test/EtsTsFrontendTest.kt +++ b/jacodb-ets/src/test/kotlin/org/jacodb/ets/test/EtsTsFrontendTest.kt @@ -592,17 +592,24 @@ class EtsTsFrontendTest { } @Test - fun `named object method is unsupported before allocation through JSON conversion`() { + fun `named object method retains its callable own property through JSON conversion`() { val dto = runFrontend("export function value() { return { x: 1, method() { return this.x; } }; }") val serialized = Json { serializersModule = dtoModule }.encodeToString(dto) val roundTripped = EtsFileDto.loadFromJson(serialized) val stmts = roundTripped.classes.single { it.signature.name == DEFAULT_ARK_CLASS_NAME } .methods.single { it.signature.name == "value" }.body!!.cfg.blocks.flatMap { it.stmts } - assertTrue(stmts.filterIsInstance().any { it.right is RawValueDto }) - assertTrue(stmts.filterIsInstance().none { it.right is NewExprDto }) - assertTrue(stmts.none { it is DefineDataPropertyStmtDto }) - assertTrue(roundTripped.classes.none { it.signature.name.startsWith("%AC") }) + assertTrue(stmts.filterIsInstance().none { it.right is RawValueDto }) + assertTrue(stmts.filterIsInstance().any { it.right is NewExprDto }) + val property = stmts.filterIsInstance() + .single { (it.key as? ConstantDto)?.value == "method" } + val storedMethod = assertIs(property.value) + val storedType = assertIs(storedMethod.type) + val owner = roundTripped.toEtsFile().classes.single { it.name == DEFAULT_ARK_CLASS_NAME } + val lifted = owner.methods.single { it.name == storedType.signature.name } + + assertTrue(lifted.isObjectLiteralMethod) + assertTrue(lifted.parameters.single().type is EtsLexicalEnvType) } @Test diff --git a/jacodb-ets/ts-frontend/src/dto/constants.ts b/jacodb-ets/ts-frontend/src/dto/constants.ts index d87f7d8e7..658daad7e 100644 --- a/jacodb-ets/ts-frontend/src/dto/constants.ts +++ b/jacodb-ets/ts-frontend/src/dto/constants.ts @@ -67,6 +67,7 @@ export const Modifier = { OUT: 1 << 12, OVERRIDE: 1 << 13, DECLARE: 1 << 14, + OBJECT_LITERAL_METHOD: 1 << 15, } as const; export type ModifierName = keyof typeof Modifier; diff --git a/jacodb-ets/ts-frontend/src/lowering/diagnostics.ts b/jacodb-ets/ts-frontend/src/lowering/diagnostics.ts index 2da288b8b..ed59ee702 100644 --- a/jacodb-ets/ts-frontend/src/lowering/diagnostics.ts +++ b/jacodb-ets/ts-frontend/src/lowering/diagnostics.ts @@ -68,6 +68,9 @@ export function syntaxKindName(kind: ts.SyntaxKind): string { return SYNTAX_KIND_NAMES[kind] ?? ts.SyntaxKind[kind] ?? String(kind); } +/** Signals that a source construct must fall back to an unsupported IR node. */ +export class LoweringError extends Error {} + function snippet(node: ts.Node): string { try { return node.getText().slice(0, 200); diff --git a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts index acc70e71e..efb348ee5 100644 --- a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts @@ -35,6 +35,7 @@ import { ANONYMOUS_METHOD_PREFIX, ClassCategory, CONSTRUCTOR_NAME, + Modifier, PATTERN_PARAMETER_PREFIX, } from "../dto/constants"; import { FieldDto } from "../dto/model"; @@ -67,7 +68,7 @@ import { StaticFieldRefDto, ValueDto, } from "../dto/values"; -import { syntaxKindName, unsupportedValue } from "./diagnostics"; +import { LoweringError, syntaxKindName, unsupportedStmt, unsupportedValue } from "./diagnostics"; import { MethodContext } from "./methodBuilder"; import { IteratorLowerer, throwRuntimeError } from "./iteratorLowering"; @@ -120,8 +121,10 @@ const COMPOUND_ASSIGN_BY_SYNTAX: Partial> = { [ts.SyntaxKind.QuestionQuestionEqualsToken]: "??", }; -/** Thrown internally for constructs the current milestone cannot lower; callers degrade to Raw*. */ -export class LoweringError extends Error {} +export { LoweringError } from "./diagnostics"; + +type LiftedFunction = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration + | ts.GetAccessorDeclaration | ts.MethodDeclaration; /** Lowers the body of a nested function (closure / object-literal method) into a fresh MethodContext. */ export type FunctionBodyLowerer = ( @@ -1752,7 +1755,7 @@ export class ExprLowerer { return this.lowerClosure(node); } - private lowerClosure(node: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | ts.GetAccessorDeclaration): LocalDto { + private lowerClosure(node: LiftedFunction): LocalDto { if (this.lowerFunctionBody === undefined) { throw new LoweringError("closure in a context without a body lowerer"); } @@ -1773,7 +1776,9 @@ export class ExprLowerer { const { parameters, prologueParams } = buildParameters(this.m.ctx, node); const returnType = returnTypeOf(this.m.ctx, node); const baseSignature: MethodSignatureDto = { declaringClass, name, parameters, returnType }; - const capturedIdentifiers = collectCapturedIdentifiers(node, this.m.checker); + const objectMethod = ts.isMethodDeclaration(node); + const unsupportedBody = objectMethod ? unsupportedObjectMethodBody(node, this.m.checker) : undefined; + const capturedIdentifiers = unsupportedBody === undefined ? collectCapturedIdentifiers(node, this.m.checker) : []; const capturesUninitializedParameter = capturedIdentifiers.some((identifier) => this.m.isUninitializedParameter(identifier), ); @@ -1793,7 +1798,9 @@ export class ExprLowerer { let environment: | { name: string; type: Extract } | undefined; - if (captures.length > 0 || lexicalThis !== undefined) { + // Every evaluation of a method definition creates a function, even + // when there are no captured values to put in its environment. + if (objectMethod || captures.length > 0 || lexicalThis !== undefined) { const capturedLocals = captures.map((capture) => ({ name: capture.outerLocal.name, type: capture.outerLocal.type, @@ -1825,18 +1832,24 @@ export class ExprLowerer { name, ts.isArrowFunction(node) && this.m.isStaticMethod, ); - this.lowerFunctionBody(closureContext, node.body, (afterParameter) => { - if (environment === undefined) { - closureContext.emitPrologue(prologueParams, afterParameter); - } else { - closureContext.emitClosurePrologue( - environment.name, environment.type, captures, prologueParams, afterParameter, lexicalThis, - ); - } - }); + if (unsupportedBody !== undefined) { + this.m.diagnostics.warn(node, unsupportedBody); + closureContext.withOrigin(node, () => closureContext.cfg.emit(unsupportedStmt(node))); + } else { + this.lowerFunctionBody(closureContext, node.body, (afterParameter) => { + if (environment === undefined) { + closureContext.emitPrologue(prologueParams, afterParameter); + } else { + closureContext.emitClosurePrologue( + environment.name, environment.type, captures, prologueParams, afterParameter, lexicalThis, + ); + } + }); + } + const modifiers = modifiersOf(node) | (objectMethod ? Modifier.OBJECT_LITERAL_METHOD : 0); registry.methods.push({ signature, - modifiers: modifiersOf(node), + modifiers, decorators: [], isStrictMode: isStrictMode(node), body: closureContext.build(), @@ -1853,11 +1866,6 @@ export class ExprLowerer { if (this.lowerFunctionBody === undefined) { throw new LoweringError("object literal in a context without a body lowerer"); } - const hasUnmaterializedMethod = node.properties.some(ts.isMethodDeclaration); - if (hasUnmaterializedMethod) { - throw new LoweringError("object literal method needs a per-evaluation callable own property"); - } - const registry = this.m.ctx.anonymous; const name = `${ANONYMOUS_CLASS_PREFIX}${registry.nextClassId++}$${this.m.methodName}`; const signature: ClassSignatureDto = { @@ -1905,12 +1913,16 @@ export class ExprLowerer { excludedKeys: [], throwOnNullishSource: false, }); - } else if (ts.isGetAccessorDeclaration(property)) { + } else if (ts.isGetAccessorDeclaration(property) || ts.isMethodDeclaration(property)) { const key = ts.isComputedPropertyName(property.name) ? this.lowerPropertyKey(property.name.expression) : constant(memberName(property.name), STRING_TYPE); - const getter = this.lowerClosure(property); - this.m.cfg.emit({ _: "DefineAccessorStmt", target: temp, key, getter }); + const callable = this.lowerClosure(property); + if (ts.isMethodDeclaration(property)) { + this.m.cfg.emit({ _: "DefineDataPropertyStmt", target: temp, key, value: callable }); + } else { + this.m.cfg.emit({ _: "DefineAccessorStmt", target: temp, key, getter: callable }); + } } else { // Setters remain separately unsupported. throw new LoweringError(`object literal member: ${syntaxKindName(property.kind)}`); @@ -2257,6 +2269,55 @@ function numericConstantText(node: ts.NumericLiteral): string { return Number.isFinite(Number(node.text)) ? node.text : node.getText(); } +function unsupportedObjectMethodBody( + method: ts.MethodDeclaration, + checker: ts.TypeChecker, +): string | undefined { + if (method.asteriskToken !== undefined) return "object literal generator method calls are not represented in EtsIR"; + + const pending: ts.Node[] = [...method.parameters]; + if (method.body !== undefined) pending.push(method.body); + while (pending.length > 0) { + const node = pending.pop()!; + if (ts.isTypeNode(node)) continue; + if (node.kind === ts.SyntaxKind.SuperKeyword) { + return "object literal method requires [[HomeObject]] for super"; + } + if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.NewKeyword) { + return "object literal method new.target is not represented in EtsIR"; + } + if (ts.isIdentifier(node) && node.text === "arguments") { + const parent = node.parent; + const propertyName = (ts.isPropertyAccessExpression(parent) || ts.isPropertyAssignment(parent)) + && parent.name === node; + if (!propertyName && checker.getSymbolAtLocation(node)?.declarations === undefined) { + return "object literal method arguments object is not represented in EtsIR"; + } + } + + // Arrows inherit these bindings from the method. Other functions have + // independent bodies, but their computed keys run in this lexical scope. + if (ts.isFunctionLike(node) && !ts.isArrowFunction(node)) { + const name = node.name; + if (name !== undefined && ts.isComputedPropertyName(name)) pending.push(name.expression); + continue; + } + if (ts.isClassLike(node)) { + for (const clause of node.heritageClauses ?? []) { + for (const type of clause.types) pending.push(type.expression); + } + for (const member of node.members) { + const name = member.name; + if (name !== undefined && ts.isComputedPropertyName(name)) pending.push(name.expression); + } + continue; + } + + ts.forEachChild(node, (child) => { pending.push(child); }); + } + return undefined; +} + /** Nested arrows share the receiver; ordinary functions and class members introduce their own. */ function usesLexicalThis(arrow: ts.ArrowFunction): boolean { let found = false; @@ -2446,7 +2507,7 @@ function sameBinding( * are excluded. */ function collectCapturedIdentifiers( - closure: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | ts.GetAccessorDeclaration, + closure: LiftedFunction, checker: ts.TypeChecker, ): ts.Identifier[] { if (closure.body === undefined) return []; diff --git a/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts b/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts index f461fe685..9d9ac863a 100644 --- a/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts +++ b/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts @@ -18,13 +18,13 @@ import * as ts from "typescript"; import { DEFAULT_ARK_CLASS_NAME, FORBIDDEN_LOCAL_PREFIX, TEMP_LOCAL_PREFIX } from "../dto/constants"; import { BodyDto, ClassDto, LocalDeclDto, MethodDto, SourceSpanDto } from "../dto/model"; import { ClassSignatureDto, FieldSignatureDto, FileSignatureDto } from "../dto/signatures"; -import { ClassTypeDto, LexicalEnvTypeDto, TypeDto, UNKNOWN_TYPE } from "../dto/types"; +import { ClassTypeDto, LexicalEnvTypeDto, TypeDto, UNKNOWN_TYPE, VOID_TYPE } from "../dto/types"; import { ClosureFieldRefDto, LocalDto, StaticFieldRefDto, ValueDto } from "../dto/values"; import { TypeConverter } from "../types/convert"; import { scopeFunctionImplementation, scopeFunctionType } from "./astUtils"; import type { BuiltParameters } from "./astUtils"; import { CfgBuilder } from "./cfg"; -import { Diagnostics, syntaxKindName } from "./diagnostics"; +import { Diagnostics, LoweringError, syntaxKindName } from "./diagnostics"; /** * Registry for anonymous methods (`%AM$`, closures) and anonymous @@ -71,6 +71,7 @@ export class MethodContext { private readonly locals = new Map(); private readonly symbolLocals = new Map(); private readonly capturedRefs = new Map(); + private readonly sharedCaptures = new Set(); private readonly localNameCounters = new Map(); private tempCount = 0; private closureEnvCount = 0; @@ -193,10 +194,44 @@ export class MethodContext { return field === undefined ? undefined : { _: "StaticFieldRef", field }; } - /** Captured slot used directly for both reads and writes in a lifted function. */ + planSharedCaptures(symbols: readonly ts.Symbol[]): void { + for (const symbol of symbols) this.sharedCaptures.add(symbol); + } + + initializeSharedCapture(declaration: ts.VariableDeclaration, local: LocalDto): void { + if (!ts.isIdentifier(declaration.name)) return; + const symbol = this.symbolForIdentifier(declaration.name); + if (symbol === undefined || !this.sharedCaptures.has(symbol)) return; + + const type: LexicalEnvTypeDto = { + _: "LexicalEnvType", + method: { declaringClass: this.declaringClass, name: this.methodName, parameters: [], returnType: VOID_TYPE }, + closures: [{ name: local.name, type: local.type }], + }; + const holder = this.newClosureEnvironment(type); + const fresh = this.newClosureEnvironment(type); + + // Reading the unassigned environment materializes a fresh cell; the local + // holding its reference is reused until this declaration executes again. + this.cfg.withOrigin(undefined, () => this.cfg.emit({ _: "AssignStmt", left: holder, right: fresh })); + this.capturedRefs.set(symbol, { + _: "ClosureFieldRef", + base: { name: holder.name, type }, + fieldName: local.name, + type: local.type, + }); + } + + /** Captured slots handle reads and writes in both the declaring and lifted methods. */ capturedRefForIdentifier(node: ts.Identifier): ClosureFieldRefDto | undefined { const symbol = this.symbolForIdentifier(node); - return symbol === undefined ? undefined : this.capturedRefs.get(symbol); + if (symbol === undefined) return undefined; + + const captured = this.capturedRefs.get(symbol); + if (captured === undefined && this.sharedCaptures.has(symbol)) { + throw new LoweringError(`mutable capture of '${node.text}' requires an initialized block-local binding`); + } + return captured; } /** Preserve the original lexical-environment reference for a transitive capture. */ diff --git a/jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts b/jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts new file mode 100644 index 000000000..ccfb824f4 --- /dev/null +++ b/jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts @@ -0,0 +1,97 @@ +import * as ts from "typescript"; +import type { TypeConverter } from "../types/convert"; + +interface LocalBinding { + declaration: ts.VariableDeclaration; + captured: boolean; + capturedBeforeInitialization: boolean; + written: boolean; +} + +/** Finds local lexical bindings that must retain their identity across closure calls. */ +export function mutableCapturedLocals( + statements: readonly ts.Statement[], + converter: TypeConverter, +): ts.Symbol[] { + const bindings = new Map(); + const localNames = new Set(); + const pending: ts.Node[] = [...statements]; + while (pending.length > 0) { + const node = pending.pop()!; + if (ts.isFunctionLike(node) || ts.isClassLike(node) || ts.isTypeNode(node)) continue; + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && initializedBlockLet(node)) { + const symbol = converter.symbolOf(node.name); + if (symbol !== undefined) { + bindings.set(symbol, { + declaration: node, + captured: false, + capturedBeforeInitialization: false, + written: false, + }); + localNames.add(node.name.text); + } + } + ts.forEachChild(node, (child) => { pending.push(child); }); + } + + if (bindings.size === 0) return []; + + const references = statements.map((node: ts.Node) => ({ node, inClosure: false })); + while (references.length > 0) { + const { node, inClosure } = references.pop()!; + if (ts.isTypeNode(node)) continue; + if (ts.isIdentifier(node) && localNames.has(node.text)) { + const symbol = converter.symbolOf(node); + const binding = symbol === undefined ? undefined : bindings.get(symbol); + if (binding !== undefined) { + if (inClosure) { + binding.captured = true; + if (node.end <= binding.declaration.end) binding.capturedBeforeInitialization = true; + } + if (!binding.written) binding.written = assignmentTarget(node); + } + } + + const inNestedFunction = inClosure || ts.isFunctionLike(node); + ts.forEachChild(node, (child) => { references.push({ node: child, inClosure: inNestedFunction }); }); + } + + // Creating a cell before the declaration would also require modeling the TDZ. + return [...bindings.entries()] + .filter(([, binding]) => binding.captured && binding.written && !binding.capturedBeforeInitialization) + .map(([symbol]) => symbol); +} + +function initializedBlockLet(node: ts.VariableDeclaration): boolean { + const list = node.parent; + if (node.initializer === undefined || !ts.isVariableDeclarationList(list)) return false; + + const statement = list.parent; + return (list.flags & ts.NodeFlags.Let) !== 0 + && ts.isVariableStatement(statement) + && ts.isBlock(statement.parent); +} + +function assignmentTarget(identifier: ts.Identifier): boolean { + let target: ts.Node = identifier; + for (;;) { + const parent = target.parent; + const inPattern = (ts.isShorthandPropertyAssignment(parent) && parent.name === target) + || (ts.isPropertyAssignment(parent) && parent.initializer === target) + || ts.isArrayLiteralExpression(parent) || ts.isObjectLiteralExpression(parent) + || ts.isSpreadElement(parent) || ts.isSpreadAssignment(parent); + if (ts.isParenthesizedExpression(parent) || inPattern) { + target = parent; + continue; + } + + if (ts.isBinaryExpression(parent) && parent.left === target) { + const operator = parent.operatorToken.kind; + return operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment; + } + if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) { + return parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken; + } + return (ts.isForInStatement(parent) || ts.isForOfStatement(parent)) && parent.initializer === target; + } +} diff --git a/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts b/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts index e295a0126..14e96cc2a 100644 --- a/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts @@ -32,6 +32,7 @@ import { IteratorLowerer, throwRuntimeError } from "./iteratorLowering"; import { unsupportedStmt } from "./diagnostics"; import { ExprLowerer, LoweringError, arrayElementType, constant } from "./exprLowering"; import { MethodContext } from "./methodBuilder"; +import { mutableCapturedLocals } from "./mutableCaptures"; /** The lowered loop variable of a for-of/for-in statement. */ interface LoopBinding { @@ -66,6 +67,7 @@ export class StmtLowerer { private readonly finallyExceptionTargets: Label[] = []; private readonly catchScopes: CatchContext[] = []; private readonly unsupportedForwardFunctionCaptures = new Set(); + private sharedCapturesPrepared = false; private pendingLabels: readonly string[] = []; constructor( @@ -86,6 +88,11 @@ export class StmtLowerer { } lowerStatements(statements: readonly ts.Statement[]): void { + if (!this.sharedCapturesPrepared) { + this.sharedCapturesPrepared = true; + this.m.planSharedCaptures(mutableCapturedLocals(statements, this.m.converter)); + } + // Function declarations are hoisted in JavaScript, but lowering materializes // their captured values at the creation point: hoisting unconditionally would // snapshot captures BEFORE the captured variables are assigned. Hoist only the @@ -763,7 +770,9 @@ 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.m.capturedRefForIdentifier(initializer) + ?? this.m.moduleFieldForIdentifier(initializer) + ?? this.m.localForIdentifier(initializer, type), type, }; } @@ -1049,6 +1058,7 @@ export class StmtLowerer { if (decl.initializer !== undefined) { const value = this.expr.lowerExpr(decl.initializer); this.m.cfg.emit({ _: "AssignStmt", left: local, right: value }); + if (local._ === "Local") this.m.initializeSharedCapture(decl, local); } } diff --git a/jacodb-ets/ts-frontend/test/closures.spec.ts b/jacodb-ets/ts-frontend/test/closures.spec.ts index e0f38c3f7..8c816b8ae 100644 --- a/jacodb-ets/ts-frontend/test/closures.spec.ts +++ b/jacodb-ets/ts-frontend/test/closures.spec.ts @@ -94,25 +94,34 @@ describe("closures", () => { } `); const closure = methodByName(file, "%AM0$outer"); + const [environment] = closure.signature.parameters; + expect(environment.type._).toBe("LexicalEnvType"); + if (environment.type._ !== "LexicalEnvType") throw new Error("Expected a lexical environment"); + const [cell] = environment.type.closures; expect(closure.signature.parameters).toMatchObject([ { - name: "%closures0", type: { _: "LexicalEnvType", - closures: [{ name: "current", type: { _: "NumberType" } }], + closures: [{ + type: { + _: "LexicalEnvType", + closures: [{ name: "current", type: { _: "NumberType" } }], + }, + }], }, }, { name: "delta", type: { _: "NumberType" } }, ]); const stmts = singleBlockStmts(closure); - expect(stmts.slice(0, 2)).toMatchObject([ - { left: { name: "%closures0" }, right: { _: "ParameterRef", index: 0 } }, + expect(stmts.slice(0, 3)).toMatchObject([ + { left: { name: environment.name }, right: { _: "ParameterRef", index: 0 } }, + { left: { name: cell.name }, right: { _: "ClosureFieldRef", fieldName: cell.name } }, { left: { name: "delta" }, right: { _: "ParameterRef", index: 1 } }, ]); expect(stmts).toContainEqual(expect.objectContaining({ left: expect.objectContaining({ _: "ClosureFieldRef", - base: { name: "%closures0", type: expect.anything() }, + base: { name: cell.name, type: expect.anything() }, fieldName: "current", }), })); @@ -120,11 +129,31 @@ describe("closures", () => { expect(closure.body!.locals).not.toContainEqual(expect.objectContaining({ name: "current" })); const outer = methodByName(file, "outer"); expect(outer.body!.locals).toContainEqual(expect.objectContaining({ - name: "%closures0", - type: expect.objectContaining({ _: "LexicalEnvType" }), + name: cell.name, + type: cell.type, })); }); + it("reports a hoisted mutable capture used before its binding is initialized", () => { + const { file } = lower(` + function outer(): number { + const result = read(); + let value = 1; + value = 2; + function read() { return value; } + return result; + } + `); + const outer = methodByName(file, "outer"); + const statements = singleBlockStmts(outer); + + expect(statements).toContainEqual(expect.objectContaining({ + _: "UnsupportedStmt", + kindName: "FunctionDeclaration", + })); + expect(validateEtsFile(file)).toEqual([]); + }); + it("retains lexical this and attaches lifted methods to the enclosing class", () => { const { file } = lower(` class Counter { diff --git a/jacodb-ets/ts-frontend/test/corpus.spec.ts b/jacodb-ets/ts-frontend/test/corpus.spec.ts index 507a96565..76a4a7f8d 100644 --- a/jacodb-ets/ts-frontend/test/corpus.spec.ts +++ b/jacodb-ets/ts-frontend/test/corpus.spec.ts @@ -7,7 +7,6 @@ import { lower } from "./util"; const FIXTURES_DIR = path.join(__dirname, "fixtures"); const EXPECTED_RAW_FALLBACKS: Record = { "geometry.ts": 6, - "events.js": 1, }; /** Count raw fallback statements/values (any "Unsupported*" discriminator). */ @@ -66,26 +65,6 @@ describe("corpus: realistic TS/JS programs lower cleanly", () => { }), ]; - if (fixture === "events.js") { - const statements = allMethods.flatMap((method) => - method.body?.cfg.blocks.flatMap((block) => block.stmts) ?? [], - ); - - expect(statements).toContainEqual(expect.objectContaining({ - _: "AssignStmt", - right: expect.objectContaining({ - _: "UnsupportedValue", - kindName: "ObjectLiteralExpression", - text: expect.stringContaining("on(name, handler)"), - }), - })); - expect(diagnostics.messages).toEqual([ - expect.stringContaining( - "unsupported expression: object literal method needs a per-evaluation callable own property", - ), - ]); - } - for (const method of allMethods) { if (method.body !== undefined) { const stmts = method.body.cfg.blocks.flatMap((b) => b.stmts); diff --git a/jacodb-ets/ts-frontend/test/export-default.spec.ts b/jacodb-ets/ts-frontend/test/export-default.spec.ts index 2cc589ecc..aa644ca77 100644 --- a/jacodb-ets/ts-frontend/test/export-default.spec.ts +++ b/jacodb-ets/ts-frontend/test/export-default.spec.ts @@ -68,7 +68,7 @@ describe("export default expressions", () => { expect(oracle).toBe("true"); }); - it("marks an object-method default export unsupported while preserving export metadata", () => { + it("initializes a default-exported object with its method as an own property", () => { const source = `export default ({ read() { return this; } });`; const { file, diagnostics } = lower(source); const stmts = defaultMethod(file).body!.cfg.blocks.flatMap((block) => block.stmts); @@ -78,12 +78,11 @@ describe("export default expressions", () => { left: expect.objectContaining({ _: "StaticFieldRef", field: expect.objectContaining({ name: "default" }) }), })); expect(stmts).toContainEqual(expect.objectContaining({ - _: "AssignStmt", - right: expect.objectContaining({ _: "UnsupportedValue" }), + _: "DefineDataPropertyStmt", + key: expect.objectContaining({ _: "Constant", value: "read" }), + value: expect.objectContaining({ _: "Local", type: expect.objectContaining({ _: "FunctionType" }) }), })); - expect(diagnostics.messages).toEqual(expect.arrayContaining([ - expect.stringContaining("object literal method needs a per-evaluation callable own property"), - ])); + expect(diagnostics.messages).toEqual([]); expect(file.exportInfos).toContainEqual(expect.objectContaining({ exportName: "default" })); const moduleUrl = `data:text/javascript,${encodeURIComponent(source)}`; diff --git a/jacodb-ets/ts-frontend/test/object-accessors.spec.ts b/jacodb-ets/ts-frontend/test/object-accessors.spec.ts index 5efe12a00..963d68f0b 100644 --- a/jacodb-ets/ts-frontend/test/object-accessors.spec.ts +++ b/jacodb-ets/ts-frontend/test/object-accessors.spec.ts @@ -101,49 +101,7 @@ describe("object getter descriptors", () => { }); }); -describe("object method materialization boundary", () => { - it.each([ - ["direct and detached receiver", `export function run() { - const object = { method() { return this; } }; - const detached = object.method; - return [object.method(), detached()]; - }`], - ["captured local", `export function run(seed: number) { - return { method(value = seed) { return value + seed; } }; - }`], - ["fresh identity", `export function run() { - const make = () => ({ method() { return 1; } }); - return make().method === make().method; - }`], - ["method after data property", `export function run() { - return { method: 1, method() { return 2; } }; - }`], - ["data property after method", `export function run() { - return { method() { return 1; }, method: 2 }; - }`], - ["method after spread", `export function run(source: object) { - return { ...source, method() { return 1; } }; - }`], - ["spread after method", `export function run(source: object) { - return { method() { return 1; }, ...source }; - }`], - ])("rejects %s before object allocation or member effects", (_scenario, source) => { - const { file, diagnostics } = lower(source); - const stmts = file.classes.flatMap((clazz) => clazz.methods) - .flatMap((method) => method.body?.cfg.blocks.flatMap((block) => block.stmts) ?? []); - - expect(stmts).toContainEqual(expect.objectContaining({ - _: "AssignStmt", - right: expect.objectContaining({ _: "UnsupportedValue" }), - })); - expect(stmts.some((stmt) => stmt._ === "AssignStmt" && stmt.right._ === "NewExpr")).toBe(false); - expect(stmts.some((stmt) => stmt._ === "DefineDataPropertyStmt" || stmt._ === "CopyDataPropertiesStmt")).toBe(false); - expect(diagnostics.messages).toEqual(expect.arrayContaining([ - expect.stringContaining("object literal method needs a per-evaluation callable own property"), - ])); - expect(file.classes.some((clazz) => clazz.signature.name.startsWith("%AC"))).toBe(false); - }); - +describe("object function-valued data properties", () => { it("keeps an ordinary function-valued data property on the supported store path", () => { const { file, diagnostics } = lower(`export function run(seed: number) { return { method: function (value: number) { return value + seed; } }; diff --git a/jacodb-ets/ts-frontend/test/object-methods.spec.ts b/jacodb-ets/ts-frontend/test/object-methods.spec.ts new file mode 100644 index 000000000..471f0cf44 --- /dev/null +++ b/jacodb-ets/ts-frontend/test/object-methods.spec.ts @@ -0,0 +1,124 @@ +import { runInNewContext } from "node:vm"; +import * as ts from "typescript"; +import { describe, expect, it } from "vitest"; +import { Modifier } from "../src/dto/constants"; +import { serializeEtsFile } from "../src/serialize"; +import { executeObjectIr } from "./object-runtime"; +import { lower, methodByName } from "./util"; + +function expectNativeResult(source: string, expected: unknown): void { + const { file, diagnostics } = lower(source); + const { outputText } = ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, + }); + const native = runInNewContext(`${outputText}\nexports.value()`, { exports: {} }); + + expect(diagnostics.messages).toEqual([]); + expect(native).toBe(expected); + expect(executeObjectIr(JSON.parse(serializeEtsFile(file)), "value")).toBe(native); +} + +describe("object literal methods", () => { + it("creates a fresh own function on each evaluation of one method definition", () => { + expectNativeResult(` + export function value() { + let i = 0; + let previous: unknown; + while (i !== 2) { + const current = { method() { return 1; } }; + if (i === 1) return current.method !== previous && current.method === current.method; + previous = current.method; + ++i; + } + return false; + } + `, true); + }); + + it("calls with the selected receiver and shares reassignments with sibling methods", () => { + expectNativeResult(` + export function value() { + let current = 3; + const original = { + base: 2, + method(delta = current) { + current += delta; + return this.base * 10 + current; + }, + read() { return current; }, + }; + const borrowed = { base: 5, method: original.method }; + return original.method(1) * 100 + borrowed.method() + original.read(); + } + `, 2466); + }); + + it("evaluates computed keys in order and allows later stores and spread to overwrite methods", () => { + expectNativeResult(` + export function value() { + let order = 0; + const orderStep = (step: number) => { + order = order * 10 + step; + return "method"; + }; + const source = { method: 4 }; + const first = { + before: orderStep(1), + [orderStep(2)]() { return 5; }, + ...source, + after: orderStep(3), + }; + const second = { ...source, method() { return 8; } }; + const third = { method() { return 1; }, method: 9 }; + return order * 1000 + first.method * 100 + second.method() * 10 + third.method; + } + `, 123489); + }); + + it("retains async and strict metadata and defers the body", () => { + const source = ` + export function value() { + let executions = 0; + const object = { + async method() { + ++executions; + return await 7; + }, + }; + return executions; + } + `; + const { file } = lower(source); + const method = file.classes.flatMap(clazz => clazz.methods).find(candidate => + (candidate.modifiers & Modifier.OBJECT_LITERAL_METHOD) !== 0, + ); + + expect(method).toMatchObject({ isStrictMode: true }); + expect(method!.modifiers & Modifier.ASYNC).toBe(Modifier.ASYNC); + expect(method!.body!.cfg.blocks.flatMap(block => block.stmts)).toContainEqual( + expect.objectContaining({ right: expect.objectContaining({ _: "AwaitExpr" }) }), + ); + expectNativeResult(source, 0); + }); + + it.each([ + ["method() { return () => super.toString(); }", "[[HomeObject]]"], + ["*method() { yield 1; }", "generator method"], + ["method() { return arguments[0]; }", "arguments object"], + ["method() { return new.target; }", "new.target"], + ])("retains the own property and limits invocation for %s", (property, reason) => { + const { file, diagnostics } = lower(`export function value() { return { ${property} }; }`); + const factory = methodByName(file, "value"); + const method = file.classes.flatMap(clazz => clazz.methods).find(candidate => + (candidate.modifiers & Modifier.OBJECT_LITERAL_METHOD) !== 0, + ); + + expect(factory.body!.cfg.blocks.flatMap(block => block.stmts)).toContainEqual( + expect.objectContaining({ _: "DefineDataPropertyStmt" }), + ); + expect(method?.body?.cfg.blocks.flatMap(block => block.stmts)).toContainEqual( + expect.objectContaining({ _: "UnsupportedStmt", kindName: "MethodDeclaration" }), + ); + expect(diagnostics.messages).toContainEqual(expect.stringContaining(reason)); + }); +}); diff --git a/jacodb-ets/ts-frontend/test/object-runtime.ts b/jacodb-ets/ts-frontend/test/object-runtime.ts index 0f8cfa66b..551d5cf03 100644 --- a/jacodb-ets/ts-frontend/test/object-runtime.ts +++ b/jacodb-ets/ts-frontend/test/object-runtime.ts @@ -1,3 +1,4 @@ +import { Modifier } from "../src/dto/constants"; import { EtsFileDto, MethodDto } from "../src/dto/model"; import { LexicalEnvTypeDto } from "../src/dto/types"; import { ClosureFieldRefDto } from "../src/dto/values"; @@ -28,6 +29,11 @@ export function executeObjectIr(file: EtsFileDto, name: string, args: unknown[] const locals = new Map(); const environment = (type: LexicalEnvTypeDto): object => { const slots = new Set(type.closures.map((capture) => capture.name)); + const capturedEnvironments = new Map( + type.closures + .filter((capture) => capture.type._ === "LexicalEnvType") + .map((capture) => [capture.name, locals.get(capture.name)]), + ); const checkSlot = (key: PropertyKey): string => { const name = String(key); if (!slots.has(name)) throw new Error(`undeclared test capture ${name}`); @@ -35,9 +41,14 @@ export function executeObjectIr(file: EtsFileDto, name: string, args: unknown[] }; return new Proxy({}, { - get: (_target, key) => locals.get(checkSlot(key)), + get: (_target, key) => { + const name = checkSlot(key); + return capturedEnvironments.has(name) ? capturedEnvironments.get(name) : locals.get(name); + }, set: (_target, key, value) => { - locals.set(checkSlot(key), value); + const name = checkSlot(key); + const storage = capturedEnvironments.has(name) ? capturedEnvironments : locals; + storage.set(name, value); return true; }, }); @@ -59,6 +70,10 @@ export function executeObjectIr(file: EtsFileDto, name: string, args: unknown[] const read = (value: any): any => { switch (value._) { case "Local": { + if (!locals.has(value.name) && value.type._ === "LexicalEnvType") { + return Object.fromEntries(value.type.closures.map((capture: { name: string }) => + [capture.name, locals.get(capture.name)])); + } if (!locals.has(value.name) && value.type._ === "FunctionType") { const lifted = lookup(value.type.signature); const environmentType = lifted.signature.parameters[0]?.type; @@ -66,10 +81,12 @@ export function executeObjectIr(file: EtsFileDto, name: string, args: unknown[] ? environment(environmentType) : undefined; - locals.set(value.name, function (this: unknown, ...callArgs: unknown[]) { + const callable = function (this: unknown, ...callArgs: unknown[]) { const supplied = lexicalEnvironment === undefined ? callArgs : [lexicalEnvironment, ...callArgs]; return invoke(lifted, supplied, this); - }); + }; + if ((lifted.modifiers & Modifier.OBJECT_LITERAL_METHOD) !== 0) return callable; + locals.set(value.name, callable); } return locals.get(value.name); } diff --git a/jacodb-ets/ts-frontend/test/strictMode.spec.ts b/jacodb-ets/ts-frontend/test/strictMode.spec.ts index a1b172c14..86d4e72e8 100644 --- a/jacodb-ets/ts-frontend/test/strictMode.spec.ts +++ b/jacodb-ets/ts-frontend/test/strictMode.spec.ts @@ -42,7 +42,7 @@ describe("lexical strict-mode metadata", () => { expect(methodByName(ownDirective, "%dflt").isStrictMode).toBe(false); }); - it("keeps an unsupported sloppy object method distinct from strict class code", () => { + it("keeps a sloppy object method distinct from strict class code", () => { const { file, diagnostics } = lower(` function object() { return { sloppy() { return 1; } }; } class Box { @@ -52,16 +52,12 @@ describe("lexical strict-mode metadata", () => { } `); const box = file.classes.find(clazz => clazz.signature.name === "Box")!; + const lifted = file.classes.flatMap(clazz => clazz.methods) + .find(method => method.signature.name.endsWith("$object")); expect(methodByName(file, "object").isStrictMode).toBe(false); - const objectStmts = methodByName(file, "object").body!.cfg.blocks.flatMap((block) => block.stmts); - expect(objectStmts).toContainEqual(expect.objectContaining({ - _: "AssignStmt", - right: expect.objectContaining({ _: "UnsupportedValue", kindName: "ObjectLiteralExpression" }), - })); - expect(diagnostics.messages).toEqual(expect.arrayContaining([ - expect.stringContaining("object literal method needs a per-evaluation callable own property"), - ])); + expect(lifted).toMatchObject({ isStrictMode: false }); + expect(diagnostics.messages).toEqual([]); expect(box.methods.length).toBeGreaterThan(3); expect(box.methods.every(method => method.isStrictMode === true)).toBe(true); }); From a797c89047e88392d4d5bf6063480a7d09cfe843 Mon Sep 17 00:00:00 2001 From: Aleksei Menshutin Date: Wed, 2 Dec 2026 21:57:57 +0100 Subject: [PATCH 2/2] [TS] Preserve live captures of parameters and uninitialized lexical bindings --- .../ts-frontend/src/lowering/astUtils.ts | 13 ++ .../ts-frontend/src/lowering/exprLowering.ts | 15 +- .../ts-frontend/src/lowering/methodBuilder.ts | 64 +++++-- .../src/lowering/mutableCaptures.ts | 166 +++++++++++++++--- .../ts-frontend/src/lowering/stmtLowering.ts | 13 +- .../ts-frontend/test/async-iterator.spec.ts | 4 +- .../ts-frontend/test/object-methods.spec.ts | 68 +++++++ .../ts-frontend/test/object-runtime.spec.ts | 2 +- jacodb-ets/ts-frontend/test/object-runtime.ts | 28 +-- .../ts-frontend/test/state-and-order.spec.ts | 20 +-- 10 files changed, 296 insertions(+), 97 deletions(-) diff --git a/jacodb-ets/ts-frontend/src/lowering/astUtils.ts b/jacodb-ets/ts-frontend/src/lowering/astUtils.ts index 0b1b57ff2..221b4fd5b 100644 --- a/jacodb-ets/ts-frontend/src/lowering/astUtils.ts +++ b/jacodb-ets/ts-frontend/src/lowering/astUtils.ts @@ -503,3 +503,16 @@ export function scopeFunctionType(ctx: LoweringContext, decl: ts.FunctionDeclara } return type; } + +export function unwrapTransparentExpression(node: ts.Expression): ts.Expression { + while ( + ts.isParenthesizedExpression(node) + || ts.isAsExpression(node) + || ts.isTypeAssertionExpression(node) + || ts.isNonNullExpression(node) + || ts.isSatisfiesExpression(node) + ) { + node = node.expression; + } + return node; +} diff --git a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts index efb348ee5..c69f6617c 100644 --- a/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/exprLowering.ts @@ -39,7 +39,7 @@ import { PATTERN_PARAMETER_PREFIX, } from "../dto/constants"; import { FieldDto } from "../dto/model"; -import { bindingIdentifier, buildParameters, BuiltParameters, classLikeDeclarationOf, memberName, modifiersOf, returnTypeOf, unsupportedClassDeclarationReason } from "./astUtils"; +import { bindingIdentifier, buildParameters, BuiltParameters, classLikeDeclarationOf, memberName, modifiersOf, returnTypeOf, unsupportedClassDeclarationReason, unwrapTransparentExpression } from "./astUtils"; import { BinaryOp, RelationOp, UnaryOp } from "../dto/ops"; import { ClassSignatureDto, @@ -2461,19 +2461,6 @@ function containsPossibleSideEffect(node: ts.Node): boolean { /** Erase syntax that leaves an expression's runtime value unchanged. */ -function unwrapTransparentExpression(node: ts.Expression): ts.Expression { - while ( - ts.isParenthesizedExpression(node) - || ts.isAsExpression(node) - || ts.isTypeAssertionExpression(node) - || ts.isNonNullExpression(node) - || ts.isSatisfiesExpression(node) - ) { - node = node.expression; - } - return node; -} - /** Identifier binding written by an assignment or an increment/decrement, if any. */ function assignmentTarget(node: ts.Node): ts.Identifier | undefined { if (ts.isBinaryExpression(node) && ( diff --git a/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts b/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts index 9d9ac863a..945c0ffab 100644 --- a/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts +++ b/jacodb-ets/ts-frontend/src/lowering/methodBuilder.ts @@ -18,13 +18,14 @@ import * as ts from "typescript"; import { DEFAULT_ARK_CLASS_NAME, FORBIDDEN_LOCAL_PREFIX, TEMP_LOCAL_PREFIX } from "../dto/constants"; import { BodyDto, ClassDto, LocalDeclDto, MethodDto, SourceSpanDto } from "../dto/model"; import { ClassSignatureDto, FieldSignatureDto, FileSignatureDto } from "../dto/signatures"; -import { ClassTypeDto, LexicalEnvTypeDto, TypeDto, UNKNOWN_TYPE, VOID_TYPE } from "../dto/types"; +import { ClassTypeDto, LexicalEnvTypeDto, TypeDto, UNDEFINED_TYPE, UNKNOWN_TYPE, VOID_TYPE } from "../dto/types"; import { ClosureFieldRefDto, LocalDto, StaticFieldRefDto, ValueDto } from "../dto/values"; import { TypeConverter } from "../types/convert"; import { scopeFunctionImplementation, scopeFunctionType } from "./astUtils"; import type { BuiltParameters } from "./astUtils"; import { CfgBuilder } from "./cfg"; import { Diagnostics, LoweringError, syntaxKindName } from "./diagnostics"; +import { mutableCapturedParameters, type MutableCapture } from "./mutableCaptures"; /** * Registry for anonymous methods (`%AM$`, closures) and anonymous @@ -71,7 +72,7 @@ export class MethodContext { private readonly locals = new Map(); private readonly symbolLocals = new Map(); private readonly capturedRefs = new Map(); - private readonly sharedCaptures = new Set(); + private readonly sharedCaptures = new Map(); private readonly localNameCounters = new Map(); private tempCount = 0; private closureEnvCount = 0; @@ -194,34 +195,53 @@ export class MethodContext { return field === undefined ? undefined : { _: "StaticFieldRef", field }; } - planSharedCaptures(symbols: readonly ts.Symbol[]): void { - for (const symbol of symbols) this.sharedCaptures.add(symbol); + planSharedCaptures(captures: readonly MutableCapture[]): void { + for (const capture of captures) this.sharedCaptures.set(capture.symbol, capture); } - initializeSharedCapture(declaration: ts.VariableDeclaration, local: LocalDto): void { - if (!ts.isIdentifier(declaration.name)) return; - const symbol = this.symbolForIdentifier(declaration.name); - if (symbol === undefined || !this.sharedCaptures.has(symbol)) return; + initializeSharedCapture(identifier: ts.Identifier, local: LocalDto, hasInitializer: boolean): void { + const symbol = this.symbolForIdentifier(identifier); + if (symbol === undefined || this.sharedCaptures.get(symbol)?.supportsSharedCell !== true) return; + const slotType = hasInitializer ? local.type : UNKNOWN_TYPE; const type: LexicalEnvTypeDto = { _: "LexicalEnvType", method: { declaringClass: this.declaringClass, name: this.methodName, parameters: [], returnType: VOID_TYPE }, - closures: [{ name: local.name, type: local.type }], + closures: [{ name: local.name, type: slotType }], }; const holder = this.newClosureEnvironment(type); const fresh = this.newClosureEnvironment(type); - // Reading the unassigned environment materializes a fresh cell; the local - // holding its reference is reused until this declaration executes again. - this.cfg.withOrigin(undefined, () => this.cfg.emit({ _: "AssignStmt", left: holder, right: fresh })); + // Reading the unassigned environment materializes a fresh cell at the binding's declaration. + this.cfg.withOrigin(undefined, () => { + if (!hasInitializer) { + this.cfg.emit({ + _: "AssignStmt", + left: local, + right: { _: "Constant", type: UNDEFINED_TYPE, value: "undefined" }, + }); + } + this.cfg.emit({ _: "AssignStmt", left: holder, right: fresh }); + }); this.capturedRefs.set(symbol, { _: "ClosureFieldRef", base: { name: holder.name, type }, fieldName: local.name, - type: local.type, + type: slotType, }); } + initializeDeferredSharedCapture(identifier: ts.Identifier, local: LocalDto): ClosureFieldRefDto | undefined { + const symbol = this.symbolForIdentifier(identifier); + if (symbol === undefined) return undefined; + + const capture = this.sharedCaptures.get(symbol); + if (capture?.initializeBeforeValue !== true || !capture.supportsSharedCell) return undefined; + + this.initializeSharedCapture(identifier, local, /* hasInitializer */ false); + return this.capturedRefs.get(symbol); + } + /** Captured slots handle reads and writes in both the declaring and lifted methods. */ capturedRefForIdentifier(node: ts.Identifier): ClosureFieldRefDto | undefined { const symbol = this.symbolForIdentifier(node); @@ -229,7 +249,7 @@ export class MethodContext { const captured = this.capturedRefs.get(symbol); if (captured === undefined && this.sharedCaptures.has(symbol)) { - throw new LoweringError(`mutable capture of '${node.text}' requires an initialized block-local binding`); + throw new LoweringError(`mutable capture of '${node.text}' requires a supported initialized lexical cell`); } return captured; } @@ -243,7 +263,7 @@ export class MethodContext { return { identifier: node, outerLocal: this.getOrCreateLocal(captured.base.name, captured.base.type), - type, + type: captured.type, forwardedFieldName: captured.fieldName, }; } @@ -353,6 +373,10 @@ export class MethodContext { /** Parameter bindings are initially in the temporal dead zone, including patterns. */ private beginParameterInitialization(parameters: BuiltParameters["prologueParams"]): void { + const sourceParameter = parameters[0]?.identifier?.parent ?? parameters[0]?.pattern?.parent; + if (sourceParameter !== undefined && ts.isParameter(sourceParameter)) { + this.planSharedCaptures(mutableCapturedParameters(sourceParameter, this.converter)); + } const addBinding = (name: ts.BindingName): void => { if (ts.isIdentifier(name)) { const symbol = this.symbolForIdentifier(name); @@ -397,7 +421,10 @@ export class MethodContext { right: { _: "ParameterRef", index, type: param.type }, }); afterParameter?.(param, local); - if (param.identifier !== undefined) this.markParameterInitialized(param.identifier); + if (param.identifier !== undefined) { + this.markParameterInitialized(param.identifier); + this.initializeSharedCapture(param.identifier, local, /* hasInitializer */ true); + } }); this.uninitializedParameters.clear(); if (!earlyThis) this.emitThisAssignment(); @@ -477,7 +504,10 @@ export class MethodContext { right: { _: "ParameterRef", index: index + 1, type: param.type }, }); afterParameter?.(param, local); - if (param.identifier !== undefined) this.markParameterInitialized(param.identifier); + if (param.identifier !== undefined) { + this.markParameterInitialized(param.identifier); + this.initializeSharedCapture(param.identifier, local, /* hasInitializer */ true); + } }); this.uninitializedParameters.clear(); if (!earlyThis) this.emitThisAssignment(receiver); diff --git a/jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts b/jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts index ccfb824f4..4ebe82a97 100644 --- a/jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts +++ b/jacodb-ets/ts-frontend/src/lowering/mutableCaptures.ts @@ -1,52 +1,125 @@ import * as ts from "typescript"; import type { TypeConverter } from "../types/convert"; +import { isStrictMode } from "./strictMode"; +import { unwrapTransparentExpression } from "./astUtils"; -interface LocalBinding { - declaration: ts.VariableDeclaration; +export interface MutableCapture { + symbol: ts.Symbol; + supportsSharedCell: boolean; + initializeBeforeValue: boolean; +} + +interface Binding { + declaration: ts.VariableDeclaration | ts.ParameterDeclaration; + identifier: ts.Identifier; + supportsSharedCell: boolean; + deferredInitializer?: ts.Expression; +} + +interface BindingUsage extends Binding { captured: boolean; capturedBeforeInitialization: boolean; + capturedInDeferredInitializer: boolean; written: boolean; } -/** Finds local lexical bindings that must retain their identity across closure calls. */ export function mutableCapturedLocals( statements: readonly ts.Statement[], converter: TypeConverter, -): ts.Symbol[] { - const bindings = new Map(); - const localNames = new Set(); +): MutableCapture[] { + const bindings: Binding[] = []; const pending: ts.Node[] = [...statements]; while (pending.length > 0) { const node = pending.pop()!; if (ts.isFunctionLike(node) || ts.isClassLike(node) || ts.isTypeNode(node)) continue; - if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && initializedBlockLet(node)) { - const symbol = converter.symbolOf(node.name); - if (symbol !== undefined) { - bindings.set(symbol, { - declaration: node, - captured: false, - capturedBeforeInitialization: false, - written: false, - }); - localNames.add(node.name.text); + + if (ts.isVariableDeclaration(node) && isLocalVariable(node)) { + const supportsSharedCell = ts.isIdentifier(node.name) && isBlockLexical(node); + const initializer = node.initializer; + const deferredInitializer = supportsSharedCell && initializer !== undefined && isDeferredInitializer(initializer) + ? initializer + : undefined; + for (const identifier of bindingIdentifiers(node.name)) { + bindings.push({ declaration: node, identifier, supportsSharedCell, deferredInitializer }); } } ts.forEachChild(node, (child) => { pending.push(child); }); } + return analyzeCaptures(statements, bindings, converter); +} + +export function mutableCapturedParameters( + declaration: ts.ParameterDeclaration, + converter: TypeConverter, +): MutableCapture[] { + const owner = declaration.parent; + if (!ts.isFunctionLike(owner) || !("body" in owner) || owner.body === undefined) return []; + + const hasSimpleParameters = owner.parameters.every((parameter) => + ts.isIdentifier(parameter.name) && parameter.initializer === undefined && parameter.dotDotDotToken === undefined, + ); + const usesMappedArguments = !isStrictMode(owner) && hasArgumentsReference(owner.body); + const supportsSharedCell = hasSimpleParameters && !usesMappedArguments; + const bindings = owner.parameters.flatMap((parameter) => + bindingIdentifiers(parameter.name).map((identifier) => ({ + declaration: parameter, identifier, supportsSharedCell, + })), + ); + return analyzeCaptures([...owner.parameters, owner.body], bindings, converter, usesMappedArguments); +} + +function hasArgumentsReference(root: ts.Node): boolean { + const pending = [root]; + while (pending.length > 0) { + const node = pending.pop()!; + if (ts.isIdentifier(node) && node.text === "arguments") return true; + ts.forEachChild(node, (child) => { pending.push(child); }); + } + return false; +} + +function analyzeCaptures( + roots: readonly ts.Node[], + declarations: readonly Binding[], + converter: TypeConverter, + writesThroughArguments: boolean = false, +): MutableCapture[] { + const bindings = new Map(); + const localNames = new Set(); + for (const binding of declarations) { + const symbol = converter.symbolOf(binding.identifier); + if (symbol === undefined) continue; + bindings.set(symbol, { + ...binding, + captured: false, + capturedBeforeInitialization: false, + capturedInDeferredInitializer: false, + written: writesThroughArguments, + }); + localNames.add(binding.identifier.text); + } if (bindings.size === 0) return []; - const references = statements.map((node: ts.Node) => ({ node, inClosure: false })); + const references = roots.map((node) => ({ node, inClosure: false })); while (references.length > 0) { const { node, inClosure } = references.pop()!; if (ts.isTypeNode(node)) continue; + if (ts.isIdentifier(node) && localNames.has(node.text)) { const symbol = converter.symbolOf(node); const binding = symbol === undefined ? undefined : bindings.get(symbol); if (binding !== undefined) { if (inClosure) { binding.captured = true; - if (node.end <= binding.declaration.end) binding.capturedBeforeInitialization = true; + if (node.end <= binding.declaration.end) { + const initializer = binding.deferredInitializer; + if (initializer !== undefined && node.pos >= initializer.pos) { + binding.capturedInDeferredInitializer = true; + } else { + binding.capturedBeforeInitialization = true; + } + } } if (!binding.written) binding.written = assignmentTarget(node); } @@ -56,22 +129,63 @@ export function mutableCapturedLocals( ts.forEachChild(node, (child) => { references.push({ node: child, inClosure: inNestedFunction }); }); } - // Creating a cell before the declaration would also require modeling the TDZ. - return [...bindings.entries()] - .filter(([, binding]) => binding.captured && binding.written && !binding.capturedBeforeInitialization) - .map(([symbol]) => symbol); + return [...bindings.entries()].flatMap(([symbol, binding]) => { + const needsCell = binding.written || binding.capturedBeforeInitialization || binding.capturedInDeferredInitializer; + if (!binding.captured || !needsCell) return []; + + const supportsSharedCell = binding.supportsSharedCell && !binding.capturedBeforeInitialization; + return [{ symbol, supportsSharedCell, initializeBeforeValue: binding.capturedInDeferredInitializer }]; + }); +} + +function bindingIdentifiers(name: ts.BindingName): ts.Identifier[] { + if (ts.isIdentifier(name)) return [name]; + + return name.elements.flatMap((element) => ts.isBindingElement(element) ? bindingIdentifiers(element.name) : []); +} + +function isLocalVariable(declaration: ts.VariableDeclaration): boolean { + const list = declaration.parent; + if (!ts.isVariableDeclarationList(list)) return true; + const statement = list.parent; + if (!ts.isVariableStatement(statement)) return true; + + // Top-level and namespace variables use existing shared module-field storage. + return !ts.isSourceFile(statement.parent) && !ts.isModuleBlock(statement.parent); } -function initializedBlockLet(node: ts.VariableDeclaration): boolean { - const list = node.parent; - if (node.initializer === undefined || !ts.isVariableDeclarationList(list)) return false; +function isBlockLexical(declaration: ts.VariableDeclaration): boolean { + const list = declaration.parent; + if (!ts.isVariableDeclarationList(list)) return false; const statement = list.parent; - return (list.flags & ts.NodeFlags.Let) !== 0 + return (list.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) !== 0 && ts.isVariableStatement(statement) && ts.isBlock(statement.parent); } +/** A deferred initializer can capture its own cell, but its evaluation cannot call or read any of its members. */ +function isDeferredInitializer(initializer: ts.Expression): boolean { + const value = unwrapTransparentExpression(initializer); + if (ts.isArrowFunction(value) || ts.isFunctionExpression(value) || ts.isLiteralExpression(value)) return true; + if (value.kind === ts.SyntaxKind.TrueKeyword || value.kind === ts.SyntaxKind.FalseKeyword + || value.kind === ts.SyntaxKind.NullKeyword) return true; + + if (ts.isArrayLiteralExpression(value)) { + return value.elements.every((element) => ts.isOmittedExpression(element) || isDeferredInitializer(element)); + } + if (ts.isObjectLiteralExpression(value)) { + return value.properties.every((property) => { + if (property.name === undefined || ts.isComputedPropertyName(property.name)) return false; + if (ts.isMethodDeclaration(property) || ts.isGetAccessorDeclaration(property) + || ts.isSetAccessorDeclaration(property)) return true; + + return ts.isPropertyAssignment(property) && isDeferredInitializer(property.initializer); + }); + } + return false; +} + function assignmentTarget(identifier: ts.Identifier): boolean { let target: ts.Node = identifier; for (;;) { diff --git a/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts b/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts index 14e96cc2a..db227504b 100644 --- a/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts +++ b/jacodb-ets/ts-frontend/src/lowering/stmtLowering.ts @@ -1056,9 +1056,20 @@ export class StmtLowerer { const local = this.m.moduleFieldForIdentifier(decl.name) ?? this.m.localForIdentifier(decl.name, declaredType); if (decl.initializer !== undefined) { + const deferredCell = local._ === "Local" + ? this.m.initializeDeferredSharedCapture(decl.name, local) + : undefined; + if (deferredCell !== undefined) { + const value = this.expr.lowerToImmediate(decl.initializer); + this.m.cfg.emit({ _: "AssignStmt", left: deferredCell, right: value }); + return; + } + const value = this.expr.lowerExpr(decl.initializer); this.m.cfg.emit({ _: "AssignStmt", left: local, right: value }); - if (local._ === "Local") this.m.initializeSharedCapture(decl, local); + } + if (local._ === "Local") { + this.m.initializeSharedCapture(decl.name, local, decl.initializer !== undefined); } } diff --git a/jacodb-ets/ts-frontend/test/async-iterator.spec.ts b/jacodb-ets/ts-frontend/test/async-iterator.spec.ts index e87a97554..4bf0f75f2 100644 --- a/jacodb-ets/ts-frontend/test/async-iterator.spec.ts +++ b/jacodb-ets/ts-frontend/test/async-iterator.spec.ts @@ -158,7 +158,7 @@ describe("for-await iterator acquisition and Async-from-Sync values", () => { const roundTripped = JSON.parse(serializeEtsFile(file)); const statements = methodByName(roundTripped, "run").body!.cfg.blocks.flatMap((block) => block.stmts); const snapshotIndex = statements.findIndex((statement) => statement._ === "AssignStmt" - && statement.right._ === "Local" && statement.right.name === "input"); + && statement.right._ === "ClosureFieldRef" && statement.right.fieldName === "input"); const snapshot = statements[snapshotIndex]; const lookups = statements.filter((statement) => statement._ === "AssignStmt" && statement.right._ === "PropertyRef"); @@ -167,7 +167,7 @@ describe("for-await iterator acquisition and Async-from-Sync values", () => { expect(diagnostics.messages).toEqual([]); expect(validateEtsFile(roundTripped)).toEqual([]); - expect(snapshot).toMatchObject({ _: "AssignStmt", left: { _: "Local" }, right: { _: "Local", name: "input" } }); + expect(snapshot).toMatchObject({ _: "AssignStmt", left: { _: "Local" }, right: { _: "ClosureFieldRef", fieldName: "input" } }); expect(snapshot.left.name).not.toBe("input"); expect(lookups).toHaveLength(2); expect(calls).toHaveLength(2); diff --git a/jacodb-ets/ts-frontend/test/object-methods.spec.ts b/jacodb-ets/ts-frontend/test/object-methods.spec.ts index 471f0cf44..8f48457a9 100644 --- a/jacodb-ets/ts-frontend/test/object-methods.spec.ts +++ b/jacodb-ets/ts-frontend/test/object-methods.spec.ts @@ -19,6 +19,74 @@ function expectNativeResult(source: string, expected: unknown): void { } describe("object literal methods", () => { + it("shares reassignments of a simple parameter across returned methods", () => { + expectNativeResult(` + export function value() { + function make(count: number) { + return { increment() { ++count; }, read() { return count; } }; + } + const pair = make(1); + pair.increment(); + return pair.read(); + } + `, 2); + }); + + it("shares a let declared without an initializer and starts it at undefined", () => { + expectNativeResult(` + export function value() { + let count: number; + const pair = { increment() { ++count; }, read() { return count; } }; + if (pair.read() !== undefined) return -1; + count = 1; + pair.increment(); + return pair.read(); + } + `, 2); + }); + + it("keeps deferred self-captures live after object construction and reassignment", () => { + expectNativeResult(` + export function value() { + let counter = { + read() { return counter.value; }, + value: 1, + }; + const original = counter; + counter = { read() { return 2; }, value: 2 }; + return original.read(); + } + `, 2); + }); + + it.each([ + ["possible TDZ access during a non-deferred initializer", ` + const counter = { read() { return counter.value; }, value: (() => counter.read())() }; + return counter.read(); + `], + ["mutable var", ` + var count = 1; + const pair = { increment() { ++count; }, read() { return count; } }; + pair.increment(); + return pair.read(); + `], + ["mutable parameter in defaults", ` + function make(count: number, read = () => count) { count++; return read(); } + return make(1); + `], + ["per-iteration let", ` + for (let count = 1; count < 3; count++) { + const pair = { read() { return count; } }; + return pair.read(); + } + return 0; + `], + ])("makes unsupported %s an explicit capture boundary", (_name, body) => { + const { diagnostics } = lower(`export function value() { ${body} }`); + + expect(diagnostics.messages).toContainEqual(expect.stringContaining("requires a supported initialized lexical cell")); + }); + it("creates a fresh own function on each evaluation of one method definition", () => { expectNativeResult(` export function value() { diff --git a/jacodb-ets/ts-frontend/test/object-runtime.spec.ts b/jacodb-ets/ts-frontend/test/object-runtime.spec.ts index 1eeb76e48..cdce5db44 100644 --- a/jacodb-ets/ts-frontend/test/object-runtime.spec.ts +++ b/jacodb-ets/ts-frontend/test/object-runtime.spec.ts @@ -77,7 +77,7 @@ describe("object test interpreter closure environments", () => { }); expect(changedSlots).toBeGreaterThan(0); - expect(() => executeObjectIr(file, "result", [3])).toThrow("undeclared test capture seed"); + expect(() => executeObjectIr(file, "result", [3])).toThrow(/undeclared test capture (?:%closures\d+|seed)/); }); it("keeps outer writes and sibling closure writes visible through declared slots", () => { diff --git a/jacodb-ets/ts-frontend/test/object-runtime.ts b/jacodb-ets/ts-frontend/test/object-runtime.ts index 551d5cf03..a0a86713a 100644 --- a/jacodb-ets/ts-frontend/test/object-runtime.ts +++ b/jacodb-ets/ts-frontend/test/object-runtime.ts @@ -27,32 +27,8 @@ export function executeObjectIr(file: EtsFileDto, name: string, args: unknown[] const invoke = (method: MethodDto, supplied: unknown[], receiver: unknown): unknown => { if (method.body === undefined) throw new Error(`bodyless test method ${method.signature.name}`); const locals = new Map(); - const environment = (type: LexicalEnvTypeDto): object => { - const slots = new Set(type.closures.map((capture) => capture.name)); - const capturedEnvironments = new Map( - type.closures - .filter((capture) => capture.type._ === "LexicalEnvType") - .map((capture) => [capture.name, locals.get(capture.name)]), - ); - const checkSlot = (key: PropertyKey): string => { - const name = String(key); - if (!slots.has(name)) throw new Error(`undeclared test capture ${name}`); - return name; - }; - - return new Proxy({}, { - get: (_target, key) => { - const name = checkSlot(key); - return capturedEnvironments.has(name) ? capturedEnvironments.get(name) : locals.get(name); - }, - set: (_target, key, value) => { - const name = checkSlot(key); - const storage = capturedEnvironments.has(name) ? capturedEnvironments : locals; - storage.set(name, value); - return true; - }, - }); - }; + const environment = (type: LexicalEnvTypeDto): object => + Object.fromEntries(type.closures.map((capture) => [capture.name, locals.get(capture.name)])); const captureEnvironment = (reference: ClosureFieldRefDto): Record => { const type = reference.base.type; const isDeclaredCapture = type._ === "LexicalEnvType" diff --git a/jacodb-ets/ts-frontend/test/state-and-order.spec.ts b/jacodb-ets/ts-frontend/test/state-and-order.spec.ts index 8e3494d33..eca22803e 100644 --- a/jacodb-ets/ts-frontend/test/state-and-order.spec.ts +++ b/jacodb-ets/ts-frontend/test/state-and-order.spec.ts @@ -352,8 +352,8 @@ describe("expression evaluation snapshots", () => { (stmt) => stmt._ === "AssignStmt" && stmt.left._ === "Local" && stmt.left.name === firstArgument.name - && stmt.right._ === "Local" - && stmt.right.name === "x", + && stmt.right._ === "ClosureFieldRef" + && stmt.right.fieldName === "x", ); expect(firstArgument.name).toMatch(/^%/); expect(snapshot).toBeDefined(); @@ -408,8 +408,8 @@ describe("expression evaluation snapshots", () => { (stmt) => stmt._ === "AssignStmt" && stmt.left._ === "Local" && stmt.left.name === left.name - && stmt.right._ === "Local" - && stmt.right.name === "x", + && stmt.right._ === "ClosureFieldRef" + && stmt.right.fieldName === "x", )).toBe(true); }); @@ -549,8 +549,8 @@ describe("expression evaluation snapshots", () => { (stmt) => stmt._ === "AssignStmt" && stmt.left._ === "Local" && stmt.left.name === receiver.name - && stmt.right._ === "Local" - && stmt.right.name === "service", + && stmt.right._ === "ClosureFieldRef" + && stmt.right.fieldName === "service", )).toBe(true); const calleeStmts = flattened(methodByName(file, "callee")); @@ -562,8 +562,8 @@ describe("expression evaluation snapshots", () => { (stmt) => stmt._ === "AssignStmt" && stmt.left._ === "Local" && stmt.left.name === (calleeCall.expr.ptr as { name: string }).name - && stmt.right._ === "Local" - && stmt.right.name === "callback", + && stmt.right._ === "ClosureFieldRef" + && stmt.right.fieldName === "callback", )).toBe(true); const ctorStmts = flattened(methodByName(file, "ctor")); @@ -578,8 +578,8 @@ describe("expression evaluation snapshots", () => { (stmt) => stmt._ === "AssignStmt" && stmt.left._ === "Local" && stmt.left.name === firstArgument.name - && stmt.right._ === "Local" - && stmt.right.name === "x", + && stmt.right._ === "ClosureFieldRef" + && stmt.right.fieldName === "x", )).toBe(true); });