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 bc7f45af3..e84875744 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 @@ -920,8 +920,8 @@ drop-free `.instanceOf` call, the payload is borrowed for as long as the box liv forwarding another's borrow, a field-or-`null` result, a returned parameter), `own_param_kept` (field, forwarding, method into `this`, push, constructor parameter property), `own_any_box`. - **Negatives:** - - calls that drop: `own_err_call_drops_indirectly`, `own_err_call_given_borrow`, - `own_err_call_this_borrow`, `own_err_exported_virtual_call`; + - calls that drop: `own_err_call_drops_indirectly`, `own_counted_call_given_borrow` (counted since TSLANG 240), + `own_counted_call_this_borrow` (counted since TSLANG 240), `own_err_exported_virtual_call`; - borrowed results: `own_err_borrowed_result_stored`, `own_err_borrowed_result_outlives`, `own_err_borrowed_result_let_outlives`, `own_err_borrowed_result_escapes`, `own_err_borrowed_result_family`; @@ -3560,7 +3560,7 @@ rc, gc and none, AOT and JIT, and on Linux; own emits no counting. `own_interfac function field through a global and a local `Shared` of a literal, through a parameter with no handle, and through a handle given as a parameter, each after churn, under the four models (counted, so not in `own_test`), and `--verify-ownership` is quiet under own and rc. The five §27 negatives -now export their interface (the open form, same texts). New negatives: `own_err_interface_exported_impl` +now export their interface (the open form, same texts). New negatives: `own_counted_interface_exported_impl` (counted since TSLANG 240) (the plan's program with `export class B`), `own_err_interface_family_disagrees`, `own_err_interface_member_drops`, `own_err_interface_from_interface`, `own_err_interface_result_outlives`, `own_err_interface_fn_field_drops`, @@ -3636,7 +3636,7 @@ a block freed too early is reused before it is read. function); the second remains. `own_declared_scalar_no_drops` holds a field's borrow across `sqrt`, across a function that calls `sqrt` and `floor`, and across a call through a - closed interface whose member does; `own_err_declared_drops` (`strlen(s: string)`) is unchanged. + closed interface whose member does; `own_counted_declared_drops` (counted since TSLANG 238-240) (`strlen(s: string)`) is unchanged. - **A `public` method of a class no other module can name** (controller ruling) is not callable from another module: the class is not exported (its vtable is private), not a word of `__decls`, and not in the type of an exported or declared function or of an exported or imported global (a derived @@ -3665,11 +3665,11 @@ a block freed too early is reused before it is read. Teeth: with function reinterpretations not opening anything, `own_err_interface_fn_any_param` and `_result` compile and their AOT runs fail with `0xC0000374` (with and without `--opt`), and `_drops` prints 77777 instead of 5 (gc 5). With every declaration without `export` taken as destroying -nothing, `own_err_declared_drops` compiles, and so does a program that lends a field and passes the +nothing, `own_counted_declared_drops` (counted since TSLANG 238-240) compiles, and so does a program that lends a field and passes the field's object to a declared `free(p: V)`; its AOT run fails with `0xC0000374`. With a `public` method's class never nameable, `own_err_interface_public_reachable` compiles; with every module taken for an executable, `own-exe-exports.cmake` fails (the object file and the DLL compile), and so do -`own_err_interface_exported_impl` and `own_err_interface_keeps_param`. The last two rules protect +`own_counted_interface_exported_impl` (counted since TSLANG 240) and `own_err_interface_keeps_param`. The last two rules protect callers in another module, which no single-module run can show. Corpus (`--emit=obj`, not an executable): 528 of 693 before this section and after, the same files. @@ -4121,7 +4121,7 @@ start value, a named callback `add` that only borrows its accumulator beside `pi under own, rc, gc and none, AOT and JIT, and on Linux; own emits no counting, and `--verify-ownership` is quiet on it under own and rc. Negatives: `own_err_mixed_return` (rewritten), `own_err_mixed_return_join_use` (a field read out of the kept parameter before the join -and used after it: `is moved here on some paths only`), `own_err_callback_escapes` (`pick` also +and used after it: `is moved here on some paths only`), `own_counted_callback_escapes` (counted since TSLANG 238-240) (`pick` also called through a `let`: `cannot make the callers of 'pick' give it up`), `own_err_callback_disagrees`, `own_err_callback_promoted_used`. `own_err_borrowed_result_escapes` passed `firstOf` straight to `apply`; the call through `g` now reaches only `firstOf` and gets its borrowed result, so the program @@ -4787,7 +4787,7 @@ function was not a function type. `own_callback_forwarded` sorts an `Item[]` through an optional comparison given on (and with none given), gives a callback on twice (`eachTwice` to `each`) and to the function itself, and calls an optional comparison once tested, churning between steps, under own, rc, gc and none; own emits no counting. Negatives: -`own_err_callback_forwarded_drops` (the function passed to `sortIt` replaces a global array, so +`own_counted_callback_forwarded_drops` (counted since TSLANG 240) (the function passed to `sortIt` replaces a global array, so `selectionSort`'s call with two elements is a use of them after they may be released) and `own_err_callback_forwarded_keeps` (it keeps its argument in a global array, for good, which a call through a value cannot make immortal). @@ -5025,7 +5025,7 @@ that may destroy anything, and so was every call that gave the closure on. `own_callback_captured` sums, finds the largest and walks through callbacks given to a closure that calls them and to a local that names them, from a class's methods over the array a field holds, churning between steps, under own, rc, gc and none; own emits no counting. Negative: -`own_err_callback_captured_drops`, whose callback replaces a global array that the walk's element +`own_counted_callback_captured_drops` (counted since TSLANG 238-240), whose callback replaces a global array that the walk's element may be part of. Not here, then: a closure held in a local and called, and a callback stored into a field or @@ -5074,8 +5074,8 @@ local is a view of the closure, called by name with its box. `own_callback_shapes` walks an array a class holds through a closure in a local, a callback stored into a field by a constructor and by a method, and callbacks a function returns, called through a local and given on, reading each element again after the call and churning between steps, under -own, rc, gc and none; own emits no counting. Negatives: `own_err_callback_field_drops` and -`own_err_callback_returned_drops`, whose callbacks replace a global array the walk's element may be +own, rc, gc and none; own emits no counting. Negatives: `own_counted_callback_field_drops` (counted since TSLANG 238-240) and +`own_counted_callback_returned_drops` (counted since TSLANG 238-240), whose callbacks replace a global array the walk's element may be part of. Not here: a class whose object becomes an interface or `any` keeps its fields' families open; so @@ -5098,7 +5098,7 @@ a `!ts.ref>`), where the family saw no access of its interface, `any`, `object`, `unknown` or a union. A class-to-class cast (`Sub` to `Walker`) keeps it. `own_callback_extended` stores and calls the base's field from a derived class and one two levels -down, under own, rc, gc and none; own emits no counting. Negative: `own_err_callback_extended_drops`, +down, under own, rc, gc and none; own emits no counting. Negative: `own_counted_callback_extended_drops` (counted since TSLANG 238-240), whose derived class stores a function that replaces a global array the walk's element may be part of. Not here: a class whose object, or a derived class's, becomes `any` keeps its fields' families open; @@ -5166,7 +5166,7 @@ vtable holds (§58). its callback field stored by the constructor and by a method, under own, rc, gc and none; own emits no counting. `own_callback_interface_slot` calls two classes' methods through an interface, directly, and with a caller's callback parameter given on through the interface. Negatives: -`own_err_callback_cast_field_drops` (a draining callback stored into a field of a class cast to `any` +`own_counted_callback_cast_field_drops` (counted since TSLANG 240) (a draining callback stored into a field of a class cast to `any` and back), `own_err_callback_interface_slot_drops` (a callback given only through the interface still counts for a direct call that lends the global array it replaces) and `own_err_callback_interface_slot_targets` (a callback parameter given on through the slot reaches @@ -6041,7 +6041,7 @@ the way back from a `return`) would leave one unreleased - the ownership verifie own a clause local is decided as any local: `own_err_borrow_catch_local` / `_finally_local` now report it where it is given what another only borrows. -Tests: `own_err_capture_block_closure`, `own_moved_some_paths_break`, `00catch_finally_locals_own` (rc, +Tests: `own_counted_capture_block_closure` (counted since TSLANG 238-240), `own_moved_some_paths_break`, `00catch_finally_locals_own` (rc, gc, none; refused under own), `00catch_finally_owned_locals_eh` (every model). Fuzz seeds 920000 and 921000 x500: no failure. diff --git a/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md b/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md index 452f62dca..ec5f5b4bf 100644 --- a/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md +++ b/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md @@ -40,7 +40,7 @@ kinds: that may free it is copied for the call, and the copy released after it, when the call is a callback (a function value nothing can mark `@nodrops`); a call that keeps it takes the copy. A direct call that may free it stays an error, so `@nodrops` keeps its meaning - (`own_err_declared_drops`). A string given twice is copied twice (it was + (`own_counted_declared_drops` (counted since TSLANG 238-240)). A string given twice is copied twice (it was `own_err_string_call_keeps_twice`, an error for want of a retain to turn into a copy). 5. **A parameter kept on some paths only** is released on the others (spec 33's exit releases and spec 30's edge releases): `takenParams` is the parameters a move reaches every return from, not @@ -101,7 +101,7 @@ kinds: Positive, under own (AOT and JIT): `own_generator_method_this`, `own_string_copy_call`, `own_param_kept_some_paths`, `own_method_callbacks`, `own_loop_read_again`, `own_length_drops_elements`, `own_tuple_param_kept`; each also prints the same under gc, rc and none. -Errors: `own_err_generator_method_reassigned`, `own_err_callback_method_overridden`. +Errors: `own_err_generator_method_reassigned`, `own_counted_callback_method_overridden` (counted since TSLANG 240). Retired: `own_err_param_kept_some_paths` (rule 5), `own_err_string_call_keeps_twice` (rule 4). ## 6. Objects in `Map` and `Set`: `Shared` diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index d9c116f7b..93ce602f9 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -56,6 +56,12 @@ namespace mlir_ts = mlir::typescript; // every path (`return this`). Given a temporary the caller owns no more after the call, the result is // the caller's own (spec 78). #define OWN_RESULT_ITSELF_ATTR_NAME "__own_result_itself" +// Beside OWN_RESULT_BORROWS_ATTR_NAME naming one argument (a plain borrow, no record): the places every path reads the +// result through, from that argument down - [position, slot type] pairs as a chain has them (a field's position, +// OWN_INTERFACE_FIELD_POSITION through an interface, -1 for an element). The caller's chain of the result has these +// places, as if it had read them itself, not "anywhere under the argument": `this.near(n)` returning +// `this.lists[slot]` is not dropped by a call that only writes `this.bag` (TSLANG 236). +#define OWN_RESULT_PLACES_ATTR_NAME "__own_result_places" // On the local an object literal of tuple type is built in, when it is an unboxed borrowing record // (OWN_RESULT_RECORD_UNBOXED_ATTR_NAME): the fields it borrows. #define OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME "__own_record_unboxed_fields" @@ -2545,6 +2551,15 @@ inline bool typeMayHold(mlir::ModuleOp module, mlir::Type holder, mlir::Type tar return typeMayHold(module, holder, optionalType.getElementType(), seen); } + // a value that holds no block (a number, a string's text is its own) frees nothing else, whatever the target - + // not a subclass's object either (TSLANG 237: an `int[]`'s elements) + if (mlir::isa(holder)) + { + return false; + } + // the target an object of its type only: an array, or a @final class's (not a base class's, whose // object may be a subclass's, held in a field of that type) if (auto targetClass = mlir::dyn_cast(target)) @@ -2561,9 +2576,7 @@ inline bool typeMayHold(mlir::ModuleOp module, mlir::Type holder, mlir::Type tar return true; } - if (mlir::isa(holder)) + if (mlir::isa(holder)) { return false; } @@ -2798,6 +2811,25 @@ inline mlir::Value boundThis(mlir::Value value) return {}; } +// The places a call's result is read through, from the argument it borrows (OWN_RESULT_PLACES_ATTR_NAME); none when +// the call does not say. +inline std::optional>> resultPlaces(mlir::Operation *op) +{ + auto attr = op ? op->getAttrOfType(OWN_RESULT_PLACES_ATTR_NAME) : mlir::ArrayAttr(); + if (!attr) + { + return std::nullopt; + } + + llvm::SmallVector> places; + for (auto entry : attr.getAsRange()) + { + places.push_back({mlir::cast(entry[0]).getInt(), mlir::cast(entry[1]).getValue()}); + } + + return places; +} + // The parameter whose argument `value` is a borrow of, or -1 (spec 2.4, borrowed-from-argument). // Seen through views, casts out of `!ts.opaque`, `ts.Unbox` (the payload an `any` box holds), the // object a method is called on, @@ -2958,6 +2990,135 @@ inline int borrowedParam(mlir::Value value, int depth = 0) return -1; } +// The places `value`, a borrow of parameter `param` (borrowedParam), is read through from the parameter down: each +// field (its position), field through an interface (OWN_INTERFACE_FIELD_POSITION) and element (-1), with its slot +// type, added to `places`. Merged values add each one's; a value that holds no block adds none. False where the way +// is not one of those: a handle's payload, a call's result that does not say its own places +// (OWN_RESULT_PLACES_ATTR_NAME), a union member's tuple - the result may then be anywhere under the parameter. +inline bool borrowedPlaces(mlir::Value value, int param, llvm::SmallVectorImpl> &places, + int depth = 0) +{ + if (depth > 32) + { + return false; + } + + auto add = [&](std::pair place) { + if (!llvm::is_contained(places, place)) + { + places.push_back(place); + } + }; + + value = rootOf(value); + if (auto argument = mlir::dyn_cast(value)) + { + if (argument.getOwner()->isEntryBlock()) + { + return static_cast(argument.getArgNumber()) == param; + } + + llvm::SmallVector merged; + if (!mergedInto(argument, merged)) + { + return false; + } + + return llvm::all_of(merged, [&](mlir::Value passed) { + return holdsNoBlock(passed) || borrowedPlaces(passed, param, places, depth + 1); + }); + } + + if (auto object = boundThis(value)) + { + return borrowedPlaces(object, param, places, depth + 1); + } + + auto *def = value.getDefiningOp(); + if (auto castOp = mlir::dyn_cast_or_null(def); + castOp && (mlir::isa(castOp.getIn().getType()) || + (mlir::isa(castOp.getIn().getType()) && + mlir::isa(castOp.getType())))) + { + return borrowedPlaces(castOp.getIn(), param, places, depth + 1); + } + + if (auto extractOp = mlir::dyn_cast_or_null(def)) + { + return borrowedPlaces(extractOp.getOperand(), param, places, depth + 1); + } + + if (auto unboxOp = mlir::dyn_cast_or_null(def)) + { + return borrowedPlaces(unboxOp.getIn(), param, places, depth + 1); + } + + if (auto unionValueOp = mlir::dyn_cast_or_null(def)) + { + return borrowedPlaces(unionValueOp->getOperand(0), param, places, depth + 1); + } + + if (auto place = placeBase(value)) + { + switch (place.kind) + { + case PlaceKind::Field: + add({value.getDefiningOp().getPosition(), value.getType()}); + break; + case PlaceKind::Element: + add({-1, value.getType()}); + break; + case PlaceKind::InterfaceField: + add({OWN_INTERFACE_FIELD_POSITION, value.getType()}); + break; + default: + return false; + } + + return borrowedPlaces(place.base, param, places, depth + 1); + } + + if (auto loadOp = mlir::dyn_cast_or_null(def)) + { + auto ref = loadOp.getReference(); + if (isPlace(ref)) + { + return borrowedPlaces(ref, param, places, depth + 1); + } + + auto index = -1; + auto varOp = ref.getDefiningOp(); + return varOp && isParameterSlot(varOp, index) && index == param; + } + + if (auto varOp = mlir::dyn_cast_or_null(def)) + { + auto index = -1; + return isParameterSlot(varOp, index) && index == param; + } + + // a plain borrow of one argument that says its places: those, then the argument's + if (def && isCall(def) && resultBorrows(def) >= 0 && !isRecordResult(def)) + { + auto indices = resultBorrowsAll(def); + auto calleePlaces = resultPlaces(def); + auto args = callArgs(def); + if (indices.size() != 1 || !calleePlaces || static_cast(indices.front()) >= args.size()) + { + return false; + } + + for (auto &calleePlace : *calleePlaces) + { + add(calleePlace); + } + + return borrowedPlaces(args[indices.front()], param, places, depth + 1); + } + + return false; +} + // ---- Borrowing records (spec 32) ---- // // An object literal boxed as an interface whose fields hold values it does not own - `this`, a diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index 10677d487..43ed8a425 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -893,9 +893,10 @@ namespace own_inference // `const model = this.model; model.push(0.0)` (TSLANG 62): the array changed in place, // through the slot that holds its header - the borrowed array, which the field sees. A // null header (an unset field) gets one in the local's slot only, which nothing frees: - // that is `undefined` in TypeScript terms, where `.push` throws (array spec, ruling T4-D) - if ((mlir::isa(user) || growsOnly(user)) && + // that is `undefined` in TypeScript terms, where `.push` throws (array spec, ruling T4-D). + // `xs.length = 0` too, which removes elements in place as `pop` does (TSLANG 237) + if (mlir::isa(user) && user->getOperand(0) == borrower.getResult()) { uses.push_back({user, {kills.begin(), kills.end()}}); @@ -1378,7 +1379,21 @@ namespace own_inference continue; } - // A result that borrows what it was given borrows this too, and is walked as it. + // A result that borrows what it was given borrows this too, and is walked as it - not a + // result that says which arguments it borrows, given this as another one: `t.copy(pts[0])` + // returning `t` (TSLANG 239) + if (isCall(user) && user->getNumResults() == 1 && borrowingCall(user->getResult(0)) == user) + { + auto args = callArgs(user); + auto borrowsThis = llvm::any_of(resultBorrowsAll(user), [&](int index) { + return static_cast(index) < args.size() && args[index] == pending.value; + }); + if (!borrowsThis) + { + continue; + } + } + for (auto result : user->getResults()) { if (mayPointInto(result) && seen.insert(result).second) diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 968b14370..24a7a4668 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -106,11 +106,21 @@ namespace own_inference // nobody's // ...or when it holds the member's `this` (a copy, spec 70) or another parameter's copy, // the caller's, as a closure that does not escape borrowed the cell it held before + // ...a value a named `const` owns (`const B = new Back()`, kept as its value: OWNED_RESULT_NAMED_ATTR_NAME) + // is no value made for the closure: the const releases it where its scope ends, and a closure that does + // not escape borrows it as it borrows a parameter (TSLANG 238; it moved into the first box) + auto ownedByNamedConst = [&](mlir::Value value) { + auto root = rootOf(value); + auto *def = root.getDefiningOp(); + return def && isFresh(root) && def->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME); + }; auto noneFresh = llvm::none_of(closure->fills, [&](auto &fill) { auto value = fill.second.getValue(); - return !holdsNoBlock(value) && isFresh(rootOf(value)); + return !holdsNoBlock(value) && isFresh(rootOf(value)) && !ownedByNamedConst(value); + }); + auto holdsParam = llvm::any_of(closure->fills, [&](auto &fill) { + return isBorrowableCapture(fill.second.getValue()) || ownedByNamedConst(fill.second.getValue()); }); - auto holdsParam = llvm::any_of(closure->fills, [&](auto &fill) { return isBorrowableCapture(fill.second.getValue()); }); closure->borrowsCopies = !closure->escape && noneFresh && (holdsParam || llvm::any_of(closure->boxUses, [](mlir::Operation *use) { diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index b1de7db7a..b0f7ddc1f 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -1327,6 +1327,21 @@ namespace own_inference (countedValues.contains(countedUnitOf(read->getResult(0))) || (isCall(read) && countedValues.contains(countedUnitOf(lentRootOf(read->getResult(0))))))) { + // ...but the call lends it back with no count of its own (`B.add(st)` returning `this`, a borrow the + // callee's own body gives without a retain): rc's release of its result, for the count an rc callee + // would have given, has none to give back - kept, it freed the counted object one release early + // (TSLANG 240: `const B = this.B; B.add(st); B.add(st)` crashed) + if (isCall(read) && !countedValues.contains(countedUnitOf(read->getResult(0)))) + { + for (auto *user : read->getResult(0).getUsers()) + { + if (mlir::isa(user)) + { + toErase.insert(user); + } + } + } + continue; } @@ -1602,6 +1617,7 @@ namespace own_inference returnedParams.clear(); getFunction().walk([](mlir::Operation *op) { for (auto *name : {OWN_PARAMS_ATTR_NAME, OWN_PARAMS_RELEASED_ATTR_NAME, OWN_RESULT_BORROWS_ATTR_NAME, + OWN_RESULT_PLACES_ATTR_NAME, OWN_RESULT_RECORD_ATTR_NAME, OWN_RESULT_RECORD_UNBOXED_ATTR_NAME, OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME, OWN_RECORD_TEMPORARY_ATTR_NAME, OWN_NO_DROPS_ATTR_NAME, OWN_DROP_FIELDS_ATTR_NAME, OWN_DROP_FIELD_OWNERS_ATTR_NAME, @@ -2540,6 +2556,13 @@ namespace own_inference borrows = !(storeOp && storeOp.getValue() == used) && !mlir::isa(user); } + // rc's release of a call's result that borrows an argument: not run under own - the result is lent, + // and the counted read's release is erased (checkPlaceReads' counted reads) + if (mlir::isa(user) && used == value && isCall(read) && borrowingCall(value) == read) + { + return; + } + if (!borrows) { usable = false; @@ -2733,6 +2756,17 @@ namespace own_inference mlir::OpBuilder builder(read->getContext()); builder.setInsertionPointAfter(read); + + // a call's result lent by an argument, no name holding it (`k.add(k.first())`, TSLANG 240): rc's release of + // the temporary, where its statement ends, gives back the count taken here - as rc's callee's count would be + if (!copied && isCall(read) && borrowingCall(value) == read && rootOf(value) == value && + llvm::any_of(value.getUsers(), [](mlir::Operation *user) { return mlir::isa(user); })) + { + builder.create(read->getLoc(), value); + countedValues.insert(countedUnitOf(value)); + return; + } + mlir::Value held = value; mlir::Operation *acquired = nullptr; if (copied) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 3f4a365d3..5be6d8c53 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -1124,6 +1124,8 @@ class OwnershipInferencePass // With `place`, the chain of that place itself: where a store into it moves a value (spec 29). Chain chainOf(mlir::Operation *read, mlir::Value place = {}); + // A plain borrow that says the places its result is read through (TSLANG 236): those added to `chain`. + static bool knownResultPlaces(mlir::Operation *call, Chain &chain); // Where the roots stop holding what the chain reads: a local's releases and assignments and // every declaration or retain that may move it away; a made value's releases and every use diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index b8c5c48be..4f7898210 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -513,6 +513,27 @@ namespace own_inference return llvm::all_of(indices, [&](int index) { return static_cast(index) < args.size(); }) ? def : nullptr; } + // A plain borrow of one argument that says the places it is read through (OWN_RESULT_PLACES_ATTR_NAME): those go on + // the chain, as if read here. False for any other call's result. + bool OwnershipInferencePass::knownResultPlaces(mlir::Operation *call, Chain &chain) + { + auto places = resultPlaces(call); + if (!places || isRecordResult(call) || resultBorrowsAll(call).size() != 1) + { + return false; + } + + for (auto &place : *places) + { + if (!llvm::is_contained(chain.places, place)) + { + chain.places.push_back(place); + } + } + + return true; + } + OwnershipInferencePass::Chain OwnershipInferencePass::chainOf(mlir::Operation *read, mlir::Value place) { Chain chain; @@ -535,8 +556,13 @@ namespace own_inference else { // a call's result that borrows its arguments - a plain borrow, or a borrowing record's box - // (spec 32), which may hold a borrow of each - is somewhere under each of them - chain.anyPlace = true; + // (spec 32), which may hold a borrow of each - is somewhere under each of them; a plain borrow + // that says the places it is read through is under those (TSLANG 236) + if (!knownResultPlaces(read, chain)) + { + chain.anyPlace = true; + } + auto args = callArgs(read); for (auto index : resultBorrowsAll(read)) { @@ -647,7 +673,11 @@ namespace own_inference // a result that borrows an argument is somewhere under the argument if (auto *call = borrowingCall(base)) { - chain.anyPlace = true; + if (!knownResultPlaces(call, chain)) + { + chain.anyPlace = true; + } + auto args = callArgs(call); for (auto index : resultBorrowsAll(call)) { @@ -1011,6 +1041,13 @@ namespace own_inference return false; } + // ...nor a call's result lent by its arguments (`k.self()`, `k.first()`): what it reads is under them, which + // may be the chain's root (TSLANG 240: `k.self().add2(k.arr[0])` freed `k.arr` under the borrow) + if (borrowingCall(argumentRoot) || borrowingCall(argument)) + { + return false; + } + // ...and neither made of the other: the argument is no record or view of a root, nor a root read out of it for (auto source : rootSources(chain)) { @@ -1162,6 +1199,18 @@ namespace own_inference return typeMayHold(module, slotType, borrowedValue.getType()); } + // pop, shift, splice, `length =`: what goes is elements of that array, and what they own - not a + // borrow of a type no element can hold (`grid.length = 0` of an `int[]`, TSLANG 237) + if (borrowedValue && drop->getNumOperands() > 0 && !mlir::isa(drop)) + { + auto refType = mlir::dyn_cast(drop->getOperand(0).getType()); + auto arrayType = refType ? mlir::dyn_cast(refType.getElementType()) : mlir_ts::ArrayType(); + if (arrayType) + { + return typeMayHold(module, arrayType.getElementType(), borrowedValue.getType()); + } + } + return true; } @@ -1278,10 +1327,27 @@ namespace own_inference { auto &fromRead = derivedFrom(borrowed ? borrowed : read->getResult(0)); auto sources = rootSources(chain); + // ...an operand made of a source, or a call's result lent by one (`k.self()`, `k.first()`: `this` or + // a field of `k` lent back, which reaches what `k` holds - TSLANG 240, `k.self().add2(k.arr[0])`) + std::function reaches = [&](mlir::Value operand, int depth) { + if (llvm::any_of(sources, [&](mlir::Value source) { return derivedFrom(source).contains(operand); })) + { + return true; + } + + auto *lender = depth < 8 ? borrowingCall(rootOf(operand)) : nullptr; + if (!lender) + { + return depth >= 8; + } + + auto args = callArgs(lender); + return llvm::any_of(resultBorrowsAll(lender), [&](int32_t index) { + return static_cast(index) >= args.size() || reaches(args[index], depth + 1); + }); + }; mayDrop = llvm::any_of(drop->getOperands(), [&](mlir::Value operand) { - return !fromRead.contains(operand) && llvm::any_of(sources, [&](mlir::Value source) { - return derivedFrom(source).contains(operand); - }); + return !fromRead.contains(operand) && reaches(operand, 0); }); } @@ -1885,6 +1951,7 @@ namespace own_inference auto keepsIt = llvm::any_of(ownedParams(drop), [&](int32_t index) { return static_cast(index) < args.size() && args[index] == result; }); + auto copiedForCall = callCopies.size(); if (dryRun && use.op == drop && (keepsIt || (callee && callee.getDefiningOp())) && copiesInto(drop, result)) { @@ -1914,7 +1981,11 @@ namespace own_inference // (USER RULING 11-27, TSLANG 218/221). Asked only where the dry run fails, so what plain own // accepts is decided as before; still an error when that repair can't be made. // (a `const` the read is folded into, which names the read itself: the read is the candidate) - if (dryRun && use.op != drop && !mlir::isa(read)) + // ...and one given to the very call that may free it (`const B = this.B; B.add(st)` of an `add` that + // runs a stored callback): the same reference, held across the call, when no copy is made for it - + // as `B.add(st); B.add(st)` was already given one by its second use (TSLANG 240) + if (dryRun && (use.op != drop || callCopies.size() == copiedForCall) && + !mlir::isa(read)) { if (assignedLet) { @@ -1924,7 +1995,13 @@ namespace own_inference (read->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME) || // ...and a string no name holds, used after it (`this.name + " " + this.sides`, // the second getter a call that may free what the first one lends): a copy - isCopyableValueAt(read, read->getResult(0).getType()))) + isCopyableValueAt(read, read->getResult(0).getType()) || + // ...and an object no name holds, given straight to the call that may free it + // (`k.add(k.first())`, `k.run(k.arr[0])`): counted across the call, as a named + // one is (TSLANG 240) + // (not `this` lent back, `k.self()`: that is `k` itself, no value of its own) + (use.op == drop && rootOf(read->getResult(0)) == read->getResult(0) && + mlir::isa(read->getResult(0).getType())))) { letsUsedAfterCalls.insert(read); } diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index f7b9a5ee8..3e2a1b220 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -1135,6 +1135,15 @@ namespace own_signature ResultBorrows result{{found}, false}; auto returned = returnedValues(funcOp); result.itself = !returned.empty() && llvm::all_of(returned, [&](mlir::Value value) { return isParameterItself(value, found); }); + // the places each value returned is read through (TSLANG 236): all of them, or not known + llvm::SmallVector> places; + if (!returned.empty() && llvm::all_of(returned, [&](mlir::Value value) { + return holdsNoBlock(value) || borrowedPlaces(value, found, places); + })) + { + result.places = std::move(places); + } + return result; } @@ -1233,6 +1242,7 @@ namespace own_signature erased.insert(releases.begin(), releases.end()); op->removeAttr(OWN_RESULT_BORROWS_ATTR_NAME); op->removeAttr(OWN_RESULT_ITSELF_ATTR_NAME); + op->removeAttr(OWN_RESULT_PLACES_ATTR_NAME); op->setAttr(OWN_FRESH_RESULT_ATTR_NAME, mlir::UnitAttr::get(op->getContext())); } @@ -1653,6 +1663,7 @@ namespace own_signature facts.record = result.record; facts.unboxed = result.unboxed; facts.itself = result.itself; + facts.places = std::move(result.places); facts.owned = localOwnedParams(entry.second); // what the body takes into something on every path; a parameter it returns on // some paths only is kept too, and released on the others (spec 33) @@ -1744,6 +1755,12 @@ namespace own_signature said.itself = said.borrows.size() == 1 && !said.record && (entry.second.isDeclaration() ? entry.second->hasAttr(OWN_DECLARED_RETURNS_THIS_ATTR_NAME) : local.itself && local.borrows == said.borrows); + // ...and the places a body here reads it through (TSLANG 236) + if (said.borrows.size() == 1 && !said.record && !entry.second.isDeclaration() && + local.borrows == said.borrows && !local.record) + { + said.places = local.places; + } if (factsThroughInterface(entry.second, said)) { continue; @@ -1834,13 +1851,24 @@ namespace own_signature agreed = shifted; } - return agreed.value_or(Facts()); + // (through a callback, its places are not kept: TSLANG 236 needs no more) + auto result = agreed.value_or(Facts()); + result.places.reset(); + return result; } auto facts = factsEffective.lookup(callees.funcs.front()); auto agree = llvm::all_of(callees.funcs, [&](mlir_ts::FuncOp callee) { return factsEffective.lookup(callee) == facts; }); + // the places only where every callee reads the result through the same ones (TSLANG 236) + if (agree && facts.places && llvm::any_of(callees.funcs, [&](mlir_ts::FuncOp callee) { + return factsEffective.lookup(callee).places != facts.places; + })) + { + facts.places.reset(); + } + return agree ? facts : Facts(); } @@ -1851,9 +1879,22 @@ namespace own_signature op->removeAttr(OWN_RESULT_RECORD_ATTR_NAME); op->removeAttr(OWN_RESULT_RECORD_UNBOXED_ATTR_NAME); op->removeAttr(OWN_RESULT_ITSELF_ATTR_NAME); + op->removeAttr(OWN_RESULT_PLACES_ATTR_NAME); op->removeAttr(OWN_PARAMS_ATTR_NAME); if (!facts.borrows.empty()) { + if (facts.places && facts.borrows.size() == 1 && !facts.record) + { + llvm::SmallVector entries; + for (auto &place : *facts.places) + { + entries.push_back(mlir::ArrayAttr::get(context, {mlir::IntegerAttr::get(mlir::IntegerType::get(context, 64), place.first), + mlir::TypeAttr::get(place.second)})); + } + + op->setAttr(OWN_RESULT_PLACES_ATTR_NAME, mlir::ArrayAttr::get(context, entries)); + } + op->setAttr(OWN_RESULT_BORROWS_ATTR_NAME, mlir::DenseI32ArrayAttr::get(context, facts.borrows)); if (facts.itself && facts.borrows.size() == 1 && !facts.record) { diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 2f2dc9ab8..6c3a96726 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -465,6 +465,9 @@ class OwnershipSignaturePass : public mlir::PassWrapper>> places; bool empty() const { @@ -1040,6 +1043,8 @@ class OwnershipSignaturePass : public mlir::PassWrapper>> places; }; // Is `value` parameter `index` itself: the argument, or a read of its slot, seen through views? diff --git a/tslang/test/fuzz/__pycache__/mm_fuzz.cpython-315.pyc b/tslang/test/fuzz/__pycache__/mm_fuzz.cpython-315.pyc new file mode 100644 index 000000000..75a12109f Binary files /dev/null and b/tslang/test/fuzz/__pycache__/mm_fuzz.cpython-315.pyc differ diff --git a/tslang/test/fuzz/mm_fuzz.py b/tslang/test/fuzz/mm_fuzz.py index 5021bec68..5353c07f7 100644 --- a/tslang/test/fuzz/mm_fuzz.py +++ b/tslang/test/fuzz/mm_fuzz.py @@ -26,6 +26,12 @@ # and info.json says whether it fails there too. --avoid stops generating a shape whose # bug is already known and would hide the rest (arg-assign, globals, literal-temp). # +# mm_fuzz.py --classes run [--count N] [--seed S] +# The same, with class K too (CLASSES_HEADER): methods that lend their fields back (`first()`, `at(i)`, `this` +# from `self()`), replace or empty them, free them and then read their argument (`swapIn`, `drain`), and run a +# callback stored in a field; closures given straight to a call. The shapes of TSLANG 236-240; it found the +# lent-`this` crash (`k.self().drain(k.head())`). +# # mm_fuzz.py replay FILE.ts|DIR ... # Check existing programs (the seeds/ folder by default), without generating or minimizing. # seeds/ holds the probes reviewers wrote by hand against own-raytrace that still failed @@ -274,6 +280,40 @@ def check_program(tc, text, work, models=("rc", "own"), runs=1): "@noinline function mt(i: number): T { return new T(\"t\" + i); }", ] +# --classes: a class whose methods lend its fields back (`first()`, `at(i)`, `this` from `self()` and `add()`), replace or +# empty them, and run a callback stored in a field - what -mm=own got wrong in TSLANG 236-240: a borrow of a method's +# result across a call that writes some other field, an `int[]` emptied, a closure given straight to a call, a +# `this`-returning call given an element, a value given to the very call that may free it +CLASSES_HEADER = [ + "type KF = (x: N) => number;", + "class K {", + " n: N = mk(1);", + " arr: N[] = [mk(2), mk(3)];", + " nums: number[] = [1, 2];", + " cb: Shared | null = null;", + " tag: number = 0;", + " @lends(\"this\") at(i: number): N { return this.arr[i % this.arr.length]; }", + " first(): N { return this.arr[0]; }", + " head(): N { return this.n; }", + " self(): this { return this; }", + " copyFrom(x: N): this { this.tag += x.v.x; return this; }", + " setN(x: N): void { this.n = x; }", + " resetN(i: number): void { this.n = mk(i); churn(); }", + " replaceArr(i: number): void { this.arr = [mk(i), mk(i + 1)]; churn(); }", + " refill(i: number): void { this.arr.length = 0; this.arr.push(mk(i)); this.arr.push(mk(i + 1)); churn(); }", + " popPush(i: number): void { this.arr.pop(); this.arr.push(mk(i)); churn(); }", + " numsReset(i: number): void { this.nums.length = 0; this.nums.push(i); this.nums.push(i + 1); }", + " setCb(f: KF): void { this.cb = new Shared(f); }", + " run(x: N): number { const f = this.cb; if (f) { return f.value(x); } return x.v.x; }", + " add(x: N): this { this.tag += this.run(x); return this; }", + # free what an argument may have been read from, then read the argument + " swapIn(x: N): this { this.arr = [mk(9), mk(9)]; this.n = mk(8); churn(); this.tag += x.v.x + x.items[0].x; return this; }", + " drain(x: N): number { this.arr.length = 0; this.arr.push(mk(5)); this.arr.push(mk(6)); churn(); return x.v.w.x; }", + "}", + "@noinline function apply(fn: KF, x: N): number { return fn(x); }", + "@noinline function kmut(k: K, i: number): void { k.replaceArr(i); }", +] + AVOIDABLE = { "arg-assign": "an assignment inside an argument list, f(n, (n = mk(1), m))", "globals": "the module-level G, HG, GS and GA", @@ -283,7 +323,7 @@ def check_program(tc, text, work, models=("rc", "own"), runs=1): TYPE_NAME = {"N": "N", "V": "V", "NA": "N[]", "IX": "IX", "IY": "IY", "IG": "IG", "FN": "() => number", "SV": "Shared", "H": "H", - "S": "string", "SA": "string[]", "T": "T", "FS": "(n: number) => string"} + "S": "string", "SA": "string[]", "T": "T", "FS": "(n: number) => string", "K": "K"} # number-valued reads of a value of each type READS = { @@ -300,10 +340,11 @@ def check_program(tc, text, work, models=("rc", "own"), runs=1): "SA": ["{0}.length", "{0}[0].length"], "T": ["{0}.s.length"], "FS": ["{0}(3).length"], + "K": ["{0}.n.v.x", "{0}.arr[0].v.x", "{0}.tag", "{0}.first().v.x", "{0}.nums[0]", "{0}.at(1).items[0].x"], } PREFIX = {"N": "n", "V": "v", "NA": "a", "IX": "ix", "IY": "iy", "IG": "ig", "FN": "c", - "SV": "sh", "H": "h", "S": "st", "SA": "sa", "T": "t", "FS": "fs"} + "SV": "sh", "H": "h", "S": "st", "SA": "sa", "T": "t", "FS": "fs", "K": "k"} class Var: @@ -345,10 +386,11 @@ def declare(self, ty, mutable, minlen=0): class Gen: - def __init__(self, seed, size=None, avoid=(), extended=False): + def __init__(self, seed, size=None, avoid=(), extended=False, classes=False): self.r = random.Random(seed) self.seed = seed self.extended = extended # EXTENDED_HEADER's types too + self.classes = classes # CLASSES_HEADER's K and the statements over it self.avoid = set(avoid) # shapes not to generate, once their bugs are known (AVOIDABLE) self.counter = 0 self.globals = [] @@ -414,9 +456,17 @@ def expr(self, ctx, ty, fresh_bias=0.4, depth=0): if arrs and self.reducers and self.chance(0.4): opts.append(lambda: "%s.reduce(%s, %s)" % (self.pick(arrs).name, self.pick(self.reducers), self.expr(ctx, "N", 0.7, depth + 1))) + ks = ctx.vars(lambda v: v.ty == "K") + if ks: + opts.append(lambda: self.pick(ks).name + self.pick([".first()", ".head()", ".at(%s)" % self.num_k(ctx), + ".arr[0]", ".n", ".self().first()"])) if not opts or self.chance(fresh_bias): return "mk(%s)" % self.num_k(ctx) return self.pick(opts)() + if ty == "K": + if alias and self.chance(0.6): + return self.pick(vs).name + return "new K()" if ty == "V": opts = [] if alias: @@ -600,13 +650,20 @@ def stmt(self, ctx, ind, depth=0): kinds.append(("jump", 2)) if ctx.fn != "main": kinds.append(("return", 1)) + if self.classes and ctx.vars(lambda v: v.ty == "K"): + kinds.append(("kcall", 12)) kind = self.r.choices([k for k, _ in kinds], [w for _, w in kinds])[0] acc = ctx.acc + if kind == "kcall": + return self.kcall(ctx, sp) + if kind == "decl": types, weights = ["N", "V", "NA", "IX", "IY", "IG", "FN", "SV"], [6, 4, 3, 2, 1, 1, 3, 1] if self.extended: types, weights = types + ["S", "SA", "T", "FS"], weights + [8, 4, 3, 3] + if self.classes: + types, weights = types + ["K"], weights + [5] ty = self.r.choices(types, weights)[0] mutable = self.chance(0.6) e = self.expr(ctx, ty) @@ -652,6 +709,10 @@ def stmt(self, ctx, ind, depth=0): opts.append("%s.push(%s);" % (v.name, self.expr(ctx, "S", 0.4))) for v in ctx.vars(lambda v: v.ty == "S" and v.mutable): opts.append("%s += %s;" % (v.name, self.expr(ctx, "S", 0.6))) + for v in ctx.vars(lambda v: v.ty == "K"): + opts.append("%s.n = %s;" % (v.name, self.expr(ctx, "N", 0.5))) + opts.append("%s.arr[0] = %s;" % (v.name, self.expr(ctx, "N", 0.5))) + opts.append("%s.arr.push(%s);" % (v.name, self.expr(ctx, "N", 0.5))) if not opts: return self.stmt(ctx, ind) s = self.pick(opts) @@ -719,11 +780,83 @@ def stmt(self, ctx, ind, depth=0): raise ValueError(kind) + # -- calls of K's methods (--classes) + + def kmut(self, ctx): + """A call that may write K's fields, free what they held, or run a stored callback that does.""" + ks = ctx.vars(lambda v: v.ty == "K") + k = self.pick(ks).name + i = self.num_k(ctx) + return self.pick([ + "%s.resetN(%s);" % (k, i), "%s.replaceArr(%s);" % (k, i), "%s.refill(%s);" % (k, i), + "%s.popPush(%s);" % (k, i), "%s.numsReset(%s);" % (k, i), "kmut(%s, %s);" % (k, i), + "%s.setN(%s);" % (k, self.expr(ctx, "N", 0.5)), "%s.tag += 1;" % k, + "%s.add(%s);" % (k, self.expr(ctx, "N", 0.4)), "churn();", + "%s.swapIn(%s);" % (k, self.expr(ctx, "N", 0.3)), + "%s.tag += %s.drain(%s);" % (k, k, self.expr(ctx, "N", 0.3)), + ]) + + def kcallback(self, ctx): + """A callback for K.setCb: harmless, reading what it captures, or writing a K's fields.""" + c = self.r.random() + if c < 0.3: + return "(x: N): number => x.v.x + %d" % self.k() + if c < 0.6: + return "(x: N): number => x.v.x + %s" % self.num_read(ctx, no_calls=True) + return "(x: N): number => { %s return x.v.x; }" % self.kmut(ctx) + + def kcall(self, ctx, sp): + ks = ctx.vars(lambda v: v.ty == "K") + k = self.pick(ks).name + acc = ctx.acc + c = self.r.random() + if c < 0.25: + # a borrow of a method's result across a call that may write some field (236, 237) + e = self.pick([".first()", ".head()", ".at(%s)" % self.num_k(ctx), ".self().first()", ".arr[0]"]) + v = ctx.declare("N", False) + out = ["%sconst %s = %s%s;" % (sp, v.name, k, e)] + for _ in range(self.r.randint(1, 2)): + out.append(sp + self.kmut(ctx)) + out.append("%s%s += %s;" % (sp, acc, self.pick(READS["N"]).format(v.name))) + return out + if c < 0.37: + x = self.fresh("x") + return ["%sfor (const %s of %s.arr) {" % (sp, x, k), sp + " " + self.kmut(ctx), + "%s %s += %s;" % (sp, acc, self.pick(READS["N"]).format(x)), sp + "}"] + if c < 0.52: + # a closure given straight to a call (238) + return ["%s%s += apply((x: N): number => x.v.x + %s, %s);" % ( + sp, acc, self.num_read(ctx, no_calls=True), self.expr(ctx, "N", 0.4))] + if c < 0.64: + return ["%s%s.setCb(%s);" % (sp, k, self.kcallback(ctx))] + if c < 0.82: + # a `this`-returning chain given an element, a value given to the call that may free it (239, 240) + chain = self.pick([".add(%s)", ".copyFrom(%s)", ".add(%s).self().copyFrom(%s)", ".self().add(%s)", + ".swapIn(%s)", ".self().swapIn(%s)", ".swapIn(%s).swapIn(%s)", ".swapIn(%s).self().swapIn(%s)"]) + args = tuple(self.expr(ctx, "N", 0.4) for _ in range(chain.count("%s"))) + if self.chance(0.3): + return ["%s%s += %s%s.tag;" % (sp, acc, k, chain % args)] + return ["%s%s%s;" % (sp, k, chain % args)] + if c < 0.9: + return ["%s%s += %s%s(%s);" % (sp, acc, k, self.pick([".run", ".drain", ".self().drain"]), + self.expr(ctx, "N", 0.4))] + # a field's array held in a local, emptied or read through (237, 239) + if self.chance(0.5): + ns = self.fresh("ns") + return ["%sconst %s = %s.nums;" % (sp, ns, k), "%s%s.length = 0;" % (sp, ns), + "%s%s.push(%s);" % (sp, ns, self.num_k(ctx))] + ar = self.fresh("ar") + k2 = self.pick(ks).name + return ["%sconst %s = %s.arr;" % (sp, ar, k), "%s%s.copyFrom(%s[0]);" % (sp, k2, ar), + "%s%s += %s[%s.length - 1].v.x;" % (sp, acc, ar, ar)] + # -- functions def helper_params(self): shapes = [["N", "N"], ["N", "V"], ["NA", "N"], ["H", "N"], ["IX", "N"], ["N", "N", "B"], ["N"], ["SV", "N"], ["N", "IY"]] + if self.classes: + shapes += [["K", "N"], ["K", "N"], ["K", "K", "N"], ["K", "N", "B"]] return self.pick(shapes) def gen_helper(self): @@ -793,7 +926,7 @@ def gen_globals(self): return lines def program(self): - lines = list(HEADER) + (EXTENDED_HEADER if self.extended else []) + lines = list(HEADER) + (EXTENDED_HEADER if self.extended else []) + (CLASSES_HEADER if self.classes else []) if "literal-temp" in self.avoid: lines += ["@noinline function mna(i: number): N[] { const a: N[] = [mk(i)]; return a; }"] if self.extended: @@ -805,6 +938,9 @@ def program(self): lines += self.gen_helper() ctx = Ctx(self, "main", "s") main = ["function main() {", " let s: number = 0;"] + if self.classes: + for _ in range(self.r.randint(1, 2)): + main.append(" const %s = new K();" % ctx.declare("K", False).name) main += self.stmts(ctx, self.r.randint(1, 2 + self.size // 2), 1) iters = self.pick([1, 3, 20, 100, 300]) ctx.loop_vars.append("i") @@ -1363,7 +1499,7 @@ def cmd_leak_flag_only(args, tc): stats = Stats() def one(seed): - text = Gen(seed, avoid=args.avoid, extended=not args.objects_only).program() + text = Gen(seed, avoid=args.avoid, extended=not args.objects_only, classes=args.classes).program() name = "s%d" % seed work = os.path.join(work_root, name) if own_accepts(tc, text, work, False): @@ -1433,7 +1569,7 @@ def cmd_leaks(args, tc, recheck): minimized = [0] def one(seed): - text = Gen(seed, avoid=args.avoid, extended=not args.objects_only).program() + text = Gen(seed, avoid=args.avoid, extended=not args.objects_only, classes=args.classes).program() work = os.path.join(work_root, str(seed)) res = leak_check(tc, text, work, args.low, args.high) if res is None: @@ -1569,7 +1705,7 @@ def variant(label, text, work): return gc.status == "ok" and gc.run_code == 0 and res["own"].status == "rejected" def one(seed): - text = Gen(seed, avoid=args.avoid).program() + text = Gen(seed, avoid=args.avoid, classes=args.classes).program() if variant(str(seed), text, os.path.join(work_root, str(seed))) and not args.no_repair: # own rejected it: delete what own complains about until it accepts, and check that work = os.path.join(work_root, "%dr" % seed) @@ -1686,6 +1822,9 @@ def main(): ap.add_argument("--avoid", type=lambda s: [x for x in s.split(",") if x], default=[], help="comma-separated shapes not to generate, so that a known bug that every " "other program hits stops hiding the rest: " + ", ".join(sorted(AVOIDABLE))) + ap.add_argument("--classes", action="store_true", + help="generate class K too: methods that lend fields back, replace or empty them, and run a stored " + "callback (the shapes of TSLANG 236-240)") sub = ap.add_subparsers(dest="cmd", required=True) r = sub.add_parser("run") r.add_argument("--count", type=int, default=200) @@ -1726,7 +1865,7 @@ def main(): args = ap.parse_args() if args.cmd == "show": - sys.stdout.write(Gen(args.seed, avoid=args.avoid, extended=args.extended).program()) + sys.stdout.write(Gen(args.seed, avoid=args.avoid, extended=args.extended, classes=args.classes).program()) return 0 own_fallback = args.own_fallback or getattr(args, "own_fallback_here", False) tc = Toolchain(args.tslang, args.tslang_lib_path, args.gc_lib_path, own_fallback) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 84913d5b7..c4fc2b249 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2807,6 +2807,15 @@ add_test(NAME test-compile-00tslang_issue_234-quiet -o "${CMAKE_CURRENT_BINARY_DIR}/00tslang_issue_234-quiet.obj") set_tests_properties(test-compile-00tslang_issue_234-quiet PROPERTIES FAIL_REGULAR_EXPRESSION "warning:|error:|Stack dump|Assertion failed") +# TSLANG 236-240: -mm=own borrows end only where what they read is overwritten or freed: a result's places (236), an +# `int[]` holds no object (237), a closure given to a call borrows a named const (238), a call's result borrows only +# the arguments it says (239), a value given to a call that may free it is counted (240); every model runs them +foreach(issue236_n 236 237 238 239 240 240_temps) + foreach(issue236_mm gc rc none own) + tslang_add_test(NAME test-jit-00tslang_issue_${issue236_n}-${issue236_mm} COMMAND test-runner -jit -mm=${issue236_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue236_n}.ts") + tslang_add_test(NAME test-compile-00tslang_issue_${issue236_n}-${issue236_mm} COMMAND test-runner -mm=${issue236_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue236_n}.ts") + endforeach() +endforeach() add_test(NAME test-compile-declared-method-overloads-warning COMMAND $ --emit=obj --no-default-lib -mm=none "${PROJECT_SOURCE_DIR}/test/tester/tests/declared_method_overloads_warning.ts" @@ -7867,6 +7876,12 @@ set_tests_properties(test-own-err-names-the-variable set(own_error_cases "own_err_assign_after_move|:12:16: error: '[^']*' borrows '[^']*' but is used here after '[^']*' is released or overwritten" "own_err_borrow_escape|:9:5: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" + "own_err_result_places_reassigned|:7:29: error: a value that borrows the result of 'T.get' is used here after it may be released or overwritten" + "own_err_result_places_popped|:7:29: error: a value that borrows the result of 'T.get' is used here after it may be released or overwritten" + "own_err_result_places_holder_replaced|:6:67: error: 'f' borrows the result of 'T.get' but is used here after it may be released or overwritten" + "own_err_object_array_emptied|:5:76: error: 'f' borrows the result of 'T.get' but is used here after it may be released or overwritten" + "own_err_object_array_emptied_callee|:5:68: error: 'f' borrows the result of 'T.get' but is used here after it may be released or overwritten" + "own_err_result_borrows_argument|:5:88: error: 'pts' borrows 'tube.pts' and cannot be stored, returned or captured" "own_err_borrow_and_move|:8:5: error: '[^']*' is moved here while '[^']*' borrows it" "own_err_borrow_bound_method|:25:11: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" "own_err_borrow_catch_local|:28:13: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" @@ -7902,9 +7917,6 @@ set(own_error_cases "own_err_alias_read_popped|:28:9: error: a value that borrows an element is used here after it may be released or overwritten" "own_err_container_read_stored|:27:5: error: a value that borrows 'h[.]c' cannot be stored, returned or captured" "own_err_field_let_assigned|:12:5: error: 'a' borrows 'h[.]a' and cannot be assigned. -mm=own cannot prove that yet" - "own_err_call_given_borrow|:21:5: error: a value that borrows 'g[.]c' is used here after it may be released or overwritten" - "own_err_call_this_borrow|:19:5: error: a value that borrows 'g[.]c' is used here after it may be released or overwritten" - "own_err_declared_drops|:15:16: error: a value that borrows 'this[.]value' is used here after it may be released or overwritten" "own_err_borrowed_result_stored|a value that borrows the result of 'firstOf' cannot be stored, returned or captured" "own_err_borrowed_result_outlives|:19:11: error: '[^']*' borrows the result of 'firstOf' but is used here after it may be released or overwritten" "own_err_borrowed_result_let_outlives|borrows the result of 'H.first' but is used here after it may be released or overwritten" @@ -7920,7 +7932,6 @@ set(own_error_cases "own_err_param_kept_not_owned|is given to 'keep', which keeps it, but -mm=own cannot move it here" "own_err_mixed_return|:13:28: error: '[^']*' is used here after its value was moved" "own_err_mixed_return_join_use|:14:15: error: '[^']*' is moved here on some paths only" - "own_err_callback_escapes|error: 'v' borrows an element but is used here after it may be released or overwritten" "own_err_callback_disagrees|a function passed in its place disagrees" "own_err_callback_promoted_used|:25:26: error: '[^']*' is used here after its value was moved" "own_err_kept_and_borrowed_arg|:41:14: error: '[^']*' is used here after its value was moved" @@ -7982,7 +7993,6 @@ set(own_error_cases "own_err_interface_borrow_param|:9:44: error: '[^']*' is a parameter, returned here, but -mm=own cannot tell the callers of 'G[.]get' that the result borrows it" "own_err_interface_borrow_element|:9:66: error: a value that borrows 'this[.]items..' cannot be stored, returned or captured" "own_err_interface_borrow_field|:9:59: error: a value that borrows 'this[.]v' cannot be stored, returned or captured" - "own_err_interface_exported_impl|:15:36: error: a value that borrows 'sc[.]ts' is used here after it may be released or overwritten" "own_err_interface_family_disagrees|is a parameter, returned here, but -mm=own cannot tell the callers of 'GA.get' that the result borrows it" "own_err_interface_from_interface|:9:65: error: '[^']*' is a parameter, returned here, but -mm=own cannot tell the callers of 'G[.]get' that the result borrows it" "own_err_interface_result_outlives|borrows the result of 'First.first' but is used here after it may be released or overwritten" @@ -8018,7 +8028,6 @@ set(own_error_cases "own_err_lends_outlives|:20:11: error: '[^']*' borrows the result of 'firstOf' but is used here after it may be released or overwritten" "own_err_generator_method_this|'this' is a parameter, kept here, but -mm=own cannot make the callers of 'S[.]chars' give it up" "own_err_generator_method_reassigned|:17:5: error: a value is used here after the value it borrows is released or overwritten" - "own_err_callback_method_overridden|:12:53: error: a value that borrows 'this[.]items' is used here after it may be released or overwritten" "own_err_shared_moved_in|:10:11: error: '[^']*' is used here after its value was moved" "own_err_shared_union_owned|a Shared in a union with 'string', which -mm=own does not count, is not supported" "own_err_shared_place_arg|:29:5: error: a value that borrows 'p[.]child' is used here after it may be released or overwritten" @@ -8089,7 +8098,6 @@ set(own_error_cases "own_err_generator_keeps_bounded|:14:17: error: a value that borrows its generator's arguments cannot be stored, returned or captured" "own_err_generator_keeps_bounded_outlives|:20:11: error: a value is used here after the value it borrows is released or overwritten" "own_err_generator_this_param_returned|:11:26: error: a value that borrows its generator's arguments cannot be stored, returned or captured" - "own_err_callback_forwarded_drops|:15:17: error: a value that borrows 'a..' is used here after it may be released or overwritten" "own_err_capture_two_closures|:14:37: error: 'thing' is used here after its value was moved" "own_err_capture_in_loop|:15:44: error: 'thing' is moved inside a loop but was made outside it" "own_err_callback_result_captured|:19:45: error: '[^']*' borrows a field and cannot be stored, returned or captured" @@ -8098,13 +8106,8 @@ set(own_error_cases "own_err_optional_record_field_kept|:15:12: error: '[^']*' borrows the result of 'findIn' and cannot be stored, returned or captured" "own_err_generator_take_used_after|:14:9: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_captured_string_drops|:20:5: error: 'name' borrows 'h[.]name' but is used here after it may be released or overwritten" - "own_err_callback_captured_drops|:14:9: error: 'v' borrows 'a..' but is used here after it may be released or overwritten" - "own_err_callback_field_drops|:16:13: error: 'v' borrows 'a..' but is used here after it may be released or overwritten" - "own_err_callback_returned_drops|:21:9: error: 'v' borrows 'a..' but is used here after it may be released or overwritten" - "own_err_callback_extended_drops|:16:13: error: 'v' borrows 'a..' but is used here after it may be released or overwritten" "own_err_callback_interface_param|:34: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_field|:46:11: error: a value read out of the global 'pool' is lent to a call that may release or overwrite it" - "own_err_callback_cast_field_drops|:16:13: error: 'v' borrows 'a..' 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" @@ -8168,7 +8171,6 @@ set(own_error_cases "own_err_weakref_after_call|:5:137: error: a value that borrows the object a WeakRef refers to is used here after it may be released or overwritten" "own_err_weakref_after_release|:4:137: error: a value that borrows the object a WeakRef refers to is used here after it may be released or overwritten" "own_err_weakref_thread|:14:15: error: -mm=own cannot make a WeakRef to a 'Node' in a program that shares what may hold one with another thread" - "own_err_capture_block_closure|:5:51: error: 'n4' is used here after its value was moved" "own_err_literal_let_used_after|:5:11: error: '[^']*' is used here after its value was moved" "own_err_literal_let_twice|:4:12: error: '[^']*' is used here after its value was moved" "own_err_select_used_after|:11:11: error: '[^']*' is used here after its value was moved" @@ -8197,7 +8199,6 @@ set(own_error_cases "own_err_merged_locals_overwritten|:11:16: error: '[^']*' borrows '[^']*' but is used here after '[^']*' is released or overwritten" "own_err_merged_locals_moved|:12:5: error: '[^']*' is moved here while '[^']*' borrows it" "own_err_element_field_moved_replaced|:11:12: error: a value that borrows 'frames..' is used here after it may be released or overwritten" - "own_err_overridable_reached|:34:13: note: 'Prop.tick' calls 'setNodeTransform', which calls 'World.setTransform'" "own_err_borrowed_array_pushed_returned|:14:5: error: 'a' borrows 'h[.]arr' and cannot be stored, returned or captured" "own_err_local_stored_element_reset|:22:12: error: a value that borrows 'h[.]items..' is used here after it may be released or overwritten" "own_err_pushed_object_field_popped|:24:16: error: a value that borrows 'h[.]frames..' is used here after it may be released or overwritten" @@ -8205,7 +8206,6 @@ set(own_error_cases "own_err_split_let_field_overwritten|:14:16: error: 'dir' borrows 'this[.]dir' but is used here after it may be released or overwritten" "own_err_pushed_or_null_popped|:17:23: error: a value that borrows 'this[.]views..' is used here after it may be released or overwritten" "own_err_kept_local_array_popped|:16:22: error: a value that borrows 'this[.]nodes..' is used here after it may be released or overwritten" - "own_err_private_field_written_callback|:33:24: error: a value that borrows 'this[.]sample' is used here after it may be released or overwritten" "own_err_kept_field_rebound|:29:5: error: '[^']*' is used here after its value was moved" "own_err_kept_array_filled_after_pop|:21:9: error: a value that borrows 'this[.]frames..' is used here after it may be released or overwritten" "own_err_local_object_field_popped|:18:11: error: a value that borrows 'frame[.]allocs..' is used here after it may be released or overwritten" @@ -8321,6 +8321,21 @@ set(own_counted_cases "own_counted_global_read_callee_assigns|^0[\r\n]*$" "own_counted_global_read_callee_assigns_transitive|^0[\r\n]*$" "own_counted_global_let_call|^2[\r\n]*$" + "own_counted_private_field_written_callback|^done[.][\r\n]*$" + "own_counted_overridable_reached|^4[\r\n]*$" + "own_counted_callback_cast_field_drops|^1[\r\n]+0[\r\n]*$" + "own_counted_callback_forwarded_drops|^1 0[\r\n]*$" + "own_counted_callback_method_overridden|^[\r\n]*$" + "own_counted_interface_exported_impl|^9[\r\n]+done[.][\r\n]*$" + "own_counted_call_this_borrow|^0[\r\n]*$" + "own_counted_call_given_borrow|^0[\r\n]*$" + "own_counted_capture_block_closure|^1[\r\n]*$" + "own_counted_callback_extended_drops|^1[\r\n]+0[\r\n]*$" + "own_counted_callback_returned_drops|^1[\r\n]+0[\r\n]*$" + "own_counted_callback_field_drops|^1[\r\n]+0[\r\n]*$" + "own_counted_callback_captured_drops|^1[\r\n]+0[\r\n]*$" + "own_counted_callback_escapes|^1 1[\r\n]*$" + "own_counted_declared_drops|^3[\r\n]*$" ) foreach(own_counted_case ${own_counted_cases}) string(FIND "${own_counted_case}" "|" own_counted_sep) diff --git a/tslang/test/tester/own-facts-objects.cmake b/tslang/test/tester/own-facts-objects.cmake index 093242bd7..6506b8e38 100644 --- a/tslang/test/tester/own-facts-objects.cmake +++ b/tslang/test/tester/own-facts-objects.cmake @@ -38,10 +38,11 @@ if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") message(FATAL_ERROR "own_facts_lib: exit ${status}\n${output}") endif() -# without the library's facts: Cam.reset may destroy anything, the borrow of this.cam among it -tslang_run(blind --emit=obj -mm=own own_facts_main.ts -o own_facts_main_blind.obj) -if(status EQUAL 0 OR NOT output MATCHES "borrows '[^']*' (but )?is used here after it may be released or overwritten") - message(FATAL_ERROR "own_facts_main without --own-facts compiled, or failed otherwise: exit ${status}\n${output}") +# without the library's facts: Cam.reset may destroy anything, the borrow of this.cam among it - given to that call, +# it takes a count of its own across it (USER RULING 12-04, TSLANG 240), where the facts below say it needs none +tslang_run(blind --emit=mlir-affine -mm=own own_facts_main.ts) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump" OR NOT output MATCHES "__own_counted") + message(FATAL_ERROR "own_facts_main without --own-facts: expected a counted borrow, exit ${status}\n${output}") endif() tslang_run(main --emit=obj -mm=own --own-facts=own_facts_lib.obj own_facts_main.ts -o own_facts_main.obj) diff --git a/tslang/test/tester/own-shared-no-drops.cmake b/tslang/test/tester/own-shared-no-drops.cmake index 0df063f92..36ebe6c8e 100644 --- a/tslang/test/tester/own-shared-no-drops.cmake +++ b/tslang/test/tester/own-shared-no-drops.cmake @@ -65,11 +65,16 @@ endforeach() compile("${WORK_DIR}/own" "import_own_no_drops against the own library" ok "${TSLANG}" --emit=obj -mm=own --no-default-lib "${SOURCE_DIR}/import_own_no_drops.ts" -o import.obj) -compile("${WORK_DIR}/own" "import_own_err_imported_drops against the own library" "${borrow_ended}" - "${TSLANG}" --emit=obj -mm=own --no-default-lib "${SOURCE_DIR}/import_own_err_imported_drops.ts" -o import.obj) +# (a borrow given to an imported call the library does not list takes a count of its own across it: USER RULING +# 12-04, TSLANG 240 - where the list says the call drops nothing, it takes none) +compile("${WORK_DIR}/own" "import_own_no_drops against the own library, uncounted" uncounted + "${TSLANG}" --emit=mlir-affine -mm=own --no-default-lib "${SOURCE_DIR}/import_own_no_drops.ts") -compile("${WORK_DIR}/rc" "import_own_no_drops against the rc library" "${borrow_ended}" - "${TSLANG}" --emit=obj -mm=own --no-default-lib "${SOURCE_DIR}/import_own_no_drops.ts" -o import.obj) +compile("${WORK_DIR}/own" "import_own_err_imported_drops against the own library" counted + "${TSLANG}" --emit=mlir-affine -mm=own --no-default-lib "${SOURCE_DIR}/import_own_err_imported_drops.ts") + +compile("${WORK_DIR}/rc" "import_own_no_drops against the rc library" counted + "${TSLANG}" --emit=mlir-affine -mm=own --no-default-lib "${SOURCE_DIR}/import_own_no_drops.ts") # `new H()` of an own library's class is a fresh object this module owns; of an rc library's, whose # blocks carry a count their module holds, it is not, and a borrow under it ends at any unknown call: the local diff --git a/tslang/test/tester/own/own_err_call_given_borrow.ts b/tslang/test/tester/own/own_counted_call_given_borrow.ts similarity index 67% rename from tslang/test/tester/own/own_err_call_given_borrow.ts rename to tslang/test/tester/own/own_counted_call_given_borrow.ts index a4c4df4da..587c7a83a 100644 --- a/tslang/test/tester/own/own_err_call_given_borrow.ts +++ b/tslang/test/tester/own/own_counted_call_given_borrow.ts @@ -1,3 +1,5 @@ +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. // -mm=own, phase 4 rejects: `use` is given `h.c`, then assigns the global that owns it and reads // its parameter. A call given a borrow uses it for as long as the callee runs, so a callee that // may destroy it is a use after the destroy. diff --git a/tslang/test/tester/own/own_err_call_this_borrow.ts b/tslang/test/tester/own/own_counted_call_this_borrow.ts similarity index 62% rename from tslang/test/tester/own/own_err_call_this_borrow.ts rename to tslang/test/tester/own/own_counted_call_this_borrow.ts index 67765cec6..5d1cf2e39 100644 --- a/tslang/test/tester/own/own_err_call_this_borrow.ts +++ b/tslang/test/tester/own/own_counted_call_this_borrow.ts @@ -1,3 +1,5 @@ +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. // -mm=own, phase 4 rejects: `g.c.m()` calls `m` on the borrow of `g.c` itself. `m` assigns // `g.c`, which destroys its own `this`, and then reads `this`. class C { diff --git a/tslang/test/tester/own/own_err_callback_captured_drops.ts b/tslang/test/tester/own/own_counted_callback_captured_drops.ts similarity index 70% rename from tslang/test/tester/own/own_err_callback_captured_drops.ts rename to tslang/test/tester/own/own_counted_callback_captured_drops.ts index 10908415e..490c46932 100644 --- a/tslang/test/tester/own/own_err_callback_captured_drops.ts +++ b/tslang/test/tester/own/own_counted_callback_captured_drops.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: `each` gives its callback to a closure that calls it (spec 54), so the function +// TSLANG 240: once refused; the value given to the call that may free it now takes a reference of its own across +// the call (USER RULING 11-27, TSLANG 219), and the output matches -mm=rc. +// -mm=own used to reject: `each` gives its callback to a closure that calls it (spec 54), so the function // passed to `each` is the one the closure calls - and it replaces a global array, releasing what // it held. `walk` calls the closure with an element of an array that may be that global, and reads // the element again after the call. diff --git a/tslang/test/tester/own/own_err_callback_cast_field_drops.ts b/tslang/test/tester/own/own_counted_callback_cast_field_drops.ts similarity index 67% rename from tslang/test/tester/own/own_err_callback_cast_field_drops.ts rename to tslang/test/tester/own/own_counted_callback_cast_field_drops.ts index 3fe92cc7d..c944a8f0b 100644 --- a/tslang/test/tester/own/own_err_callback_cast_field_drops.ts +++ b/tslang/test/tester/own/own_counted_callback_cast_field_drops.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: the function stored into `Walker`'s field replaces a global array, releasing what +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. +// -mm=own used to reject: the function stored into `Walker`'s field replaces a global array, releasing what // it held. The class is cast to `any` and back before `walk` calls it (spec 59), with an element of an // array that may be that global, and reads the element again after the call. class Item { diff --git a/tslang/test/tester/own/own_err_callback_escapes.ts b/tslang/test/tester/own/own_counted_callback_escapes.ts similarity index 70% rename from tslang/test/tester/own/own_err_callback_escapes.ts rename to tslang/test/tester/own/own_counted_callback_escapes.ts index 8f2727f7f..e5229a458 100644 --- a/tslang/test/tester/own/own_err_callback_escapes.ts +++ b/tslang/test/tester/own/own_counted_callback_escapes.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: `pick` is passed to `reduce`, whose calls through its callback get the facts of the functions its +// TSLANG 240: once refused; the value given to the call that may free it now takes a reference of its own across +// the call (USER RULING 11-27, TSLANG 219), and the output matches -mm=rc. +// -mm=own used to reject: `pick` is passed to `reduce`, whose calls through its callback get the facts of the functions its // callers pass there (spec 33), but `pick` is also held in a `let` and called through it, where -mm=own cannot see // which function runs: its callers can't be told it keeps `acc`. `pick` itself takes a reference of its own to `acc` // for the merge with a new value (TSLANG 224, USER RULING 11-28), but `reduce`'s loop, given such a `pick`, still diff --git a/tslang/test/tester/own/own_err_callback_extended_drops.ts b/tslang/test/tester/own/own_counted_callback_extended_drops.ts similarity index 73% rename from tslang/test/tester/own/own_err_callback_extended_drops.ts rename to tslang/test/tester/own/own_counted_callback_extended_drops.ts index 61e17651c..cafe83c49 100644 --- a/tslang/test/tester/own/own_err_callback_extended_drops.ts +++ b/tslang/test/tester/own/own_counted_callback_extended_drops.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: a class extending `Walker` stores into its field (spec 57) a function that +// TSLANG 240: once refused; the value given to the call that may free it now takes a reference of its own across +// the call (USER RULING 11-27, TSLANG 219), and the output matches -mm=rc. +// -mm=own used to reject: a class extending `Walker` stores into its field (spec 57) a function that // replaces a global array, releasing what it held. `walk` calls it with an element of an array that // may be that global, and reads the element again after the call. class Item { diff --git a/tslang/test/tester/own/own_err_callback_field_drops.ts b/tslang/test/tester/own/own_counted_callback_field_drops.ts similarity index 67% rename from tslang/test/tester/own/own_err_callback_field_drops.ts rename to tslang/test/tester/own/own_counted_callback_field_drops.ts index 75d91bf75..18d36e447 100644 --- a/tslang/test/tester/own/own_err_callback_field_drops.ts +++ b/tslang/test/tester/own/own_counted_callback_field_drops.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: the function stored into `Walker`'s field (spec 55) replaces a global array, +// TSLANG 240: once refused; the value given to the call that may free it now takes a reference of its own across +// the call (USER RULING 11-27, TSLANG 219), and the output matches -mm=rc. +// -mm=own used to reject: the function stored into `Walker`'s field (spec 55) replaces a global array, // releasing what it held. `walk` calls it with an element of an array that may be that global, and // reads the element again after the call. class Item { diff --git a/tslang/test/tester/own/own_err_callback_forwarded_drops.ts b/tslang/test/tester/own/own_counted_callback_forwarded_drops.ts similarity index 76% rename from tslang/test/tester/own/own_err_callback_forwarded_drops.ts rename to tslang/test/tester/own/own_counted_callback_forwarded_drops.ts index 50e0bf6a4..416c9fb06 100644 --- a/tslang/test/tester/own/own_err_callback_forwarded_drops.ts +++ b/tslang/test/tester/own/own_counted_callback_forwarded_drops.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: `sortIt` gives its comparison on to `selectionSort` (spec 43), so the function +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. +// -mm=own used to reject: `sortIt` gives its comparison on to `selectionSort` (spec 43), so the function // passed to `sortIt` is the one `selectionSort` calls - and it replaces a global array, releasing // what it held. `selectionSort` calls it with two elements of an array that may be that global, and // reads them again after the call. diff --git a/tslang/test/tester/own/own_err_callback_method_overridden.ts b/tslang/test/tester/own/own_counted_callback_method_overridden.ts similarity index 65% rename from tslang/test/tester/own/own_err_callback_method_overridden.ts rename to tslang/test/tester/own/own_counted_callback_method_overridden.ts index ef12c0f30..a708a3141 100644 --- a/tslang/test/tester/own/own_err_callback_method_overridden.ts +++ b/tslang/test/tester/own/own_counted_callback_method_overridden.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: `forEach` lends an element to its callback, and a call through Bag's vtable may +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. +// -mm=own used to reject: `forEach` lends an element to its callback, and a call through Bag's vtable may // reach Bag2's override, so the callbacks Bag's callers pass are not all the method may call through // `f` - nothing says it frees nothing. (Without the override, the callbacks' facts are its.) class Node { diff --git a/tslang/test/tester/own/own_err_callback_returned_drops.ts b/tslang/test/tester/own/own_counted_callback_returned_drops.ts similarity index 67% rename from tslang/test/tester/own/own_err_callback_returned_drops.ts rename to tslang/test/tester/own/own_counted_callback_returned_drops.ts index edb2e47ae..10e0622a2 100644 --- a/tslang/test/tester/own/own_err_callback_returned_drops.ts +++ b/tslang/test/tester/own/own_counted_callback_returned_drops.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: one of the functions `pick` returns (spec 56) replaces a global array, releasing +// TSLANG 240: once refused; the value given to the call that may free it now takes a reference of its own across +// the call (USER RULING 11-27, TSLANG 219), and the output matches -mm=rc. +// -mm=own used to reject: one of the functions `pick` returns (spec 56) replaces a global array, releasing // what it held. `walk` calls what `pick` returned with an element of an array that may be that // global, and reads the element again after the call. class Item { diff --git a/tslang/test/tester/own/own_err_capture_block_closure.ts b/tslang/test/tester/own/own_counted_capture_block_closure.ts similarity index 65% rename from tslang/test/tester/own/own_err_capture_block_closure.ts rename to tslang/test/tester/own/own_counted_capture_block_closure.ts index d904e1c3b..b29bfb2da 100644 --- a/tslang/test/tester/own/own_err_capture_block_closure.ts +++ b/tslang/test/tester/own/own_counted_capture_block_closure.ts @@ -1,3 +1,5 @@ +// TSLANG 238: once refused as a move; a closure that does not escape borrows what a named `const` owns, and the +// output matches -mm=rc. class V { constructor(public x: number) {} get(): number { return this.x; } } class N { constructor(public v: V) {} } function f2(): number { diff --git a/tslang/test/tester/own/own_err_declared_drops.ts b/tslang/test/tester/own/own_counted_declared_drops.ts similarity index 58% rename from tslang/test/tester/own/own_err_declared_drops.ts rename to tslang/test/tester/own/own_counted_declared_drops.ts index 997001dec..d520af458 100644 --- a/tslang/test/tester/own/own_err_declared_drops.ts +++ b/tslang/test/tester/own/own_counted_declared_drops.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: `strlen` is declared without `@nodrops`, so the method that calls it may destroy anything, +// TSLANG 240: once refused; the value given to the call that may free it now takes a reference of its own across +// the call (USER RULING 11-27, TSLANG 219), and the output matches -mm=rc. +// -mm=own used to reject: `strlen` is declared without `@nodrops`, so the method that calls it may destroy anything, // and `this.value` (public: not one TSLANG 73 keeps) cannot be lent to it (own_declared_no_drops). declare function strlen(s: string): index; diff --git a/tslang/test/tester/own/own_err_interface_exported_impl.ts b/tslang/test/tester/own/own_counted_interface_exported_impl.ts similarity index 70% rename from tslang/test/tester/own/own_err_interface_exported_impl.ts rename to tslang/test/tester/own/own_counted_interface_exported_impl.ts index c536f4655..a3bafc112 100644 --- a/tslang/test/tester/own/own_err_interface_exported_impl.ts +++ b/tslang/test/tester/own/own_counted_interface_exported_impl.ts @@ -1,4 +1,6 @@ -// -mm=own rejects: the plan's closed-interface program (own_interface_facts) with one implementation +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. +// -mm=own used to reject: the plan's closed-interface program (own_interface_facts) with one implementation // exported. Another module may extend `B` or implement `Th` and hand this module the value, so a call // through `Th` may reach a function this module never sees: it gets no facts, may destroy anything, // and the borrow of `sc.ts` it is made through ends at it. diff --git a/tslang/test/tester/own/own_err_overridable_reached.ts b/tslang/test/tester/own/own_counted_overridable_reached.ts similarity index 80% rename from tslang/test/tester/own/own_err_overridable_reached.ts rename to tslang/test/tester/own/own_counted_overridable_reached.ts index 9c5e9dea3..d887e4f84 100644 --- a/tslang/test/tester/own/own_err_overridable_reached.ts +++ b/tslang/test/tester/own/own_counted_overridable_reached.ts @@ -1,3 +1,5 @@ +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. // TSLANG_ISSUES 60: a call of a function defined here that may destroy anything only because a call it // reaches is of a method another module may override: the error at a borrow it ends names that method // and the way to it. diff --git a/tslang/test/tester/own/own_err_private_field_written_callback.ts b/tslang/test/tester/own/own_counted_private_field_written_callback.ts similarity index 83% rename from tslang/test/tester/own/own_err_private_field_written_callback.ts rename to tslang/test/tester/own/own_counted_private_field_written_callback.ts index 86338753e..d4ec24529 100644 --- a/tslang/test/tester/own/own_err_private_field_written_callback.ts +++ b/tslang/test/tester/own/own_counted_private_field_written_callback.ts @@ -1,3 +1,5 @@ +// TSLANG 240: once refused; the value given to the call that may free it, whatever form the argument has, now takes +// a reference of its own across the call (USER RULINGS 11-27 and 12-04), and the output matches -mm=rc. // TSLANG_ISSUES 73: a private field another method writes may be overwritten by a callback the call // runs, so a borrow of it across the call is refused. const retained: ((n: int) => void)[] = []; diff --git a/tslang/test/tester/own/own_declared_no_drops.ts b/tslang/test/tester/own/own_declared_no_drops.ts index c38347d05..011cd5188 100644 --- a/tslang/test/tester/own/own_declared_no_drops.ts +++ b/tslang/test/tester/own/own_declared_no_drops.ts @@ -1,7 +1,7 @@ // -mm=own: a C function declared `@nodrops` destroys nothing a TypeScript caller can reach, so a // borrow of a field survives a call that reaches it, as it survives a call to a function defined // here that destroys nothing. Without the mark the declaration may destroy anything -// (own_err_declared_drops). +// (own_counted_declared_drops). @nodrops declare function strlen(s: string): index; namespace __S { diff --git a/tslang/test/tester/own/own_declared_scalar_no_drops.ts b/tslang/test/tester/own/own_declared_scalar_no_drops.ts index dee312ffd..b3dead7ee 100644 --- a/tslang/test/tester/own/own_declared_scalar_no_drops.ts +++ b/tslang/test/tester/own/own_declared_scalar_no_drops.ts @@ -2,7 +2,7 @@ // ray tracer's `sqrt` and `floor` - is given no block of this module and destroys none (spec 31), so // a borrow of a field survives a call that reaches it: directly, through a function, and through a // method called through an interface closed in this module. A declaration that takes a block still -// may destroy anything (own_err_declared_drops). +// may destroy anything (own_counted_declared_drops). declare function sqrt(v: number): number; declare function floor(v: number): number; diff --git a/tslang/test/tester/own/own_err_object_array_emptied.ts b/tslang/test/tester/own/own_err_object_array_emptied.ts new file mode 100644 index 000000000..0c318b445 --- /dev/null +++ b/tslang/test/tester/own/own_err_object_array_emptied.ts @@ -0,0 +1,6 @@ +// -mm=own, TSLANG 237: emptying an `int[]` ends no borrow; emptying the `F[]` a borrow was read from +// still does. +class F { v = 2.0; } +class T { list: F[] = [new F()]; get(i: int): F { return this.list[i]; } } +function run(t: T): number { const f = t.get(0); t.list.length = 0; return f.v; } +function main() { print(run(new T())); } diff --git a/tslang/test/tester/own/own_err_object_array_emptied_callee.ts b/tslang/test/tester/own/own_err_object_array_emptied_callee.ts new file mode 100644 index 000000000..50b6041db --- /dev/null +++ b/tslang/test/tester/own/own_err_object_array_emptied_callee.ts @@ -0,0 +1,6 @@ +// -mm=own, TSLANG 237: emptying an `int[]` ends no borrow; a call that empties the `F[]` a borrow was +// read from still does. +class F { v = 2.0; } +class T { list: F[] = [new F()]; get(i: int): F { return this.list[i]; } clear() { this.list.length = 0; } } +function run(t: T): number { const f = t.get(0); t.clear(); return f.v; } +function main() { print(run(new T())); } diff --git a/tslang/test/tester/own/own_err_result_borrows_argument.ts b/tslang/test/tester/own/own_err_result_borrows_argument.ts new file mode 100644 index 000000000..9396c5b11 --- /dev/null +++ b/tslang/test/tester/own/own_err_result_borrows_argument.ts @@ -0,0 +1,6 @@ +// -mm=own, TSLANG 239: a call's result borrows the arguments it says; `keep` returns its argument, so +// `k` borrows `pts`, which cannot be stored. +@final class P { constructor(public x: number) {} keep(v: P): P { return v; } } +class Tube { pts: P[] = []; } +function f(tube: Tube): number { const pts = tube.pts; const t = new P(0.0); const k = t.keep(pts[0]); tube.pts = []; return k.x; } +function main() { const tb = new Tube(); tb.pts.push(new P(2.0)); print(f(tb)); } diff --git a/tslang/test/tester/own/own_err_result_places_holder_replaced.ts b/tslang/test/tester/own/own_err_result_places_holder_replaced.ts new file mode 100644 index 000000000..03bb193bf --- /dev/null +++ b/tslang/test/tester/own/own_err_result_places_holder_replaced.ts @@ -0,0 +1,7 @@ +// -mm=own, TSLANG 236: a result read through `this.h.f` ends when a call replaces `this.h`, the place +// it is read through. +class F { v = 2.0; } +class H { f: F = new F(); } +class T { h: H = new H(); get(): F { return this.h.f; } reset() { this.h = new H(); } } +function run(t: T): number { const f = t.get(); t.reset(); return f.v; } +function main() { print(run(new T())); } diff --git a/tslang/test/tester/own/own_err_result_places_popped.ts b/tslang/test/tester/own/own_err_result_places_popped.ts new file mode 100644 index 000000000..b783659e3 --- /dev/null +++ b/tslang/test/tester/own/own_err_result_places_popped.ts @@ -0,0 +1,9 @@ +// -mm=own, TSLANG 236: a result's places are what it reads through (`this.lists[0]`); a call that pops +// `this.lists` still ends the borrow of it. +@final export class T { + lists: int[][] = [[1, 2]]; + @lends("this") get(): int[] { return this.lists[0]; } + work() { this.lists.pop(); } + run(): int { let s = 0; for (const i of this.get()) { this.work(); s += i; } return s; } +} +function main() { print(new T().run()); } diff --git a/tslang/test/tester/own/own_err_result_places_reassigned.ts b/tslang/test/tester/own/own_err_result_places_reassigned.ts new file mode 100644 index 000000000..78786fd2a --- /dev/null +++ b/tslang/test/tester/own/own_err_result_places_reassigned.ts @@ -0,0 +1,9 @@ +// -mm=own, TSLANG 236: a result's places are what it reads through (`this.lists[0]`); a call that overwrites +// `this.lists` still ends the borrow of it. +@final export class T { + bag: int[] = []; lists: int[][] = [[1, 2]]; + @lends("this") get(): int[] { return this.lists[0]; } + work() { this.lists = [[5]]; } + run(): int { let s = 0; for (const i of this.get()) { this.work(); s += i; } return s; } +} +function main() { print(new T().run()); } diff --git a/tslang/test/tester/tests/00tslang_issue_236.ts b/tslang/test/tester/tests/00tslang_issue_236.ts new file mode 100644 index 000000000..38ecdeb60 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_236.ts @@ -0,0 +1,52 @@ +// TSLANG 236: under -mm=own a call that overwrote any field of a type a borrow could have (`this.bag = order` of an +// `int[]`) ended every borrow its caller held of a call's result, even of an unrelated field: "a value that borrows +// the result of 'T.get' is used here after it may be released or overwritten". A result that borrows one argument +// now says the places it is read through (`this.lists[0]`), and only an overwrite of those ends it. Every model runs +// it; the allocations between the steps would show a block freed early. + +@final class Holder { + n = 0; + bag: int[] = []; + lists: int[][] = [[1, 2], [30]]; + tags: string[] = []; + + @lends("this") get(): int[] { + return this.lists[0]; + } + + @lends("this") at(i: int): int[] { + return this.lists[i]; + } + + work() { + const order: int[] = [7]; + this.bag = order; + this.tags.push("t" + this.n); + this.n++; + } + + run(): int { + let s = 0; + for (const i of this.get()) { + this.work(); + const churn: int[] = [i, i, i]; + s += i + churn.length; + } + + for (const i of this.at(1)) { + this.work(); + const churn: int[] = [i, i]; + s += i + churn.length; + } + + return s; + } +} + +function main() { + const h = new Holder(); + const r = h.run(); + print(r, h.n, h.bag.length, h.tags.length); + assert(r == 41 && h.n == 3 && h.bag.length == 1 && h.tags.length == 3); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_237.ts b/tslang/test/tester/tests/00tslang_issue_237.ts new file mode 100644 index 000000000..ce89a2997 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_237.ts @@ -0,0 +1,51 @@ +// TSLANG 237: under -mm=own emptying a local `int[]` (`grid.length = 0`, `splice`, `pop`) ended borrows of unrelated +// objects, though an element of an `int[]` holds no object. And `xs.length = 0` through `const xs = this.xs` was +// refused as storing the borrow, though `this.xs.length = 0` and `xs.pop()` were not. + +class F { + v = 2.0; +} + +class T { + list: F[] = [new F()]; + xs: int[] = [1, 2]; + + get(i: int): F { + return this.list[i]; + } + + reset(): int { + const xs = this.xs; + xs.length = 0; + xs.push(3); + return xs[0]; + } +} + +function run(t: T, n: int): number { + const f = t.get(0); + const grid: int[] = []; + let s = 0.0; + for (let k = 0; k < n; k++) { + s += f.v; + grid.length = 0; + grid.push(k); + grid.splice(0, 0, k); + grid.pop(); + const churn = new F(); + churn.v = 100.0; + } + + return s + grid[0]; +} + +function main() { + const t = new T(); + const r = run(t, 3); + print(r); + assert(r == 8); + const x = t.reset(); + print(x, t.xs.length); + assert(x == 3 && t.xs.length == 1); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_238.ts b/tslang/test/tester/tests/00tslang_issue_238.ts new file mode 100644 index 000000000..341b0ab4a --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_238.ts @@ -0,0 +1,52 @@ +// TSLANG 238: under -mm=own a closure given straight to a function that only calls it was taken to move a class +// instance it captures, held by a `const`: "'B' is used here after its value was moved" (in a loop: "moved inside a +// loop"). A closure that does not escape borrows what a named `const` owns, as it borrows a parameter. + +type UVFn = (u: number, v: number) => number[]; + +@final class Back { + k: number = 2.0; + pt(x: number): number { + return x * this.k; + } +} + +function surf(fn: UVFn, n: int): number[] { + const out: number[] = []; + for (let i = 0; i < n; i++) { + const r = fn(i / n, 0.5); + out.push(r[0]); + } + + return out; +} + +function noLoop(): number { + const B = new Back(); + const a = surf((u: number, v: number): number[] => [B.pt(u), v], 4); + const churn = new Back(); + churn.k = 100.0; + const b = surf((u: number, v: number): number[] => [B.pt(u), v], 4); + return a[1] + b[2] + B.pt(1.0); +} + +function inLoop(): number { + const B = new Back(); + let s = 0.0; + for (let i = 0; i < 3; i++) { + const a = surf((u: number, v: number): number[] => [B.pt(u), v], 2); + const churn = new Back(); + churn.k = 100.0; + s += a[1]; + } + + return s + B.k; +} + +function main() { + const x = noLoop(); + const y = inLoop(); + print(x, y); + assert(x == 3.5 && y == 5); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_239.ts b/tslang/test/tester/tests/00tslang_issue_239.ts new file mode 100644 index 000000000..e2c08b570 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_239.ts @@ -0,0 +1,34 @@ +// TSLANG 239: under -mm=own `const pts = tube.pts; t.copy(pts[0]);`, of a `copy` returning `this`, was refused: +// "'pts' borrows 'tube.pts' and cannot be stored". The result borrows `t` only; what is given as another argument is +// not in it. + +@final class P { + constructor(public x: number) {} + + copy(v: P): this { + this.x = v.x; + return this; + } +} + +class Tube { + pts: P[] = []; +} + +function f(tube: Tube): number { + const pts = tube.pts; + const t = new P(0.0); + t.copy(pts[0]); + const churn = new P(100.0); + return t.copy(pts[1]).x + t.x + churn.x; +} + +function main() { + const tb = new Tube(); + tb.pts.push(new P(2.0)); + tb.pts.push(new P(3.0)); + const r = f(tb); + print(r, tb.pts.length, tb.pts[0].x); + assert(r == 106 && tb.pts.length == 2 && tb.pts[0].x == 2); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_240.ts b/tslang/test/tester/tests/00tslang_issue_240.ts new file mode 100644 index 000000000..ecf661c5b --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_240.ts @@ -0,0 +1,101 @@ +// TSLANG 240: under -mm=own a value given to a call that may free it (`add` runs a stored callback) was refused or +// accepted by how the argument was written: `B.add(PAINT.a); B.add(PAINT.a)` compiled, `B.add(new Style())` and +// `B.add(st)` did not. Each now takes a reference of its own across the call (USER RULING 11-27, TSLANG 219). The +// accepted form freed `B` one release early: the call's result, `this` lent back with no count, was released too. + +export type VFn = (x: number) => number[]; + +@final export class Style { + fn0: Shared | null = null; + v = 1.0; +} + +export function recipe(v: number): Style { + const s = new Style(); + s.v = v; + return s; +} + +@final export class Paints { + get a(): Style { + return recipe(2.0); + } +} + +export const PAINT: Paints = new Paints(); + +@final export class Bucket { + out: number[] = []; + tag = 7; + + add(s: Style): this { + const f = s.fn0; + if (f) { + const r = f.value(1.0); + this.out.push(r.length); + } + + this.out.push(s.v); + return this; + } +} + +@final export class Loco { + B = new Bucket(); + + m1(): void { + const B = this.B; + B.add(PAINT.a); + B.add(PAINT.a); + } + + m1b(): void { + const B = this.B; + B.add(PAINT.a); + } + + m3(): void { + const B = this.B; + B.add(new Style()); + } + + m5(): void { + const B = this.B; + const st = PAINT.a; + B.add(st); + } + + m7(): void { + const B = this.B; + const st = new Style(); + B.add(st); + B.add(st); + } +} + +function main() { + const l = new Loco(); + const keep: Bucket[] = []; + for (let i = 0; i < 3; i++) { + l.m1(); + l.m1b(); + l.m3(); + l.m5(); + l.m7(); + for (let k = 0; k < 10; k++) { + const b = new Bucket(); + b.tag = 99; + b.out.push(-1.0); + keep.push(b); + } + } + + let s = 0.0; + for (const v of l.B.out) { + s += v; + } + + print(l.B.tag, l.B.out.length, s, keep.length); + assert(l.B.tag == 7 && l.B.out.length == 21 && s == 33 && keep.length == 30); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_240_temps.ts b/tslang/test/tester/tests/00tslang_issue_240_temps.ts new file mode 100644 index 000000000..34f32a5a2 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_240_temps.ts @@ -0,0 +1,106 @@ +// TSLANG 240, found by the memory-model fuzzer (mm_fuzz.py --classes): a value no name holds, lent by a call or read +// out of a field, given straight to a method that frees where it came from. Under -mm=own `k.add2(k.first())` was +// refused while `const f = k.first(); k.add2(f)` was counted; now each takes a count of its own across the call. +// And the receiver lent back by a call (`k.self()`, `k.add2(...)` returning `this`) is `k`: what the call frees through +// it is `k`'s - own took it for an object of its own and freed `k.arr` under the borrow (a crash). Every model runs it; +// the callees allocate after the free, so a block freed early shows as a wrong value. + +class W { + x: number; + constructor(x: number) { + this.x = x; + } +} + +class V { + x: number; + w: W; + constructor(x: number) { + this.x = x; + this.w = new W(x); + } +} + +class N { + v: V; + items: V[]; + constructor(v: V) { + this.items = [new V(v.x)]; + this.v = v; + } +} + +function mk(i: number): N { + return new N(new V(i)); +} + +function churn() { + const hold: N[] = []; + for (let i = 0; i < 64; i++) { + hold.push(new N(new V(777))); + } +} + +class K { + n: N = mk(1); + arr: N[] = [mk(2), mk(3)]; + tag: number = 0; + + first(): N { + return this.arr[0]; + } + + head(): N { + return this.n; + } + + self(): this { + return this; + } + + add2(x: N): this { + this.arr = [mk(9), mk(9)]; + this.n = mk(8); + churn(); + this.tag += x.v.x + x.items[0].x; + return this; + } + + run2(x: N): number { + this.arr.length = 0; + this.arr.push(mk(5)); + churn(); + return x.v.w.x; + } +} + +function main() { + let s: number = 0; + const k = new K(); + const k2 = new K(); + for (let i = 0; i < 3; i++) { + k.add2(k.first()); + k.add2(k.head()); + s += k.run2(k.first()); + s += k.run2(k.arr[0]); + k.self().add2(k.arr[0]); + k.self().add2(k.first()); + k.add2(k.head()).add2(k.first()); + k.add2(k.head()).self().add2(k.first()); + s += k.self().run2(k.first()); + const q = k.self(); + q.add2(k.first()); + k2.self().add2(k.first()); + if (i > 0) { + k.add2(k.first()); + } else { + s += k.run2(k.head()); + } + k.arr.push(mk(i)); + } + + churn(); + print(s, k.tag, k2.tag, k.arr.length); + assert(s == 77 && k.tag == 434 && k2.tag == 54 && k.arr.length == 3); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_60.ts b/tslang/test/tester/tests/00tslang_issue_60.ts index e3e44eae5..3bc554b2c 100644 --- a/tslang/test/tester/tests/00tslang_issue_60.ts +++ b/tslang/test/tester/tests/00tslang_issue_60.ts @@ -1,8 +1,8 @@ // TSLANG_ISSUES 60 (-mm=own), from native_ts_graphics' core/rtxpt_game.ts: `this.props[i].tick(t)`, where // `Prop.tick` calls `setNodeTransform`, which calls a method of the exported `GameWorld`. Another module // may override that method, so the call may destroy anything, and the error said so only for a direct call -// of it (own_err_overridable_reached). `@final` on the class says no module does: the borrows of `this.props[i]`, -// `this.world` and `this.name` then hold over the call. +// of it (own_counted_overridable_reached, where the borrow is now counted across the call: TSLANG 240). `@final` on the +// class says no module does: the borrows of `this.props[i]`, `this.world` and `this.name` then hold over the call. @final export class World {