From 8a7bc038af6d282eca4cc00de24eee6349242a4e Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 01:15:00 +0000 Subject: [PATCH] -mm=own: a field taken out of an object a `const` names (spec 64) `const r = new Holder(); return r.value`, `c ? initial : r.value` and `initial ?? r.value` were "'this value' borrows a field and cannot be stored, returned or captured". A `const` whose value is `new`'s or a call's own result is folded into that value, so the read is spec 63's shape with a named owner. namedFieldTakeOf moves the read out of the field when nothing sees the object after the read but its releases (no method, move, read of that field, nor a borrow made of it before), the read is not made again on the same object, and rc's retain of it is in its block; the field is emptied right at the read, so a release after a merge frees nothing of a path that did not take it. Under own, consumeConditionalResults retains such a branch yield in the branch when a receiver keeps the merge, so the take sees its retain; a merge only read stays a borrow. findReceiverRetains gets a mode that only asks, without marking a `let` as the acquisition. own_err_container_read_stored reads `h.c` after `h2.c = h.c`: without that read it is now a move. Co-Authored-By: Claude Opus 5.5 --- .../2026-09-24-own-memory-model-design.md | 48 +++++++ .../TypeScript/OwnedReturnConsumptionPass.cpp | 25 +++- .../lib/TypeScript/OwnershipInferencePass.h | 5 + .../OwnershipInferencePlaceReads.cpp | 129 ++++++++++++++++-- tslang/test/tester/CMakeLists.txt | 12 +- .../own/own_err_container_read_stored.ts | 5 +- .../own/own_err_named_field_borrow_after.ts | 34 +++++ .../own/own_err_named_field_method_after.ts | 33 +++++ .../own/own_err_named_field_object_moved.ts | 33 +++++ .../own/own_err_named_field_read_again.ts | 33 +++++ .../test/tester/own/own_named_field_take.ts | 109 +++++++++++++++ 11 files changed, 449 insertions(+), 17 deletions(-) create mode 100644 tslang/test/tester/own/own_err_named_field_borrow_after.ts create mode 100644 tslang/test/tester/own/own_err_named_field_method_after.ts create mode 100644 tslang/test/tester/own/own_err_named_field_object_moved.ts create mode 100644 tslang/test/tester/own/own_err_named_field_read_again.ts create mode 100644 tslang/test/tester/own/own_named_field_take.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 4a50e4075..0714d930e 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 @@ -5277,3 +5277,51 @@ own build fails its count (exit 3). Not here: the field of a named local of a class type (`const r = next(xs, 0); let v = initial ?? r.value`) is still a borrow that cannot be stored, and a parameter on the other branch (`given ?? pair(n).item`) is kept, which callers cannot give up. + +## 64. A field taken out of an object a `const` names, 2026-10-29 + +`const r = new Holder(); return r.value` was `'this value' borrows a field and cannot be stored, +returned or captured`, and so was `c ? initial : r.value` and `initial ?? r.value`. A `const` whose +value is `new`'s or a call's own result is not a slot: MLIRGen folds the name into the value +(`__owned_result_named`), so `r.value` is a `Load(PropertyRef(%new))` and rc releases `%new` where the +name ends - the shape of spec 63 with an owner that has a name. + +- **The take** (`namedFieldTakeOf`, from `temporaryFieldTakeOf`). A read of a field of such an object + (`ts.New` with `__owned_result`, or `callResultIsOwn`), with rc's retain of the read later in its + block, is a move out of the field when: + 1. nothing sees the object after the read but its releases: no method, no move of it, no read of + that field; and nothing made of the object before the read (a borrow `const w = same(r)`, followed + through every result made of it in turn) is used after it. Its other fields stay readable; + 2. the read is not made again on the same object: no path from the read back to it that does not + make the object anew (a loop around the read but not around `new`); + 3. rc's retain of the read is in the read's block, and is it or its taker what keeps the borrow. + + rc's retain goes, and a `ts.Default` of the field's type is stored into the field right after the + read - not before the release, which after a `?:` stands on every path, and would leave the field of + a path that did not take it unreleased. +- **rc, a branch retains** (`consumeConditionalResults`). Under own only, a branch of a `ts.If` that + yields a field read out of a named object retains it in the branch, right after the read, so that + the take sees its retain - when a receiver keeps the merge (rc retained it after the `ts.If`), whose + retain then goes, as for spec 63. A merge only read (`const x = c ? a : r.value; return x.n`) is left a + borrow: retained in its branches it would be an owned value, and the parameter on its other branch + kept, which callers cannot give up. Under rc the retain after the merge is left: the object outlives + the `ts.If` either way. + +A parameter on the other branch of a merge that is kept (`return c ? initial : r.value`) is moved in, as +for any parameter a function keeps: the caller gives it up. + +Between the read and the taker the taken value has no owner but the read: an exception thrown there +leaks it (as in spec 63), it does not free it twice. + +`own_err_container_read_stored` (`h2.c = h.c`) is now a move out of `h`'s field when `h` is not read +again: the test reads `h.c` after, which stays an error. + +`own_named_field_take` returns, picks with a `?:` and a `??`, uses the read before returning it and +reads another field after, reads a merge it does not keep, pushes it from a `new` in a loop, and takes +from a call's result, churning between steps, under own, rc, gc and none; the ownership verifier is +silent on it. `own_err_named_field_{read_again,method_after,object_moved,borrow_after}` are the four +shapes that must stay borrows; a loop around the read but not around `new`, and a `let h = r` read after, +are rejected too. + +Not here: a `let` of a class type (a slot, not a folded name), and a push of the field into a global +array (spec 25's immortal keepers ask for a value made here). diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index f91e6a32b..a582cc3da 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -1588,7 +1588,21 @@ class OwnedReturnConsumptionPass return false; }; - if (llvm::none_of(yields, carriesOwned) && llvm::none_of(yields, borrowsBranchTemporary)) + // ...or, under -mm=own, a field read out of an object a `const` names (`c ? init : r.value`), + // the merge kept by a receiver: a retain in the branch, right after the read, is what own + // takes out of the field (spec 64). A merge only read stays a borrow, as it was. Under rc a + // retain after the `ts.If` does the same, and is left so. + auto mergeKept = !findReceiverRetains(result, /*claim=*/false).empty(); + auto readsNamedObjectField = [&](mlir_ts::ResultOp resultOp) { + auto loadOp = producerOf(resultOp->getOperand(0)).getDefiningOp(); + auto propertyRefOp = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); + auto *definingOp = propertyRefOp ? propertyRefOp.getObjectRef().getDefiningOp() : nullptr; + return compileOptions.memoryModel == MemoryModelOwn && mergeKept && definingOp && + definingOp->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME); + }; + + if (llvm::none_of(yields, carriesOwned) && llvm::none_of(yields, borrowsBranchTemporary) && + llvm::none_of(yields, readsNamedObjectField)) { return; } @@ -2731,7 +2745,8 @@ class OwnedReturnConsumptionPass // back as a temporary like any other nobody took. Every `return` of it takes it over, since // each is on a path of its own - `if (x) return r; return r;` - and one left retaining would // hand its caller two references. - static llvm::SmallVector findReceiverRetains(mlir::Value result) + // (`claim` false only asks: the declaration is not marked as the acquisition) + static llvm::SmallVector findReceiverRetains(mlir::Value result, bool claim = true) { auto *definingOp = result.getDefiningOp(); if (definingOp && definingOp->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME)) @@ -2775,7 +2790,11 @@ class OwnedReturnConsumptionPass { // the declaration becomes the acquisition, which is what keeps the // ownership verifier able to pair the release still to come - varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, mlir::UnitAttr::get(varOp.getContext())); + if (claim) + { + varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, mlir::UnitAttr::get(varOp.getContext())); + } + return {retainSlotOp.getOperation()}; } } diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index d390f7640..0fb26d473 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -819,6 +819,8 @@ class OwnershipInferencePass mlir_ts::VariableOp slot; // a field of a temporary (spec 63): the temporary's release, before which the field is emptied mlir::Operation *release = nullptr; + // a field of an object a `const` names (spec 64): emptied right at the read + bool emptyAtRead = false; }; // Is `kept`, what keeps the borrow `read` (a read of a field of an owning record local), one @@ -831,6 +833,9 @@ class OwnershipInferencePass // Is `kept` rc's retain of `read`, a read of a field of a call's own result released as a // temporary right after, with nothing else reading that field (spec 63)? bool temporaryFieldTakeOf(mlir::Operation *read, mlir::Operation *kept, FieldTake &take); + // ...or of an object a `const` names, `new`'s or a call's own, that nothing sees after the move + // but its releases, and that is not taken from twice (spec 64)? + bool namedFieldTakeOf(mlir::Operation *read, mlir::Operation *retain, mlir_ts::PropertyRefOp field, FieldTake &take); // Can `call` be given a copy of `value`, a string read out of a place, in its place (callCopies)? static bool copiesInto(mlir::Operation *call, mlir::Value value); // Does `store` put `value`, a string read out of a place, into another place with no retain of diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 7b3ac7eae..30bc66e5c 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -852,10 +852,12 @@ namespace own_inference { if (!dryRun) { - mlir::OpBuilder builder(take.release); + // (right after the read: rc's retain of it is erased with the bookkeeping) + auto *at = take.emptyAtRead ? read->getNextNode() : take.release; + mlir::OpBuilder builder(at); auto fieldType = mlir::cast(take.field.getType()).getElementType(); - auto empty = builder.create(take.release->getLoc(), fieldType); - builder.create(take.release->getLoc(), empty, take.field); + auto empty = builder.create(at->getLoc(), fieldType); + builder.create(at->getLoc(), empty, take.field); } bookkeeping.push_back(take.retain); @@ -1145,7 +1147,33 @@ namespace own_inference // walk may meet the taker first (`r = next(xs, 0).value`). A string too: it moves, as nothing // else holds it. auto loadOp = mlir::dyn_cast(read); - auto retainOp = loadOp ? mlir::dyn_cast_or_null(read->getNextNode()) : mlir_ts::RetainOp(); + auto field = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); + auto temporary = field ? field.getObjectRef() : mlir::Value(); + auto *call = temporary ? temporary.getDefiningOp() : nullptr; + if (!call || !field->hasOneUse()) + { + return false; + } + + // ...or out of an object a `const` names, `new`'s or a call's own (spec 64): `return r.value`. + // The read may be used before rc's retain of it, later in its block (`const v = r.value; + // print(v.n); return v`): the field is empty from the read on, and the read holds what it held. + if (call->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME)) + { + for (auto *user : loadOp->getUsers()) + { + auto namedRetain = mlir::dyn_cast(user); + if (namedRetain && namedRetain->getBlock() == read->getBlock() && + (kept == namedRetain || takerOf(namedRetain, loadOp.getResult()) == kept)) + { + return namedFieldTakeOf(read, namedRetain, field, take); + } + } + + return false; + } + + auto retainOp = mlir::dyn_cast_or_null(read->getNextNode()); if (!retainOp || retainOp.getReference() != loadOp.getResult() || (kept != retainOp && takerOf(retainOp, loadOp.getResult()) != kept)) { @@ -1155,10 +1183,8 @@ namespace own_inference kept = retainOp; // a field read in place out of a call's own result, not a borrow of what the call was given - auto field = loadOp.getReference().getDefiningOp(); - auto temporary = field ? field.getObjectRef() : mlir::Value(); - auto *call = temporary ? temporary.getDefiningOp() : nullptr; - if (!call || !callResultIsOwn(call) || !field->hasOneUse()) + + if (!callResultIsOwn(call)) { return false; } @@ -1199,6 +1225,93 @@ namespace own_inference return true; } + bool OwnershipInferencePass::namedFieldTakeOf(mlir::Operation *read, mlir::Operation *retain, + mlir_ts::PropertyRefOp field, FieldTake &take) + { + // The object a `const` names is `new`'s own, or a call's own result: nothing else holds it, + // and its releases end it. The field is left empty right at the read, so each release frees + // nothing of what the taker has, on a path that took it or not (`c ? init : r.value`). + auto object = field.getObjectRef(); + auto *producer = object.getDefiningOp(); + if (!(mlir::isa(producer) && producer->hasAttr(OWNED_RESULT_ATTR_NAME)) && !callResultIsOwn(producer)) + { + return false; + } + + llvm::SmallVector releases; + for (auto *user : object.getUsers()) + { + if (mlir::isa(user)) + { + releases.push_back(user); + } + } + + if (releases.empty()) + { + return false; + } + + // taken once for each object: not again around a loop that does not make it anew + auto *next = read->getNextNode(); + if (!next || reachableAfter(next, read, producer)) + { + return false; + } + + // Nothing sees the object after the move but its releases: no method, no move of it, no read + // of that field, nor anything made of the object before it that is used after (a borrow of it). + // Its other fields are its own still. + auto seenAfter = [&](mlir::Operation *op) { return op != read && op != retain && reachableAfter(read, op, releases); }; + for (auto *user : object.getUsers()) + { + if (mlir::isa(user) || user == field.getOperation()) + { + continue; + } + + if (auto propertyRefOp = mlir::dyn_cast(user); + propertyRefOp && propertyRefOp.getPosition() != field.getPosition()) + { + continue; + } + + // the user, and what is made of its results in turn + llvm::SmallVector derived{user}; + llvm::SmallPtrSet visited; + while (!derived.empty()) + { + auto *op = derived.pop_back_val(); + if (!visited.insert(op).second) + { + continue; + } + + if (seenAfter(op)) + { + return false; + } + + for (auto result : op->getResults()) + { + derived.append(result.getUsers().begin(), result.getUsers().end()); + } + } + } + + auto *taker = takerOf(retain, read->getResult(0)); + if (!taker) + { + return false; + } + + take.retain = retain; + take.taker = taker; + take.field = field.getResult(); + take.emptyAtRead = true; + return true; + } + bool OwnershipInferencePass::keptParamOutlives(const Chain &chain, llvm::function_ref outlives) { for (auto &root : chain.roots) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 88a6d6baa..bafe08564 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -3992,7 +3992,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_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_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") @@ -4030,7 +4030,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_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_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") @@ -4501,7 +4501,7 @@ set(own_error_cases "own_err_alias_read_popped|:28:9: error: '[^']*' borrows an element but is used here after it may be released or overwritten" "own_err_alias_read_stale|:31:19: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_merge_root_assigned|:36:12: error: '[^']*' borrows a field but is used here after it may be released or overwritten" - "own_err_container_read_stored|:26:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_container_read_stored|:27:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_field_let_overwritten|:28:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_field_let_assigned|:26:5: error: '[^']*' borrows a field and cannot be assigned" "own_err_call_drops_indirectly|:24:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" @@ -4739,7 +4739,11 @@ set(own_error_cases "own_err_callback_cast_field_drops|:16:13: error: '[^']*' borrows an element but is used here after it may be released or overwritten" "own_err_callback_interface_slot_drops|:41:11: error: a value read out of the global 'pool' is lent to a call that may release or overwrite it" "own_err_callback_interface_slot_targets|:47:12: error: a value read out of the global 'pool' is lent to a call that may release or overwrite it" - "own_err_union_narrowed_moved|:26:14: error: '[^']*' is used here after its value was moved") + "own_err_union_narrowed_moved|:26:14: error: '[^']*' is used here after its value was moved" + "own_err_named_field_read_again|:28:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_named_field_method_after|:28:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_named_field_object_moved|:28:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_named_field_borrow_after|:29:5: error: '[^']*' borrows a field and cannot be stored, returned or captured") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_err_container_read_stored.ts b/tslang/test/tester/own/own_err_container_read_stored.ts index 2bd4b4b37..81ca09182 100644 --- a/tslang/test/tester/own/own_err_container_read_stored.ts +++ b/tslang/test/tester/own/own_err_container_read_stored.ts @@ -1,5 +1,6 @@ // -mm=own, phase 3 rejects: a value read out of a field is borrowed; storing it into another -// field would give it a second owner. +// field would give it a second owner. (With `h` not read again it would be a move out of the field +// of an object a `const` names, spec 64: `h` reads it after.) class C { v: number[] = []; constructor(public x: number) {} @@ -24,5 +25,5 @@ function main() { const h = new H(); const h2 = new H(); h2.c = h.c; - print(h2.c.x); + print(h2.c.x, h.c.x); } diff --git a/tslang/test/tester/own/own_err_named_field_borrow_after.ts b/tslang/test/tester/own/own_err_named_field_borrow_after.ts new file mode 100644 index 000000000..ef7d0e6ff --- /dev/null +++ b/tslang/test/tester/own/own_err_named_field_borrow_after.ts @@ -0,0 +1,34 @@ +// -mm=own: a field moves out of an object a `const` names only when nothing sees the object after +// the move but its release (spec 64); a borrow of the object made before the take, used after it. +class Item { + constructor(public n: number) {} +} + +class Holder { + value = new Item(3); + show() { + return this.value.n; + } +} + +const kept: Holder[] = []; + +function keep(r: Holder) { + kept.push(r); +} + +function same(r: Holder) { + return r; +} + +function take() { + const r = new Holder(); + const w = same(r); + const v = r.value; + print(w.value.n); + return v; +} + +function main() { + print(take().n); +} diff --git a/tslang/test/tester/own/own_err_named_field_method_after.ts b/tslang/test/tester/own/own_err_named_field_method_after.ts new file mode 100644 index 000000000..2e271999a --- /dev/null +++ b/tslang/test/tester/own/own_err_named_field_method_after.ts @@ -0,0 +1,33 @@ +// -mm=own: a field moves out of an object a `const` names only when nothing sees the object after +// the move but its release (spec 64); a method of the object called after its field is taken. +class Item { + constructor(public n: number) {} +} + +class Holder { + value = new Item(3); + show() { + return this.value.n; + } +} + +const kept: Holder[] = []; + +function keep(r: Holder) { + kept.push(r); +} + +function same(r: Holder) { + return r; +} + +function take() { + const r = new Holder(); + const v = r.value; + print(r.show()); + return v; +} + +function main() { + print(take().n); +} diff --git a/tslang/test/tester/own/own_err_named_field_object_moved.ts b/tslang/test/tester/own/own_err_named_field_object_moved.ts new file mode 100644 index 000000000..861827765 --- /dev/null +++ b/tslang/test/tester/own/own_err_named_field_object_moved.ts @@ -0,0 +1,33 @@ +// -mm=own: a field moves out of an object a `const` names only when nothing sees the object after +// the move but its release (spec 64); the object moved after its field is taken: its new owner finds the field empty. +class Item { + constructor(public n: number) {} +} + +class Holder { + value = new Item(3); + show() { + return this.value.n; + } +} + +const kept: Holder[] = []; + +function keep(r: Holder) { + kept.push(r); +} + +function same(r: Holder) { + return r; +} + +function take() { + const r = new Holder(); + const v = r.value; + keep(r); + return v; +} + +function main() { + print(take().n); +} diff --git a/tslang/test/tester/own/own_err_named_field_read_again.ts b/tslang/test/tester/own/own_err_named_field_read_again.ts new file mode 100644 index 000000000..5e989d330 --- /dev/null +++ b/tslang/test/tester/own/own_err_named_field_read_again.ts @@ -0,0 +1,33 @@ +// -mm=own: a field moves out of an object a `const` names only when nothing sees the object after +// the move but its release (spec 64); the field read again after it is taken: it is empty by then. +class Item { + constructor(public n: number) {} +} + +class Holder { + value = new Item(3); + show() { + return this.value.n; + } +} + +const kept: Holder[] = []; + +function keep(r: Holder) { + kept.push(r); +} + +function same(r: Holder) { + return r; +} + +function take() { + const r = new Holder(); + const v = r.value; + print(r.value.n); + return v; +} + +function main() { + print(take().n); +} diff --git a/tslang/test/tester/own/own_named_field_take.ts b/tslang/test/tester/own/own_named_field_take.ts new file mode 100644 index 000000000..abda05978 --- /dev/null +++ b/tslang/test/tester/own/own_named_field_take.ts @@ -0,0 +1,109 @@ +// A field taken out of an object a `const` names, `new`'s or a call's own, that nothing sees after the +// move but its release (spec 64): `return r.value`, `c ? init : r.value`, `init ?? r.value`, the read used +// before it is returned, another field read after, a push of it, and `new` in a loop; a merge only read +// stays a borrow. The field is left +// empty at the read, so the object's release frees nothing of what was taken. Each step churns, so a +// value freed with its object reads garbage; every model runs it. +class Item { + constructor(public n: number) {} +} + +class Holder { + value = new Item(3); + other = new Item(9); +} + +class Pair { + constructor(public item: Item, public tag: number) {} +} + +function churn() { + const junk: Item[] = []; + for (let i = 0; i < 64; i++) junk.push(new Item(999)); +} + +function pair(n: number) { + return new Pair(new Item(n), n); +} + +function returned() { + const r = new Holder(); + return r.value; +} + +function chosen(c: boolean, initial: Item) { + const r = new Holder(); + return c ? initial : r.value; +} + +function orDefault(initial?: Item) { + const r = new Holder(); + return initial ?? r.value; +} + +function usedFirst() { + const r = new Holder(); + const v = r.value; + churn(); + print(v.n + r.other.n); + return v; +} + +// only read, the merge stays a borrow: the object is used after it +function readOnly(c: boolean, initial: Item) { + const r = new Holder(); + const x = c ? initial : r.value; + return x.n + r.other.n; +} + +function pushed() { + const out: Item[] = []; + for (let i = 0; i < 3; i++) { + const r = new Holder(); + out.push(r.value); + } + + return out; +} + +function ofCall() { + const p = pair(8); + const t = p.tag; + return p.item.n + t; +} + +function test() { + let s: number = 0; + const a = returned(); + churn(); + s += a.n; + const b = chosen(false, new Item(4)); + const c = chosen(true, new Item(4)); + churn(); + s += b.n + c.n; + const d = orDefault(); + const e = orDefault(new Item(5)); + churn(); + s += d.n + e.n; + const f = usedFirst(); + churn(); + s += f.n; + const kept = new Item(1); + s += readOnly(false, kept) + readOnly(true, kept) + kept.n; + const items = pushed(); + churn(); + for (const item of items) s += item.n; + s += ofCall(); + return s; +} + +function main() { + let ok = 0; + for (let i = 0; i < 300; i++) { + if (test() == 3 + 7 + 8 + 3 + 12 + 10 + 1 + 9 + 16) ok++; + churn(); + } + + assert(ok == 300, "ok"); + print("done."); +}