diff --git a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md index 4f8842f77..3742aee97 100644 --- a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md +++ b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md @@ -5375,6 +5375,28 @@ and a `Load` of each field: a method bound to the literal) and makes the paramet object-type parameter, calls a member after, gives the literal again and to an interface, churning between steps, under own, rc, gc and none. -Not here: a literal whose arrow captures an object (`const b = new Box(5); const q = { w: (x: number) => -x * b.n }`) moves the object into the literal's `.captured`, so `b` cannot be used after it under own, -where a closure capturing it only borrows it (§16). +Not here: a literal whose arrow captures an object; see spec 67. + +## 67. An object literal whose arrows capture an object, 2026-10-29 + +`const b = new Box(5); const q = { w: (x: number) => x * b.n }; q.w(1); b.n` was `'this value' is used +here after its value was moved`: the literal's `.captured` box took `b` (a copy of a `const`), where a +closure capturing it that does not escape only borrows it (§16). MLIRGen gives the literal no release, +and rc no reference of the box's own for it that the literal gives back: the box only ever borrowed. + +- **A literal's box** (`classifyLiteralCaptures`): a capture box (`__capture_box`) filled field by field + and stored once into the `.captured` field of a local the literal is built in, which is read once into + the object `ts.New` made. rc's `ts.RetainCell`/`ts.ReleaseCell` of the box are its own count. +- **Stays here**: `walkBorrowed` from that object finds nothing that keeps it - its members called, the + literal given to calls that keep it not (an object-type parameter, spec 66). Its uses are the box's. +- **Then the box borrows** each copy whose value has an owner of its own (a named value released here, a + parameter, a local's read; not a cell): the store is a borrow (`OWN_CAPTURE_BORROW_ATTR_NAME`, as a + closure's), rc's retain before it goes (`captureRetains`, erased in `decideClosures`), and whatever + uses the literal is a use of the borrowed value. + +`own_literal_object_captures` captures a local object and a parameter, calls members, gives the literal +to an object-type parameter and reads the objects after, churning between steps, under own, rc, gc and +none. + +Not here: a literal given to an interface (`apply(q)` for `apply(s: Scaler)`): the cast copies it into +the interface's object, which keeps it, and the object stays moved into the box. diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 2899e5e19..1b6d88ade 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -119,6 +119,158 @@ namespace own_inference }); } + void OwnershipInferencePass::classifyLiteralCaptures() + { + getFunction().walk([&](mlir_ts::VariableOp boxOp) { + if (!boxOp->hasAttr(CAPTURE_BOX_ATTR_NAME)) + { + return; + } + + // filled field by field, and stored once into a literal's `.captured`: `{ w: (x) => x * b.n }` + // builds the literal in a local, then copies it into the object `ts.New` made + llvm::SmallVector fills; + mlir_ts::VariableOp literalOp; + for (auto &use : boxOp->getUses()) + { + auto *user = use.getOwner(); + if (auto propertyRefOp = mlir::dyn_cast(user)) + { + for (auto *fieldUser : propertyRefOp->getUsers()) + { + auto storeOp = mlir::dyn_cast(fieldUser); + if (!storeOp || storeOp.getReference() != propertyRefOp.getResult()) + { + return; + } + + fills.push_back(storeOp); + } + + continue; + } + + // rc's count of the box, for the literal's reference + if (mlir::isa(user)) + { + continue; + } + + auto storeOp = mlir::dyn_cast(user); + auto fieldOp = storeOp && storeOp.getValue() == boxOp.getResult() + ? storeOp.getReference().getDefiningOp() + : mlir_ts::PropertyRefOp(); + auto ownerOp = fieldOp ? fieldOp.getObjectRef().getDefiningOp() : mlir_ts::VariableOp(); + auto tupleType = ownerOp ? mlir::dyn_cast( + mlir::cast(ownerOp.getType()).getElementType()) + : mlir_ts::TupleType(); + auto fieldName = tupleType && fieldOp.getPosition() < tupleType.size() + ? mlir::dyn_cast_or_null(tupleType.getFieldInfo(fieldOp.getPosition()).id) + : mlir::StringAttr(); + if (literalOp || !fieldName || fieldName.getValue() != CAPTURED_NAME) + { + return; + } + + literalOp = ownerOp; + } + + if (!literalOp) + { + return; + } + + // ...read once, into the object it becomes + llvm::SmallVector objects; + for (auto *user : literalOp->getUsers()) + { + if (mlir::isa(user)) + { + continue; + } + + auto loadOp = mlir::dyn_cast(user); + if (!loadOp || !loadOp.getResult().hasOneUse()) + { + return; + } + + auto storeOp = mlir::dyn_cast(*loadOp.getResult().getUsers().begin()); + auto newOp = storeOp ? storeOp.getReference().getDefiningOp() : mlir_ts::NewOp(); + if (!newOp) + { + return; + } + + objects.push_back(newOp.getResult()); + } + + if (objects.size() != 1) + { + return; + } + + // the literal stays here: nothing stores, returns, captures or keeps it + auto box = std::make_shared(); + llvm::SmallVector uses; + if (walkBorrowed(objects.front(), {}, uses)) + { + return; + } + + for (auto &use : uses) + { + box->uses.push_back(use.op); + } + + // copies of values with an owner of their own: a named value released here, a parameter, a + // local's; not a cell (a captured `let`), and not one rc retained for the box + auto owned = [&](mlir::Value value) { + auto root = rootOf(value); + if (mlir::isa(root) || root.getDefiningOp()) + { + return true; + } + + return isFresh(root) && llvm::any_of(root.getUsers(), [](mlir::Operation *rootUser) { + return mlir::isa(rootUser); + }); + }; + + llvm::SmallVector borrowed; + for (auto storeOp : fills) + { + auto value = storeOp.getValue(); + if (mlir::isa(value.getType()) || holdsNoBlock(value)) + { + continue; + } + + if (!owned(value)) + { + return; + } + + // rc's reference for the box goes with the borrow (decideClosures) + if (auto *retain = retainBefore(value, storeOp)) + { + box->retains.push_back(retain); + } + + borrowed.push_back(storeOp); + } + + captureRetains.insert(box->retains.begin(), box->retains.end()); + for (auto storeOp : borrowed) + { + setAttrTracked(storeOp, OWN_CAPTURE_BORROW_ATTR_NAME); + captureStores[storeOp] = box.get(); + } + + literalBoxes.push_back(std::move(box)); + }); + } + llvm::SmallVector OwnershipInferencePass::borrowingFieldsOf(mlir::Type recordType) { llvm::SmallVector fields; @@ -923,6 +1075,11 @@ namespace own_inference void OwnershipInferencePass::decideClosures(llvm::SetVector &toErase) { + for (auto &box : literalBoxes) + { + toErase.insert(box->retains.begin(), box->retains.end()); + } + for (auto &closure : closures) { if (!closure->op) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 89919d227..a4ccb6f77 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -63,6 +63,7 @@ namespace own_inference // first: whether a closure borrows what it captures changes what its box's stores are classifyClosures(); + classifyLiteralCaptures(); classifyStateBoxes(); classifyBorrowingFields(); // ...and whether an object literal borrows what its fields hold (spec 32) @@ -143,6 +144,7 @@ namespace own_inference edgeReleases.clear(); derivedCache.clear(); closures.clear(); + literalBoxes.clear(); closureOf.clear(); stateBoxes.clear(); fieldBorrowRetains.clear(); diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index cd8e2fa50..6623fac24 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -227,6 +227,9 @@ class OwnershipInferencePass }; llvm::SmallVector> closures; + // the capture boxes of object literals that borrow what they capture (classifyLiteralCaptures): + // `uses` only, what reaches the literal + llvm::SmallVector> literalBoxes; // a copy stored into a borrowing box -> its closure llvm::DenseMap captureStores; // rc's references for boxes, which the closures decide @@ -250,6 +253,9 @@ class OwnershipInferencePass // stores are reads or takers depends on it. A closure with copies only keeps what phase 4 does // with it - its box owns them, and each copy moves in. void classifyClosures(); + // An object literal's `.captured` box (its arrows' captures, spec 67): when the literal stays in + // this function, the box borrows the copies it holds, as a closure that does not escape does + void classifyLiteralCaptures(); // The fields of a generator's state object of this type that borrow from its arguments // (OWN_BORROWING_FIELDS_ATTR_NAME, the signature pass's), the `.captured` box's first. diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index d27324bbb..52bb6a366 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4013,7 +4013,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_generator_this_param own_copy_within_returned_param own_swap_elements own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array own_generator_take own_rest_array_borrows own_string_copies - own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures + own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") @@ -4051,7 +4051,7 @@ foreach(keeps_mm rc gc none) own_copy_within_returned_param own_swap_elements own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array own_generator_take own_rest_array_borrows own_string_copies - own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures + own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot) tslang_add_test(NAME test-jit-${keeps_mm}-${keeps_test} COMMAND test-runner -jit -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts") diff --git a/tslang/test/tester/own/own_literal_object_captures.ts b/tslang/test/tester/own/own_literal_object_captures.ts new file mode 100644 index 000000000..3c6452c19 --- /dev/null +++ b/tslang/test/tester/own/own_literal_object_captures.ts @@ -0,0 +1,52 @@ +// An object literal whose arrows capture an object (spec 67): when the literal stays in the function - its +// members called, the literal given to a parameter of an object type - its `.captured` box borrows the +// object, as a closure that does not escape does, and the object is used after. Each step churns, so +// anything freed too early reads garbage; every model runs it. +class Item { + constructor(public n: number) {} +} + +function churn() { + const junk: Item[] = []; + for (let i = 0; i < 64; i++) junk.push(new Item(999)); +} + +function apply(o: { w: (x: number) => number }) { + return o.w(3); +} + +function viaParam(item: Item) { + const q = { w: (x: number) => x + item.n }; + return q.w(1) + apply(q); +} + +function test(i: number) { + let s: number = 0; + const b = new Item(i); + const q = { w: (x: number) => x * b.n }; + s += q.w(1); + churn(); + s += apply(q); + s += b.n; + + const c = new Item(2); + const r = { w: (x: number) => x + b.n + c.n, v: () => c.n }; + s += apply(r) + r.v(); + churn(); + s += c.n + b.n; + + s += viaParam(c); + return s; +} + +function main() { + let ok = 0; + for (let i = 0; i < 300; i++) { + // i + 3i + i, then (3 + i + 2) + 2, 2 + i, then 3 + 5 + if (test(i) == 5 * i + 7 + 2 + i + 8 + i) ok++; + churn(); + } + + assert(ok == 300, "ok"); + print("done."); +}