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 e243d7fe4..8d5f0a184 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 @@ -5453,3 +5453,72 @@ that escapes owns what it captures ... its value is the caller's`. Two shapes, t `own_literal_let_captures` captures `let`s - inline in a call, in a `const` literal called and given on, given to an interface - assigns them after, and captures parameters in literals given to an object-type and an interface parameter, churning between steps, under own, rc, gc and none. + +## 70. A field that refers back to its own object, 2026-10-29 + +`class A { n = 1; fn = () => this.n; }` was `a closure that escapes owns what it captures, but -mm=own +cannot move this variable into it: its value is the caller's`, and `fn = this.get` was `'this value' +takes a second reference`. Both are a **back-reference**: a value stored into a field of an object that +holds the object itself. Own had no such value. An escaping closure owns what it captures (§17), so the +object would own the field, the field the closure's box, and the box the object. gc and rc compiled +both. rc's counts make the cycle a leak, which this section does not change. + +Such a value now **borrows** its object (USER decisions, 2026-10-29: Q1 every model, Q2 an error, Q3 +only a field of `this` itself). The field owns the closure, as it owns any value, and the box's release +frees the box, not the object. What the field holds is only ever reached through the object, so the +object bounds it: a read of the field is §14's borrow, and nothing takes it out. + +- **`this` is captured by copy** (MLIRGen, every model). An arrow reading a variable captured it by + reference, through a cell (`ts.Param {captured}`), so that an assignment after reaches the closure. + `this` is never assigned, so a copy is the same value, and a member of any class now gives + `setCaptureByValue` to its `this`, as a `@value` class's did. There is no cell, so the box holds the + object itself, which also saves a heap cell per closure. gc and rc box the copy as any copy, and rc + retains it as the cell held it before: the same cycle. +- **A back-reference's box** (`isBackReferenceBox`, `OwnershipFacts.h`) holds the member's `this` + (`isMemberThis`: the first parameter, of a class type, or a read of its slot) and nothing else that + owns a block. The closure over it is stored once, into a field of that `this` (`isFieldOfMemberThis`: + of its object, or of a base class's storage in it, §57). Anything else done with the closure is a + call through it, a view of it, or a count of it. Inference (`classifyClosures`) marks the copies + borrowed (`OWN_CAPTURE_BORROW_ATTR_NAME`) and the closure `__own_borrows_captures`, so its routine + frees the box alone (`tsfrecb_`). rc's retain of the copy goes (`fieldBorrowRetains`). +- **`this` in any box keeps nothing** (the signature pass's `keeps`): the object is the caller's, which + no box can own, so a member storing it into a capture box does not keep its `this`. Inference decides + the closure: one that does not escape borrows it, as it borrowed the cell before. A closure with cells + borrows every copy already (§16); one with copies only borrows them when it holds `this` and none of + them was made for it (`borrowsCopies`; `own_closure_borrow`'s `() => this.c.x`, `own_raytrace`'s + `addLight`). A back-reference borrows it as above. Any other escaping closure over `this` + (`return () => this.n`) stays an error, now `'this value' is a parameter, kept here, but -mm=own cannot + make the callers of ... give it up`. +- **A bound method of `this`** (`ThisSymbolRef`/`ThisVirtualSymbolRef` of the member's `this`, + `isBoundMethodOfMemberThis`) stored into a field of `this` already borrows: the closure's tag is null + for a bound method, and its release frees nothing of the object. `keeps` takes the store for no + keeping, and inference drops rc's retain for it. +- **The fields** (`OWN_BACK_REFERENCE_FIELDS_ATTR_NAME`, `ts.own_back_reference_fields`): the signature + pass lists each class storage and position a back-reference is stored into (`isBackReferenceStore`). + `checkPlaceRead` takes nothing out of such a field (`isBackReferenceField`): neither specs 48/65's + `fieldTakeOf` nor spec 63/64's `temporaryFieldTakeOf`. So `return a.fn`, `h.call = a.fn` and the + like stay borrows of the object, and are `borrows a field and cannot be stored, returned or + captured`, the error any other borrowed field gives (Q2), rather than a new message. +- **Calling it** (`a.fn()`) needs nothing new. A body that writes the field it is called through + (`fn = () => { this.fn = g; return this.n; }`) frees its own box during the call, and that is safe: + a closure body reads each value captured by copy out of its box once, at its entry, so the box is not + read after. The code is static. The negative the proposal named, `own_err_back_reference_rewrites`, + is not one. +- **Moving the object** (`let b = a`, `return a`, an array that holds it) moves the field with it. The + box still points at the same object, which the new owner keeps. + +A closure that captures anything besides `this` that owns a block (a parameter, a local, another +object) is no back-reference and keeps §17's rules. So does a back-reference stored anywhere but a +field of that `this`, and one in an array the object holds or in a nested object's field (Q3). + +`own_back_reference` stores arrow fields reading `this` (one with a parameter, one calling another and +a method), a bound method field, a field a method assigns and one main assigns, a derived class's field +and one its constructor stores, and calls them after the object moved and in objects an array holds. +It churns between steps, under own, rc, gc and none, and own emits no counting. Negatives: +`own_err_back_reference_taken` (`return c.get`), `own_err_back_reference_stored` (`h.call = c.get`) and +`own_err_back_reference_captures` (a closure capturing `this` and a parameter, §17's error). Two million +objects with an arrow field each run in a flat 49 MB under own. + +Not here: an arrow field reading a getter (`fn = () => this.prop` with `get prop()`) fails in every model, +because its arrow is kept as returning void (PR #744). A call through a field returning a string, under +`--no-default-lib`, is `borrows a field but is used here after ...` whatever the field holds, as before. diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 29bf2ee7e..7a815e58b 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -134,6 +134,8 @@ // Its release routine skips them, and a borrowing `.captured` box frees its cells but not what // they hold. #define OWN_BORROWING_FIELDS_ATTR_NAME "ts.own_borrowing_fields" +// [class storage type, field position] of each field a back-reference is stored into (own spec 70) +#define OWN_BACK_REFERENCE_FIELDS_ATTR_NAME "ts.own_back_reference_fields" // -mm=own only, set by OwnershipSignaturePass on the module, in the same shape: the fields of a // generator's state object - its locals - read only to be yielded (`const groups = [...r]; yield // groups`). A yield moves what such a field holds to the caller, so the field never owns it: an diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 37aa54e73..6c431b782 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1626,8 +1626,11 @@ namespace mlirgen param->setReadWriteAccess(); // `this` of a @value class's method is the value, which nothing assigns: a closure // takes a copy of it, not its cell (so a `ref` named `this` in a capture is the - // constructor's slot alone) - if (param->getName() == THIS_NAME && index == firstIndex && getValueClassInfo(param->getType())) + // constructor's slot alone). So does `this` of any class's member: the copy is the + // same object, with no cell for it (own spec 70: a field's closure over `this` + // borrows the object, which a cell moved into the box could not) + if (param->getName() == THIS_NAME && index == firstIndex && + (getValueClassInfo(param->getType()) || isa(param->getType()))) { param->setCaptureByValue(); } diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 5dbf30dcc..43ff375f7 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -1343,6 +1343,206 @@ inline mlir_ts::CreateBoundFunctionOp closureOfBox(mlir::Value box) return {}; } +// `this` of the class member a function is: its first parameter, of a class type, or a read of the +// parameter's slot, seen through views (spec 70) +inline bool isMemberThis(mlir::Value value) +{ + value = rootOf(value); + // the parameter's slot: `ts.Param` in MLIRGen, `ts.Variable` initialized from it by the time the + // own passes run + if (auto loadOp = value.getDefiningOp()) + { + auto *slot = loadOp.getReference().getDefiningOp(); + if (auto varOp = mlir::dyn_cast_or_null(slot); varOp && varOp.getInitializer()) + { + value = varOp.getInitializer(); + } + else if (auto paramOp = mlir::dyn_cast_or_null(slot)) + { + value = paramOp->getOperand(0); + } + else + { + return false; + } + } + + auto argument = mlir::dyn_cast(value); + return argument && argument.getArgNumber() == 0 && argument.getOwner()->isEntryBlock() && + mlir::isa(argument.getOwner()->getParentOp()) && + mlir::isa(argument.getType()); +} + +// A field of the member's `this`: of its object, or of a base class's storage in it (spec 57) +inline bool isFieldOfMemberThis(mlir::Value ref) +{ + auto propertyRefOp = ref.getDefiningOp(); + if (!propertyRefOp) + { + return false; + } + + auto object = propertyRefOp->getOperand(0); + while (auto baseRefOp = object.getDefiningOp()) + { + auto refType = mlir::dyn_cast(baseRefOp.getType()); + if (!refType || !mlir::isa(refType.getElementType())) + { + return false; + } + + object = baseRefOp->getOperand(0); + } + + return isMemberThis(object); +} + +// A back-reference's box (spec 70): it holds the member's `this` and nothing else that owns a block, +// and the closure over it is stored once, into a field of that `this`; anything else done with the +// closure is a call through it, a view of it, or a count of it. The box borrows the object: the +// field owns the closure, and the object bounds it. +inline bool isBackReferenceBox(mlir::Value box) +{ + auto boundOp = closureOfBox(box); + if (!boundOp) + { + return false; + } + + auto holdsThis = false; + for (auto *user : box.getUsers()) + { + if (user == boundOp.getOperation() || mlir::isa(user)) + { + continue; + } + + auto propertyRefOp = mlir::dyn_cast(user); + if (!propertyRefOp) + { + return false; + } + + for (auto *fieldUser : propertyRefOp->getUsers()) + { + auto storeOp = mlir::dyn_cast(fieldUser); + if (!storeOp || storeOp.getReference() != propertyRefOp.getResult()) + { + return false; + } + + if (isMemberThis(storeOp.getValue())) + { + holdsThis = true; + } + else if (!holdsNoBlock(storeOp.getValue())) + { + return false; + } + } + } + + if (!holdsThis) + { + return false; + } + + auto stores = 0; + llvm::SmallVector pending{boundOp.getResult()}; + while (!pending.empty()) + { + auto value = pending.pop_back_val(); + for (auto *user : value.getUsers()) + { + if (mlir::isa(user)) + { + continue; + } + + if (auto storeOp = mlir::dyn_cast(user); + storeOp && storeOp.getValue() == value && isFieldOfMemberThis(storeOp.getReference())) + { + ++stores; + continue; + } + + if (isView(user)) + { + pending.push_back(user->getResult(0)); + continue; + } + + return false; + } + } + + return stores == 1; +} + +// The class storage a field is in: of a class object, or of a base class's storage in one; null for +// any other field +inline mlir_ts::ClassStorageType fieldOwnerStorage(mlir_ts::PropertyRefOp propertyRefOp) +{ + auto type = propertyRefOp->getOperand(0).getType(); + if (auto refType = mlir::dyn_cast(type)) + { + type = refType.getElementType(); + } + + if (auto classType = mlir::dyn_cast(type)) + { + return mlir::dyn_cast(classType.getStorageType()); + } + + return mlir::dyn_cast(type); +} + +// Is `ref` a field some back-reference is stored into (OWN_BACK_REFERENCE_FIELDS_ATTR_NAME, the +// signature pass's)? What it holds may borrow the object it is in, so it is never taken out of it +inline bool isBackReferenceField(mlir::Value ref) +{ + auto propertyRefOp = ref.getDefiningOp(); + auto storage = propertyRefOp ? fieldOwnerStorage(propertyRefOp) : mlir_ts::ClassStorageType(); + auto module = propertyRefOp ? propertyRefOp->getParentOfType() : mlir::ModuleOp(); + auto entries = module ? module->getAttrOfType(OWN_BACK_REFERENCE_FIELDS_ATTR_NAME) : mlir::ArrayAttr(); + if (!storage || !entries) + { + return false; + } + + return llvm::any_of(entries.getAsRange(), [&](mlir::ArrayAttr entry) { + return mlir::cast(entry[0]).getValue() == storage && + mlir::cast(entry[1]).getInt() == propertyRefOp.getPosition(); + }); +} + +// A method of the member's `this` bound to it (`this.m`), seen through views (spec 70). Its release +// frees nothing of the object (the closure's tag is null for a bound method): it borrows it +inline bool isBoundMethodOfMemberThis(mlir::Value value) +{ + auto *def = rootOf(value).getDefiningOp(); + return def && mlir::isa(def) && + isMemberThis(def->getOperand(0)); +} + +// A store of a back-reference into a field of the member's `this` (spec 70): a closure over a +// back-reference's box, or a bound method of that `this` +inline bool isBackReferenceStore(mlir_ts::StoreOp storeOp) +{ + if (!isFieldOfMemberThis(storeOp.getReference())) + { + return false; + } + + if (isBoundMethodOfMemberThis(storeOp.getValue())) + { + return true; + } + + auto boundOp = rootOf(storeOp.getValue()).getDefiningOp(); + return boundOp && isBackReferenceBox(boundOp.getThisVal()); +} + // Is this the slot of parameter `argument` - a local declared from it that owns nothing, is not // captured, and is never assigned, so every read of it is the argument? inline bool isParameterSlot(mlir_ts::VariableOp varOp, int &index) diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 9d5847f80..fac92aa00 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -8,8 +8,26 @@ namespace own_inference { + // A closure stored into a field of the object it captures (spec 70; isBackReferenceBox) + bool OwnershipInferencePass::isBackReference(Closure &closure) + { + return !closure.hasCells && isBackReferenceBox(closure.box); + } + void OwnershipInferencePass::classifyClosures() { + // a bound method of `this` stored into a field of `this` (spec 70): it borrows the object, so + // rc's reference for it goes, as a borrowing field's does + getFunction().walk([&](mlir_ts::StoreOp storeOp) { + if (isFieldOfMemberThis(storeOp.getReference()) && isBoundMethodOfMemberThis(storeOp.getValue())) + { + if (auto *retain = retainBefore(storeOp.getValue(), storeOp)) + { + fieldBorrowRetains.insert(retain); + } + } + }); + getFunction().walk([&](mlir_ts::CreateBoundFunctionOp boundOp) { if (!boundOp->hasAttr(OWNS_CAPTURE_ATTR_NAME) || closureOfBox(boundOp.getThisVal()) != boundOp) { @@ -60,6 +78,25 @@ namespace own_inference closure->escape = escape; } + // a back-reference (spec 70): the field owns the closure, and its box borrows the object - + // its routine frees the box alone (`__own_borrows_captures`), and rc's reference for the + // copy goes, as a borrowing field's does + if (isBackReference(*closure)) + { + for (auto &fill : closure->fills) + { + if (auto *retain = retainBefore(fill.second.getValue(), fill.second)) + { + fieldBorrowRetains.insert(retain); + } + + setAttrTracked(fill.second, OWN_CAPTURE_BORROW_ATTR_NAME); + } + + setAttrTracked(boundOp, OWN_BORROWS_CAPTURES_ATTR_NAME); + return; + } + // copies only: the box owns them (phase 4); only an alias needs deciding - unless the box // is given to a generator's maker whose result borrows from it if (!closure->hasCells) @@ -67,14 +104,18 @@ namespace own_inference // ...and only when every copy has an owner of its own: the box frees itself alone, so a // value made for it (a callback that captures, `a.filter((x) => x > n)`) would be // nobody's + // ...or when it holds the member's `this` (a copy, spec 70), the caller's, as a closure + // that does not escape borrowed the cell it held before + auto noneFresh = llvm::none_of(closure->fills, [&](auto &fill) { + auto value = fill.second.getValue(); + return !holdsNoBlock(value) && isFresh(rootOf(value)); + }); + auto holdsThis = llvm::any_of(closure->fills, [&](auto &fill) { return isMemberThis(fill.second.getValue()); }); closure->borrowsCopies = - !closure->escape && - llvm::any_of(closure->boxUses, - [](mlir::Operation *use) { return use->hasAttr(OWN_RESULT_BOUNDED_ATTR_NAME); }) && - llvm::none_of(closure->fills, [&](auto &fill) { - auto value = fill.second.getValue(); - return !holdsNoBlock(value) && isFresh(rootOf(value)); - }); + !closure->escape && noneFresh && + (holdsThis || llvm::any_of(closure->boxUses, [](mlir::Operation *use) { + return use->hasAttr(OWN_RESULT_BOUNDED_ATTR_NAME); + })); if (!closure->borrowsCopies) { if (!closure->escape && closure->aliased) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 6623fac24..7eeae7a77 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -253,6 +253,7 @@ 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(); + bool isBackReference(Closure &closure); // 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(); diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index c564ec91a..54fc60846 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -828,8 +828,12 @@ namespace own_inference // A value taken out of a field of an owning record local by one move, the field read again // by nothing before the local ends (spec 48): the `value` of the record `next()` returns, in // a `for...of` or a spread that keeps what a generator yields + // nothing is taken out of a field a back-reference is stored into (spec 70): what it holds may + // borrow the object it is in. Such a read stays a borrow, bounded by the object + auto readRef = mlir::isa(read) ? mlir::cast(read).getReference() : mlir::Value(); + auto backReference = readRef && isBackReferenceField(readRef); FieldTake take; - if ((kept || letKept) && !countedHandle && fieldTakeOf(read, kept ? kept : letKept, take)) + if ((kept || letKept) && !countedHandle && !backReference && fieldTakeOf(read, kept ? kept : letKept, take)) { takenOps.insert(take.retain); takenOps.insert(take.taker); @@ -845,7 +849,7 @@ namespace own_inference // ...or out of a field of a call's own result, released as a temporary right after the read // (spec 63): `init ?? next(xs, 0).value`. The temporary frees nothing of it then, so nothing // after the move can see the release. - if (!take.taker && kept && !countedHandle && temporaryFieldTakeOf(read, kept, take)) + if (!take.taker && kept && !countedHandle && !backReference && temporaryFieldTakeOf(read, kept, take)) { takenOps.insert(take.retain); takenOps.insert(take.taker); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 634b48af6..2643494ed 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -30,6 +30,27 @@ namespace own_signature } } + // the fields back-references are stored into (spec 70): what they hold borrows the object they + // are in, so inference takes nothing out of them + llvm::SetVector backReferenceFields; + module.walk([&](mlir_ts::StoreOp storeOp) { + auto propertyRefOp = storeOp.getReference().getDefiningOp(); + auto storage = propertyRefOp ? fieldOwnerStorage(propertyRefOp) : mlir_ts::ClassStorageType(); + if (!storage || !isBackReferenceStore(storeOp)) + { + return; + } + + backReferenceFields.insert(mlir::ArrayAttr::get( + &getContext(), {mlir::TypeAttr::get(storage), + mlir::IntegerAttr::get(mlir::IntegerType::get(&getContext(), 32), propertyRefOp.getPosition())})); + }); + if (!backReferenceFields.empty()) + { + module->setAttr(OWN_BACK_REFERENCE_FIELDS_ATTR_NAME, + mlir::ArrayAttr::get(&getContext(), backReferenceFields.getArrayRef())); + } + if (auto functionsDropping = module->getAttrOfType(SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME)) { for (auto entry : functionsDropping) @@ -766,6 +787,21 @@ namespace own_signature return false; } + // `this` in a closure's box (captured by copy, spec 70): the object is the caller's, which + // no box can own. A closure that does not escape borrows it, as it did the cell; one stored + // into a field of `this` is a back-reference; any other one is inference's error + if (auto propertyRefOp = storeOp.getReference().getDefiningOp(); + propertyRefOp && isMemberThis(used) && closureOfBox(propertyRefOp->getOperand(0))) + { + return false; + } + + // ...or a bound method of `this` stored into a field of `this`: it borrows the object + if (isBoundMethodOfMemberThis(storeOp.getValue()) && isFieldOfMemberThis(storeOp.getReference())) + { + return false; + } + // a string stored by a statement that may run again (`a[i] = value` in `fill`'s loop) is // no one move: each store takes a copy, and the parameter stays a borrow (spec 50) if (isCopyableString(used.getType()) && mayRunAgain(user)) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index aebbf80b5..6d0cf0ed4 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4065,7 +4065,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_literal_interface_captures own_literal_let_captures own_interface_generic_method + 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_literal_let_captures own_interface_generic_method own_back_reference 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") @@ -4103,7 +4103,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_literal_interface_captures own_literal_let_captures own_interface_generic_method + 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_literal_let_captures own_interface_generic_method own_back_reference 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") @@ -4820,7 +4820,10 @@ set(own_error_cases "own_err_let_field_global|:15:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_let_field_read_again|:17:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_let_field_loop|:17:9: error: '[^']*' borrows a field and cannot be stored, returned or captured" - "own_err_let_field_captured|:18:5: error: '[^']*' borrows a field and cannot be stored, returned or captured") + "own_err_let_field_captured|:18:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_back_reference_taken|:10:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_back_reference_stored|:15:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_back_reference_captures|:12:20: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: its value is the caller's") 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_back_reference.ts b/tslang/test/tester/own/own_back_reference.ts new file mode 100644 index 000000000..d5f0f91d3 --- /dev/null +++ b/tslang/test/tester/own/own_back_reference.ts @@ -0,0 +1,89 @@ +// A field that refers back to its own object (spec 70): an arrow reading `this`, a bound method of +// `this`. Its closure's box borrows the object - the field owns the closure, the box frees itself +// alone - and the object bounds every use of it. Stored by a field initializer, a constructor and a +// method, in a class and one extending it; read and called through the object, after it is moved. +// Each step churns, so anything freed too early reads garbage; every model runs it. +class Junk { + constructor(public n: number) {} +} + +function churn() { + const junk: Junk[] = []; + for (let i = 0; i < 64; i++) junk.push(new Junk(999)); +} + +class Counter { + n: number = 1; + get = () => this.n; + add = (k: number) => this.n + k; + twice = () => this.get() + this.get(); + scaled = (k: number) => this.get() * k + this.value(); + + value() { + return this.n * 10; + } + + bound = this.value; + + double() { + this.get = () => this.n * 2; + } +} + +class Wider extends Counter { + more = () => this.add(100); + + constructor() { + super(); + this.twice = () => this.n + 1000; + } +} + +function make(n: number) { + const c = new Counter(); + c.n = n; + return c; +} + +function main() { + const c = new Counter(); + churn(); + assert(c.get() == 1 && c.add(2) == 3 && c.twice() == 2, "arrow fields"); + assert(c.scaled(3) == 13, "an arrow calling another and a method"); + assert(c.bound() == 10, "a bound method field"); + + c.n = 5; + churn(); + assert(c.get() == 5 && c.bound() == 50, "they read the object when called"); + + c.double(); + churn(); + assert(c.get() == 10, "assigned in a method"); + + c.get = () => 7; + assert(c.get() == 7, "assigned from outside"); + + const w = new Wider(); + churn(); + assert(w.more() == 101 && w.twice() == 1001, "a derived class's, and one its constructor stores"); + + let moved = make(3); + churn(); + let other = moved; + assert(other.get() == 3 && other.add(1) == 4, "after the object moved"); + + const all: Counter[] = []; + for (let i = 0; i < 100; i++) { + all.push(make(i)); + } + + churn(); + let total = 0; + for (const item of all) { + total += item.get(); + } + + assert(total == 4950, "objects an array holds"); + + print("done."); +} diff --git a/tslang/test/tester/own/own_err_back_reference_captures.ts b/tslang/test/tester/own/own_err_back_reference_captures.ts new file mode 100644 index 000000000..7a3ec6d2e --- /dev/null +++ b/tslang/test/tester/own/own_err_back_reference_captures.ts @@ -0,0 +1,21 @@ +// A closure stored into a field of `this` that captures something besides `this` (a parameter) is no +// back-reference (spec 70): an escaping closure owns what it captures, and the parameter is the caller's. +class Item { + n: number = 2; +} + +class Counter { + n: number = 1; + get = () => 0; + + setup(item: Item) { + this.get = () => this.n + item.n; + } +} + +function main() { + const c = new Counter(); + const item = new Item(); + c.setup(item); + print(c.get()); +} diff --git a/tslang/test/tester/own/own_err_back_reference_stored.ts b/tslang/test/tester/own/own_err_back_reference_stored.ts new file mode 100644 index 000000000..cd2531782 --- /dev/null +++ b/tslang/test/tester/own/own_err_back_reference_stored.ts @@ -0,0 +1,17 @@ +// A back-reference read out of its object is a borrow of the object (spec 70): it cannot be stored +// into another object, which may outlive it. +class Counter { + n: number = 1; + get = () => this.n; +} + +class Holder { + call: () => number = () => 0; +} + +function main() { + const c = new Counter(); + const h = new Holder(); + h.call = c.get; + print(h.call()); +} diff --git a/tslang/test/tester/own/own_err_back_reference_taken.ts b/tslang/test/tester/own/own_err_back_reference_taken.ts new file mode 100644 index 000000000..94d93e70d --- /dev/null +++ b/tslang/test/tester/own/own_err_back_reference_taken.ts @@ -0,0 +1,15 @@ +// A field a back-reference is stored into (spec 70) is never taken out of its object: its closure +// borrows the object, which the function releases when it returns. +class Counter { + n: number = 1; + get = () => this.n; +} + +function take() { + const c = new Counter(); + return c.get; +} + +function main() { + print(take()()); +}