From 541b2660f16098efef4d47900490121ad7c6c002 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 15:57:02 +0000 Subject: [PATCH] -mm=own: an object literal whose arrows capture an object, given to an interface, borrows it (spec 68) `use({ greet: () => "hi" + b.n }); b.n` for `use(g: Greeter)` was "used after its value was moved": the interface's release freed the literal's `.captured` box with every copy in it. - The signature pass marks `.captured` as a field a borrowing record (spec 32) borrows when each copy in the box has an owner of its own and nothing keeps or returns the interfaces. - That record's release frees such a box alone (tsfrecb_). - Inference bounds the copies by the record's uses (walkRecord) in place of walkBorrowed. - checkBoundedResults skips results that own no block (a number bounded by a state-shaped literal). Co-Authored-By: Claude Opus 5.5 --- .../2026-09-24-own-memory-model-design.md | 34 +++++++- .../LowerToLLVM/OwnershipRoutineLogic.h | 12 ++- tslang/lib/TypeScript/OwnershipFacts.h | 14 +++ .../TypeScript/OwnershipInferenceClosures.cpp | 58 +++++++++---- .../TypeScript/OwnershipInferenceRecords.cpp | 7 ++ .../lib/TypeScript/OwnershipSignaturePass.h | 4 + .../TypeScript/OwnershipSignatureRecords.cpp | 87 +++++++++++++++++++ tslang/test/tester/CMakeLists.txt | 4 +- .../own/own_literal_interface_captures.ts | 85 ++++++++++++++++++ 9 files changed, 281 insertions(+), 24 deletions(-) create mode 100644 tslang/test/tester/own/own_literal_interface_captures.ts 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 3742aee97..e8c4964cb 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 @@ -5398,5 +5398,35 @@ and rc no reference of the box's own for it that the literal gives back: the box 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. +Not here: a literal given to an interface (`apply(q)` for `apply(s: Scaler)`); see spec 68. + +## 68. An object literal whose arrows capture an object, given to an interface, 2026-10-29 + +`const b = new Box(); use({ greet: () => "hi" + b.n }); b.n` for `use(g: Greeter)` was `'this value' is used +here after its value was moved`: the interface is a view of the literal's box (`ts.NewInterface`), whose +release - the interface's at the end - frees the box and the `.captured` box with every copy in it, so +the copies could not borrow (spec 67 only covers a literal that is never released). + +- **A borrowing record's box** (spec 32, `capturedBoxBorrows` in the signature pass): the `.captured` field + is one more field the record borrows when the box is stored there once, each copy in it is a value with + an owner of its own (`hasOwnerOfItsOwn`, spec 67's test) or holds no block, none is a cell, and every + interface made of the record is only retained, released, or given to calls that keep it not and return + nothing borrowed of it. Never returnable. +- **Its release** (`OwnershipRoutineLogic::releaseFields`): a borrowed field that is a capture box is + freed with `tsfrecb_` - the box, not what it holds - where any other borrowed field is skipped. +- **Inference** (`classifyLiteralCaptures`): the record's uses (`walkRecord` from its interfaces) are the + box's, in place of `walkBorrowed` from the object; the copies borrow as in spec 67. `classifyRecords` + leaves the `.captured` store to it. A record the signature pass marked that the walk finds kept or + returned is an error, not a silent free. +- **Bounded results that hold nothing**: `checkBoundedResults` skips a call whose result owns no block. + A literal capturing a parameter is state-shaped (`findBorrowingStates`), which bounded `viaParam`'s + number result by `item`, and `print(viaParam(c))` was an error. + +`own_literal_interface_captures` gives literals capturing a local object, two objects, a string beside an +object, and a parameter to interface parameters and reads the objects after; a literal returned as an +interface and one an array keeps still take their copies. It churns between steps, under own, rc, gc and +none. + +Not here: a literal capturing a `let` (a cell), which errors as `captured by a closure that escapes` +with or without an interface; and `return applyO({ w: (x) => x + item.n })` for an object-type parameter, +`a closure that escapes owns what it captures`. diff --git a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h index 3fdcb9edb..680cd8b81 100644 --- a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h +++ b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h @@ -863,7 +863,11 @@ class OwnershipRoutineLogic for (auto [index, fieldType] : llvm::enumerate(getFieldTypes(recordType))) { - if (llvm::is_contained(left, static_cast(index))) + // ...but for an object literal's `.captured` box that borrows its copies (own spec 68): the + // box is the record's, what it holds is not + auto leftBox = mlir::dyn_cast(fieldType); + if (llvm::is_contained(left, static_cast(index)) && + !(leftBox && isa(leftBox.getElementType()))) { continue; } @@ -897,8 +901,10 @@ class OwnershipRoutineLogic { if (isa(refFieldType.getElementType())) { - routineName = borrows ? getOrCreateCaptureBoxCellsRoutine(refFieldType) - : getOrCreateCaptureBoxReleaseRoutine(refFieldType); + routineName = llvm::is_contained(left, static_cast(index)) + ? getOrCreateCaptureBoxFreeRoutine(refFieldType) + : borrows ? getOrCreateCaptureBoxCellsRoutine(refFieldType) + : getOrCreateCaptureBoxReleaseRoutine(refFieldType); } } else diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index c0c707e23..5dbf30dcc 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -1664,6 +1664,20 @@ inline RecordFieldSource recordFieldSource(mlir::Value value) return RecordFieldSource::Unknown; } +// A copy an object literal's `.captured` box may borrow (specs 67, 68): a value with an owner of its +// own - a parameter, a local's read, a named value released here; not a cell (a captured `let`) +inline bool hasOwnerOfItsOwn(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); }); +} + // The box of the object literal built in `varOp`: its one read, copied into a block `ts.New` made // (recordBoxOf). Null for anything else. inline mlir_ts::NewOp recordBoxOfLocal(mlir_ts::VariableOp varOp) diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 1b6d88ade..7fe847824 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -131,6 +131,7 @@ namespace own_inference // builds the literal in a local, then copies it into the object `ts.New` made llvm::SmallVector fills; mlir_ts::VariableOp literalOp; + int32_t capturedPosition = -1; for (auto &use : boxOp->getUses()) { auto *user = use.getOwner(); @@ -173,6 +174,7 @@ namespace own_inference } literalOp = ownerOp; + capturedPosition = static_cast(fieldOp.getPosition()); } if (!literalOp) @@ -213,7 +215,40 @@ namespace own_inference // the literal stays here: nothing stores, returns, captures or keeps it auto box = std::make_shared(); llvm::SmallVector uses; - if (walkBorrowed(objects.front(), {}, uses)) + auto newOp = objects.front().getDefiningOp(); + if (llvm::is_contained(recordBorrowedFields(newOp), capturedPosition)) + { + // ...or a borrowing record's box, seen only as interfaces given to calls that keep them + // not (spec 68): their uses are the box's, and its release frees the box alone + llvm::SmallVector interfaces; + for (auto *user : newOp->getUsers()) + { + if (mlir::isa(user)) + { + for (auto *castUser : user->getUsers()) + { + if (mlir::isa(castUser)) + { + interfaces.push_back(castUser->getResult(0)); + } + } + } + } + + RecordWalk walk; + llvm::SmallVector kills{newOp.getOperation(), literalOp.getOperation()}; + walkRecord(interfaces, kills, walk); + if (walk.kept || !walk.returns.empty()) + { + auto *at = walk.kept ? walk.kept : walk.returns.front(); + at->emitError("-mm=own: an object literal that borrows what its arrows capture can't outlive this function"); + signalPassFailure(); + return; + } + + uses.append(walk.uses.begin(), walk.uses.end()); + } + else if (walkBorrowed(objects.front(), {}, uses)) { return; } @@ -223,20 +258,7 @@ namespace own_inference 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); - }); - }; - + // copies of values with an owner of their own, not one rc retained for the box llvm::SmallVector borrowed; for (auto storeOp : fills) { @@ -246,7 +268,7 @@ namespace own_inference continue; } - if (!owned(value)) + if (!hasOwnerOfItsOwn(value)) { return; } @@ -494,7 +516,9 @@ namespace own_inference { getFunction().walk([&](mlir::Operation *call) { auto bounded = call->getAttrOfType(OWN_RESULT_BOUNDED_ATTR_NAME); - if (!bounded || !isCall(call) || call->getNumResults() != 1) + // a number holds nothing a bound could outlive: `return apply({ w: (x) => x + item.n })` + // makes a state-shaped literal, not a result that borrows `item` + if (!bounded || !isCall(call) || call->getNumResults() != 1 || !ownsHeap(call->getResult(0))) { return; } diff --git a/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp b/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp index 24130ae57..d708f9a71 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp @@ -58,6 +58,13 @@ namespace own_inference continue; } + // the `.captured` box: what it borrows is the literal's box's (classifyLiteralCaptures) + if (auto boxOp = storeOp.getValue().getDefiningOp(); + borrows && boxOp && boxOp->hasAttr(CAPTURE_BOX_ATTR_NAME)) + { + continue; + } + auto source = recordFieldSource(storeOp.getValue()); if (source == RecordFieldSource::NoBlock) { diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 6a7a8f304..292d270a8 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -952,6 +952,10 @@ class OwnershipSignaturePass : public mlir::PassWrapper interfaces); // An object literal of tuple type (a `@value` value, a type literal) that is never boxed and holds // a borrow beside nothing it owns - every field that holds a block borrows it - is an unboxed diff --git a/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp b/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp index b1eb75dcd..2269adebe 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp @@ -215,6 +215,85 @@ namespace own_signature } } + bool OwnershipSignaturePass::capturedBoxBorrows(mlir::Value field, llvm::ArrayRef interfaces) + { + // the box, stored once + mlir_ts::VariableOp boxOp; + for (auto *user : field.getUsers()) + { + if (mlir::isa(user)) + { + continue; + } + + auto storeOp = mlir::dyn_cast(user); + auto varOp = storeOp && storeOp.getReference() == field ? storeOp.getValue().getDefiningOp() + : mlir_ts::VariableOp(); + if (!varOp || !varOp->hasAttr(CAPTURE_BOX_ATTR_NAME) || boxOp) + { + return false; + } + + boxOp = varOp; + } + + if (!boxOp) + { + return false; + } + + // ...filled with copies of values that have owners of their own + for (auto *user : boxOp->getUsers()) + { + if (mlir::isa(user)) + { + continue; + } + + if (auto storeOp = mlir::dyn_cast(user); storeOp && storeOp.getReference() == field) + { + continue; + } + + auto propertyRefOp = mlir::dyn_cast(user); + if (!propertyRefOp) + { + return false; + } + + for (auto *fieldUser : propertyRefOp->getUsers()) + { + auto fillOp = mlir::dyn_cast(fieldUser); + if (!fillOp || fillOp.getReference() != propertyRefOp.getResult()) + { + return false; + } + + auto value = fillOp.getValue(); + if (mlir::isa(value.getType()) || (!holdsNoBlock(value) && !hasOwnerOfItsOwn(value))) + { + return false; + } + } + } + + // ...and nothing keeps the record: its retains and releases, and calls that only borrow it + for (auto *newInterfaceOp : interfaces) + { + auto stays = true; + forEachUse(newInterfaceOp->getResult(0), [&](mlir::Operation *use, mlir::Value used) { + stays = stays && (mlir::isa(use) || + (isCall(use) && !keeps(use, used) && resultBorrows(use) < 0)); + }); + if (!stays) + { + return false; + } + } + + return true; + } + void OwnershipSignaturePass::classifyRecordBox(mlir_ts::NewOp newOp) { auto boxOp = recordBoxOf(newOp.getResult()); @@ -294,6 +373,14 @@ namespace own_signature } auto field = propertyRefOp.getResult(); + if (capturedBoxBorrows(field, interfaces)) + { + // never returned: what the box borrows is this function's + info.returnable = false; + borrowed.push_back(propertyRefOp.getPosition()); + continue; + } + auto refType = mlir::dyn_cast(field.getType()); if (!refType || !mth.ownsHeapMemory(field.getLoc(), refType.getElementType())) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 67d037c7a..32ce2a6da 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4019,7 +4019,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_literal_object_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_literal_interface_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") @@ -4057,7 +4057,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_literal_object_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_literal_interface_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_interface_captures.ts b/tslang/test/tester/own/own_literal_interface_captures.ts new file mode 100644 index 000000000..57533ad8f --- /dev/null +++ b/tslang/test/tester/own/own_literal_interface_captures.ts @@ -0,0 +1,85 @@ +// An object literal whose arrows capture an object, given to a parameter of an interface type (spec 68): +// the interface is a view of the literal's box, and when nothing keeps it the box borrows what it +// captures - the objects are used after. A literal that is kept or returned still takes its copies. +// Each step churns, so anything freed too early reads garbage; every model runs it. +class Item { + constructor(public n: number) {} +} + +interface Scaler { + w(x: number): number; +} + +interface Namer { + name(): string; +} + +function churn() { + const junk: Item[] = []; + for (let i = 0; i < 64; i++) junk.push(new Item(999)); +} + +function apply(s: Scaler) { + return s.w(3); +} + +function nameOf(n: Namer) { + return n.name(); +} + +const kept: Scaler[] = []; +function keep(s: Scaler) { + const r = s.w(1); + kept.push(s); + return r; +} + +function viaParam(item: Item) { + return apply({ w: (x: number) => x + item.n }); +} + +function made(item: Item): Scaler { + const n = item.n; + return { w: (x: number) => x + n }; +} + +function test(i: number) { + let s: number = 0; + const b = new Item(i); + s += apply({ w: (x: number) => x * b.n }); + churn(); + s += b.n; + + const c = new Item(2); + s += apply({ w: (x: number) => x + b.n + c.n }); + churn(); + s += c.n + b.n; + + const label = "n" + i; + if (nameOf({ name: () => label + c.n }) == "n" + i + "2") s += 1; + churn(); + if (label == "n" + i) s += 1; + + s += viaParam(c); + + s += made(c).w(1); + + const e = new Item(5); + s += keep({ w: (x: number) => x + e.n }); + churn(); + return s; +} + +function main() { + let ok = 0; + for (let i = 0; i < 300; i++) { + // 3i + i, (3 + i + 2) + 2 + i, 1 + 1, 3 + 2, 1 + 2, 1 + 5 + if (test(i) == 4 * i + 7 + 2 * i + 2 + 5 + 3 + 6) ok++; + churn(); + } + + assert(ok == 300, "ok"); + assert(kept.length == 300, "kept"); + assert(kept[7].w(0) == 5, "kept value"); + print("done."); +}