From 4d9046138842db6cf4932c73733ea0213f8ebe43 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 26 Oct 2026 15:07:36 +0000 Subject: [PATCH 1/2] -mm=own: generator methods over `this` borrow it, also through a vtable A generator method whose state borrows `this` (@borrows("this")) no longer keeps it: the signature pass finds the borrowing states before the facts, and the box's store of `this` keeps nothing. Its callers keep their object and may use it after the loop. A method of a class that is not @final is called through its vtable: the forwarder check (`entries() { return this.iter(); }`) and the bound check see the object through ts.GetThis. A state field read only into a tuple yielded (`yield [k, v]`, also cast to a named tuple) moves into the yield as a field read straight into it does, and a tuple made of borrowed strings starts from copies of them (spec 22) instead of rc's retain. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/OwnershipFacts.h | 3 + .../TypeScript/OwnershipInferenceClosures.cpp | 6 ++ .../lib/TypeScript/OwnershipInferencePass.cpp | 51 +++++++++++++- .../lib/TypeScript/OwnershipInferencePass.h | 3 + .../OwnershipSignatureGenerators.cpp | 66 +++++++++++++++++-- .../lib/TypeScript/OwnershipSignaturePass.cpp | 14 +++- .../lib/TypeScript/OwnershipSignaturePass.h | 6 ++ 7 files changed, 138 insertions(+), 11 deletions(-) diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 647a2fa0c..e8c530883 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -84,6 +84,9 @@ constexpr int64_t OWN_INTERFACE_FIELD_POSITION = -3; // result is the caller's to own, but no use of it may come after any of these arguments is given // back, and it may not be kept anywhere that outlives them. #define OWN_RESULT_BOUNDED_ATTR_NAME "__own_result_bounded" +// A generator method's store of `this` into its box (`.this`), when the state borrows it: the store +// keeps nothing, so the method does not keep `this` (OwnershipSignaturePass::keeps). +#define OWN_STATE_BORROW_ATTR_NAME "__own_state_borrow" // The globals a call may give a new value, by name: a store to one, or its release, in a callee or // in a call it makes. A call that may drop and whose callees are not known may assign any of them // (OWN_ASSIGNS_ANY_GLOBAL_ATTR_NAME). A read of a global ends at such a call (checkGlobalRead). diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index ceafb0c07..ab0faa147 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -292,6 +292,12 @@ namespace own_inference // a closure's box (`.map(f)` calls its maker with it): it lives while the closures on // it do, and what it holds while their owners do. A reference to storage, so first. auto root = rootOf(args[index]); + // the object a method is called on (`w.iter()` of a class that is not `@final`) + if (auto object = boundThis(root)) + { + root = rootOf(object); + } + if (auto boxOp = root.getDefiningOp(); boxOp && boxOp->hasAttr(CAPTURE_BOX_ATTR_NAME)) { if (!checkBoundedByBox(call, root, uses, name)) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 7e6e2828e..386bc8937 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -490,7 +490,7 @@ namespace own_inference OWN_NO_DROPS_ATTR_NAME, OWN_DROP_FIELDS_ATTR_NAME, OWN_FACTS_LOST_ATTR_NAME, OWN_FRESH_RESULT_ATTR_NAME, OWN_ASSIGNS_CAPTURES_ATTR_NAME, - OWN_RESULT_BOUNDED_ATTR_NAME, + OWN_RESULT_BOUNDED_ATTR_NAME, OWN_STATE_BORROW_ATTR_NAME, OWN_CAPTURE_BORROW_ATTR_NAME}) { op->removeAttr(name); @@ -569,6 +569,11 @@ namespace own_inference auto retainOp = mlir::cast(retain); auto value = retainOp.getReference(); + if (copyIntoTuple(retainOp)) + { + return true; + } + if (!isCopyableString(value.getType()) || borrowsKnownParam(value)) { return false; @@ -628,6 +633,50 @@ namespace own_inference return true; } + bool OwnershipInferencePass::copyIntoTuple(mlir_ts::RetainOp retainOp) + { + // `[s, n]` of a borrowed string: rc retains the tuple, which retains the string in it. The + // tuple starts from a copy instead, which is its own (spec 22). Only when strings are all it + // holds blocks of: a borrowed object in it cannot be copied. + auto createTupleOp = retainOp.getReference().getDefiningOp(); + if (!createTupleOp || createTupleOp->getBlock() != retainOp->getBlock() || + !createTupleOp->isBeforeInBlock(retainOp)) + { + return false; + } + + llvm::SmallVector borrowed; + for (auto &operand : createTupleOp->getOpOperands()) + { + auto field = operand.get(); + if (holdsNoBlock(field) || isConstantData(field) || isFresh(rootOf(field))) + { + continue; + } + + if (!isCopyableString(field.getType()) || borrowsKnownParam(field)) + { + return false; + } + + borrowed.push_back(&operand); + } + + if (borrowed.empty()) + { + return false; + } + + mlir::OpBuilder builder(createTupleOp); + for (auto *operand : borrowed) + { + operand->set(builder.create(retainOp->getLoc(), operand->get().getType(), operand->get())); + } + + retainOp->erase(); + return true; + } + } // namespace own_inference #undef DEBUG_TYPE diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 33b855db5..c4bbe427d 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -172,6 +172,9 @@ class OwnershipInferencePass // without the twinReadAfter fallback: a retain whose value has no use of its own is not copied, // so its error stays. bool copyForRetain(mlir::Operation *retain); + // A retain of a tuple `ts.CreateTuple` made from borrowed strings (`[s, n]`): the strings are + // copied into it instead, and the retain goes. + bool copyIntoTuple(mlir_ts::RetainOp retainOp); // The parameter this function's result borrows (`__own_result_borrows`), or -1; and the // parameters (or views of them) whose rc reference for the caller was already decided. diff --git a/tslang/lib/TypeScript/OwnershipSignatureGenerators.cpp b/tslang/lib/TypeScript/OwnershipSignatureGenerators.cpp index 231728223..ed88907a8 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureGenerators.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureGenerators.cpp @@ -207,6 +207,58 @@ namespace own_signature return recordOp && recordOp.getInitializer() && recordOp.getInitializer().getDefiningOp(); } + bool OwnershipSignaturePass::onlyIntoYield(mlir::Value value) + { + for (auto depth = 0; depth < 8; depth++) + { + auto users = llvm::make_filter_range(value.getUsers(), [](mlir::Operation *user) { + return !mlir::isa(user); + }); + if (llvm::hasSingleElement(users)) + { + auto *user = *users.begin(); + if (isRecordFieldStore(user, value)) + { + return true; + } + + // a field of a tuple that is + if (auto createTupleOp = mlir::dyn_cast(user)) + { + value = createTupleOp.getResult(); + continue; + } + + return false; + } + + // a tuple cast to another of its shape (`<[key: K, value: V]>[k, v]`): its fields read + // out, each into the one tuple made again of them + mlir_ts::CreateTupleOp remade; + for (auto *user : users) + { + auto extractOp = mlir::dyn_cast(user); + auto *fieldUser = extractOp && extractOp->hasOneUse() ? *extractOp->getUsers().begin() : nullptr; + auto createTupleOp = mlir::dyn_cast_or_null(fieldUser); + if (!createTupleOp || (remade && remade != createTupleOp)) + { + return false; + } + + remade = createTupleOp; + } + + if (!remade) + { + return false; + } + + value = remade.getResult(); + } + + return false; + } + void OwnershipSignaturePass::findYieldedFields(mlir::ModuleOp module) { // (state type, field) -> its reads and its stores @@ -267,13 +319,8 @@ namespace own_signature continue; } - // read only to be put into a yield's record - auto onlyYielded = llvm::all_of(uses.reads, [](mlir_ts::LoadOp loadOp) { - auto users = llvm::make_filter_range(loadOp->getUsers(), [](mlir::Operation *user) { - return !mlir::isa(user); - }); - return llvm::hasSingleElement(users) && isRecordFieldStore(*users.begin(), loadOp.getResult()); - }); + // read only to be put into a yield's record, or into a tuple that is (`yield [k, v]`) + auto onlyYielded = llvm::all_of(uses.reads, [](mlir_ts::LoadOp loadOp) { return onlyIntoYield(loadOp.getResult()); }); // each value stored is yielded later in its block: nothing between stops the generator auto eachYielded = llvm::all_of(uses.stores, [&](mlir_ts::StoreOp storeOp) { @@ -619,6 +666,7 @@ namespace own_signature state.bounded.push_back(index); } + state.thisStores.push_back(storeOp); continue; } @@ -647,6 +695,10 @@ namespace own_signature auto bounded = state.bounded; llvm::sort(bounded); borrowsFound[state.maker] = bounded; + for (auto *store : state.thisStores) + { + store->setAttr(OWN_STATE_BORROW_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } } if (states.empty()) { diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 9dbe1f307..459e08419 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -74,11 +74,12 @@ namespace own_signature // before the facts: a value kept for good is immortal, which keeps nothing of its owner findKeepers(module); decideKeptForGood(module); + // before the facts: a generator method whose state borrows `this` does not keep it + findBorrowingStates(module); computeFacts(); computeDrops(); pinAssignedGlobals(); rejectGlobalArgumentsDropped(); - findBorrowingStates(module); findBoundedForwarders(); findYieldedFields(module); findImportedStates(module); @@ -388,6 +389,12 @@ namespace own_signature int32_t OwnershipSignaturePass::parameterOf(mlir::Value value, mlir_ts::FuncOp funcOp) { auto root = rootOf(value); + // the object a method is called on (`this.iter()` of a class that is not `@final`) + if (auto object = boundThis(root)) + { + return parameterOf(object, funcOp); + } + if (auto loadOp = root.getDefiningOp()) { if (auto propertyRefOp = loadOp.getReference().getDefiningOp()) @@ -751,8 +758,9 @@ namespace own_signature if (auto storeOp = mlir::dyn_cast(user)) { - // a field a borrowing record borrows (spec 32): the record keeps nothing - if (isBorrowedRecordFieldStore(user)) + // a field a borrowing record borrows (spec 32), or `this` in the box of a generator whose + // state borrows it: the record keeps nothing + if (isBorrowedRecordFieldStore(user) || user->hasAttr(OWN_STATE_BORROW_ATTR_NAME)) { return false; } diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 395ebec68..9055f176c 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -549,6 +549,10 @@ class OwnershipSignaturePass : public mlir::PassWrapper bounded; llvm::SetVector fields; + // the stores of `this` into the box, which keep nothing once the state borrows + llvm::SmallVector thisStores; }; static int32_t fieldIndex(mlir_ts::TupleType tupleType, llvm::StringRef name); From bb10ca09e6193a179569212ffe8f1c59ccc36105 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 26 Oct 2026 15:57:59 +0000 Subject: [PATCH 2/2] -mm=own: Map and Set of strings and numbers - copies into calls, kept-on-some-paths, method callbacks What the default library's Map and Set need to compile under own (spec 2026-10-26-own-generic-containers-design.md): - A string read out of a place and given to a callback that may free it, or to a call that keeps it, gets a copy (released after the call when the callee does not keep it). A direct call that may free it is still an error, so @nodrops keeps its meaning. - A parameter kept on some paths only is released on the others: takenParams is now the parameters a move reaches every return from. - findBetween does not search past the read's own block: around a loop (`continue`) it is read again. - A call's drops for `length =`, pop, shift, splice are the elements of arrays of that element type. - Callback families for methods no other method overrides, called through their vtable; a closed family with no members calls nothing. Tests: 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, own_err_generator_method_reassigned, own_err_callback_method_overridden. Retired: own_err_param_kept_some_paths and own_err_string_call_keeps_twice, which now compile (and are covered by the positive tests). Co-Authored-By: Claude Opus 5.5 --- docs/own-memory-model.md | 7 +- ...026-10-26-own-generic-containers-design.md | 103 ++++++++++++++ tslang/lib/TypeScript/OwnershipFacts.h | 8 +- .../lib/TypeScript/OwnershipInferencePass.cpp | 32 +++++ .../lib/TypeScript/OwnershipInferencePass.h | 5 + .../OwnershipInferencePlaceReads.cpp | 28 ++++ .../OwnershipSignatureCallbacks.cpp | 132 ++++++++++++++++-- .../lib/TypeScript/OwnershipSignaturePass.cpp | 76 +++++++++- .../lib/TypeScript/OwnershipSignaturePass.h | 5 + tslang/test/tester/CMakeLists.txt | 8 +- .../own/own_err_callback_method_overridden.ts | 26 ++++ .../own_err_generator_method_reassigned.ts | 18 +++ .../own/own_err_param_kept_some_paths.ts | 21 --- .../own/own_err_string_call_keeps_twice.ts | 21 --- .../tester/own/own_generator_method_this.ts | 110 +++++++++++++++ .../tester/own/own_length_drops_elements.ts | 30 ++++ tslang/test/tester/own/own_loop_read_again.ts | 32 +++++ .../test/tester/own/own_method_callbacks.ts | 46 ++++++ .../tester/own/own_param_kept_some_paths.ts | 44 ++++++ .../test/tester/own/own_string_copy_call.ts | 70 ++++++++++ .../test/tester/own/own_tuple_param_kept.ts | 33 +++++ 21 files changed, 794 insertions(+), 61 deletions(-) create mode 100644 tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md create mode 100644 tslang/test/tester/own/own_err_callback_method_overridden.ts create mode 100644 tslang/test/tester/own/own_err_generator_method_reassigned.ts delete mode 100644 tslang/test/tester/own/own_err_param_kept_some_paths.ts delete mode 100644 tslang/test/tester/own/own_err_string_call_keeps_twice.ts create mode 100644 tslang/test/tester/own/own_generator_method_this.ts create mode 100644 tslang/test/tester/own/own_length_drops_elements.ts create mode 100644 tslang/test/tester/own/own_loop_read_again.ts create mode 100644 tslang/test/tester/own/own_method_callbacks.ts create mode 100644 tslang/test/tester/own/own_param_kept_some_paths.ts create mode 100644 tslang/test/tester/own/own_string_copy_call.ts create mode 100644 tslang/test/tester/own/own_tuple_param_kept.ts diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index 6caae447e..be1834f89 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -696,8 +696,11 @@ a reference gives it back on every path out of a function. `-mm=own` is still in development, and some valid TypeScript does not compile under it yet. -- The default library has an `-mm=own` build, and arrays, strings and their methods work, but - `Map` and `Set` do not compile under `-mm=own` yet. +- The default library has an `-mm=own` build, and arrays, strings and their methods work. `Map` + and `Set` work with number, boolean and string keys and values (`new Map()`, + `new Set(["a", "b"])`): their iterators borrow the container, and strings go in as + copies. With `any` or object keys or values they do not compile yet, and neither does a `Map` + or `Set` made without type arguments (`new Set([1, 2])` also makes a `Set`). - Array methods that keep elements of the source in a new array (`filter` over class instances) give each such element a second owner, which is an error by design. Use `Shared` elements, or build the result from copies. 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 new file mode 100644 index 000000000..5e5cd3cde --- /dev/null +++ b/tslang/docs/superpowers/specs/2026-10-26-own-generic-containers-design.md @@ -0,0 +1,103 @@ +# -mm=own: generator methods over `this`, and the default library's `Map` and `Set` + +Status: implemented 2026-10-26 (branch `own-generator-this-borrows`; DefaultLib branch +`own-generic-iterators`). + +## 1. Why + +`lib.generics.ts` - `Map`, `Set`, the array generators - is compiled into each program, with its +bodies, so it was never part of the own build of the default library (`lib.ts`). Under `-mm=own` +every `map_*` and `set_*` test of the DefaultLib suite failed to compile. The errors came in a few +kinds: + +- `private *iter()` keeps `this` in its state, and `entries()`, `keys()`, `values()`, `forEach`, + `[Symbol.iterator]` and every set operation call it on `this`, which they do not own. +- `@borrows("this")` (spec of the param markers) helped only for an exported or `@final` class: a + method of any other class is called through its vtable (`ts.GetThis(ts.ThisVirtualSymbolRef(o))`), + which the forwarder check and the bound check did not see through. And a generator method with + the marker still kept `this`: a call moved the object into the generator, so a caller could not + use it after the loop (`for (const c of w.iter()) ...; w.x` was "used after its value was moved"). +- The insert paths store a key and a value that are the caller's: a string read out of an element + (`for (const [k, v] of values) this.tryInsert(k, v)`), a borrowed string put into a yielded tuple + (`yield [key, value]`), a string lent to a callback (`forEach`'s `f(entry.value, entry.key)`). +- `resizeHelper` moved entries out of one array into another, which nothing under own can do. + +## 2. Rules + +1. **A generator method's state borrows `this`.** When the signature pass finds a borrowing state + (phase 7b), the box's store of `this` (`.this`) keeps nothing (`OWN_STATE_BORROW_ATTR_NAME`), so + the method does not keep `this` and its callers keep their object. The states are found before + the facts now; they need none of them. +2. **Through the vtable.** `parameterOf` (the forwarder check) and `checkBoundedResults` see the + object a method is called on through `ts.GetThis` (`boundThis`). A reassignment of the object + while its generator is read is the error a function generator's argument gets + (`own_err_generator_method_reassigned`). +3. **A yielded tuple.** A state field read only into a tuple that is yielded - also cast to a named + tuple, which reads the fields out into a new one - moves into the yield, as a field read straight + into it does (`onlyIntoYield`). +4. **Strings as values, three more places (spec 22).** A `ts.CreateTuple` of borrowed strings that + rc retains starts from copies (`copyIntoTuple`). A string read out of a place and given to a call + 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_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 + any kept one. It was `own_err_param_kept_some_paths`. The move must be in the function's top + region (`placeOnUnmovedEdges`): a move inside a loop is still the error. +6. **A read is read again around a loop.** `findBetween` does not search past the read's own block: + a path back into it (a `continue`) reads again, and the call is given that read + (`for (const v of it) { if (other.has(v)) continue; result.add(v); }`). +7. **Length writes drop elements of their type.** A call's drops for `length =`, `pop`, `shift`, + `splice` on an array it reaches are the elements of arrays of that element type (`-1`, the + element's ref type), as `dropsChain` judges them in a body, not anything. +8. **Callbacks of methods.** A method no other method overrides gets a callback family (spec 33) + from its calls through the vtable and through its bound method: its users may be its class's + vtable and `ts.ThisVirtualSymbolRef`/`ts.ThisSymbolRef` whose methods are only called with the + object first. A family holds every method of a slot's name, of any class; another member + overrides this one when its class extends this one's (a base is the first field of a class's + storage). A closed family with no members - a method no one calls but through the vtable - calls + nothing through the parameter. + +## 3. The library (DefaultLib `own-generic-iterators`) + +- `@borrows("this")` on `iter`, `iterKey`, `iterValue` and their forwarders; the iterators read + `this._entries[i]` at each step instead of keeping the array in their state, so an insert during + iteration that gives the map a new array is not a dangling borrow. (A state that keeps a field of + `this` is "borrows a field and cannot be stored": phase 7b's borrowing fields are read straight + out of the box.) +- `forEach` is a loop over the entries, not over `iter()`. +- `resizeHelper` grows `_entries` in place (`length =`) instead of moving each entry into a new + array. +- An entry is stored as a tuple cast to the entry type, not an object literal (a literal that holds + what it owns moves only into a local, spec 36), in one place after the search loop (rule 5). + `Set`'s overwrite branch was dead (a set never overwrites an equal value) and is gone. +- `hashCodeGeneral` hashes the parameter's own bytes (`Ref(key)`) instead of a local copy, which + took the key under own. +- Bug fix, every model: `size` was `count`, which still counts deleted entries on the free list. + +## 4. Not here + +- `any` or object keys and values. The constructor from an array (`new Map([[k, v]])`) cannot take + the elements out of the caller's array, and moving an object parameter into a tuple + (`Retain` of a tuple made of kept parameters) is "takes a second reference". This waits on the + ruling on containers of owned values (two sets sharing an element by `union` is two owners). + Tried and dropped: a parameter kept through a tuple field (`entries[i] = [key, value]`) + counted as kept. It made `set` and `add` keeping calls, and a string given to two of them + (`m1.set(k, 1); m2.set(k, 2)`) has no retain to copy (spec 22.4): an error that the copy into the + tuple (rule 4) avoids, while no object case compiled with it either. +- `new Set([1, 2])` instantiates `Set` beside `Set` (MLIRGen tries the default type + argument first, in every model), so an untyped container fails under own for the `any` case. +- A callback that assigns a captured variable (`(s) => { r += s.n; }`) has no family, for a function + as much as a method: what it lends is still an error. +- A module-level `Date` with a method that changes it (`event.setDate(24)`) is "a value read out of + the global is lent to a call that may release or overwrite it", though `setDate` writes a number. + +## 5. Tests + +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`. +Retired: `own_err_param_kept_some_paths` (rule 5), `own_err_string_call_keeps_twice` (rule 4). diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index e8c530883..e62fc2331 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -750,13 +750,15 @@ inline mlir::Operation *findBetween(mlir::Operation *read, mlir::Operation *call scan(op); } - // the blocks on a path: reached from the read's, and reaching the call's + // the blocks on a path: reached from the read's, and reaching the call's. Not through the read's + // block again: a path back into it reads again (a loop's `continue`), and the call is given that + // read llvm::SmallPtrSet after; llvm::SmallVector work(fromBlock->getSuccessors().begin(), fromBlock->getSuccessors().end()); while (!work.empty()) { auto *block = work.pop_back_val(); - if (after.insert(block).second) + if (block != fromBlock && after.insert(block).second) { work.append(block->getSuccessors().begin(), block->getSuccessors().end()); } @@ -767,7 +769,7 @@ inline mlir::Operation *findBetween(mlir::Operation *read, mlir::Operation *call while (!work.empty()) { auto *block = work.pop_back_val(); - if (before.insert(block).second) + if (block != fromBlock && before.insert(block).second) { work.append(block->getPredecessors().begin(), block->getPredecessors().end()); } diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 386bc8937..3472d8dbe 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -143,6 +143,7 @@ namespace own_inference mergeBorrowRetains.clear(); captureStores.clear(); captureRetains.clear(); + callCopies.clear(); returnedParams.clear(); returnsBorrowOf = resultBorrows(f); returnsRecordOf = isRecordResult(f) ? resultBorrowsAll(f) : llvm::SmallVector(); @@ -540,6 +541,37 @@ namespace own_inference { copyForRetain(retain); } + + for (auto [read, call] : callCopies) + { + auto value = read->getResult(0); + if (!llvm::is_contained(call->getOperands(), value)) + { + continue; + } + + // a callee that keeps it takes the copy; else it is released after the call + auto args = callArgs(call); + auto kept = llvm::any_of(ownedParams(call), [&](int32_t index) { + return static_cast(index) < args.size() && args[index] == value; + }); + + mlir::OpBuilder builder(call); + auto copy = builder.create(call->getLoc(), value.getType(), value); + for (auto &operand : call->getOpOperands()) + { + if (operand.get() == value) + { + operand.set(copy); + } + } + + if (!kept) + { + builder.setInsertionPointAfter(call); + builder.create(call->getLoc(), copy); + } + } } bool OwnershipInferencePass::borrowsKnownParam(mlir::Value value) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index c4bbe427d..176374aed 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -225,6 +225,9 @@ class OwnershipInferencePass llvm::DenseMap captureStores; // rc's references for boxes, which the closures decide llvm::DenseSet captureRetains; + // A string read out of a place, given to a call that may release it (the dry run's): the call + // gets a copy instead, released after it (spec 22), read -> call + llvm::SmallVector> callCopies; // each closure over a cell, by its `ts.CreateBoundFunction` llvm::DenseMap closureOf; // each generator's capture box, which escapes with its state object (classifyStateBoxes) @@ -788,6 +791,8 @@ class OwnershipInferencePass // Reports and returns false when the read is kept, or used after something that may destroy // it. bool checkPlaceRead(mlir::Operation *read, llvm::SetVector &toErase); + // Can `call` be given a copy of `value`, a string read out of a place, in its place (callCopies)? + static bool copiesInto(mlir::Operation *call, mlir::Value value); // A local that holds a borrow through `user`, and the field path under it that holds it (empty: // the local's value itself): a store of it into the local, or into a field of the local's value diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 458a67b52..c01cd4519 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -692,6 +692,14 @@ namespace own_inference }); } + bool OwnershipInferencePass::copiesInto(mlir::Operation *call, mlir::Value value) + { + // given once: a copy given twice would have two owners. Not an invoke, whose release after + // it would go on the normal path only. + return isCopyableString(value.getType()) && !mlir::isa(call) && + llvm::count(call->getOperands(), value) == 1; + } + bool OwnershipInferencePass::checkPlaceRead(mlir::Operation *read, llvm::SetVector &toErase) { auto loadOp = mlir::dyn_cast(read); @@ -736,6 +744,12 @@ namespace own_inference if (kept || letKept) { + // a string given to a call that keeps it: the call takes a copy (spec 22) + if (dryRun && kept && isCall(kept) && copiesInto(kept, result)) + { + callCopies.push_back({read, kept}); + } + if (!kept && isAssignmentOf(letKept, letKeeps)) { reportPlaceBorrowerAssigned(letKept, varName(letKeeps), place); @@ -757,6 +771,20 @@ namespace own_inference { if ((use.op != drop || !use.callee) && reachableAfter(drop, use.op, use.kills)) { + // a string given to the very call that may release it, when the call keeps it, or + // is a callback - a function value, which nothing can say `@nodrops` of: the call + // gets a copy + auto callee = calleeValue(drop); + auto args = callArgs(drop); + auto keepsIt = llvm::any_of(ownedParams(drop), [&](int32_t index) { + return static_cast(index) < args.size() && args[index] == result; + }); + if (dryRun && use.op == drop && (keepsIt || (callee && callee.getDefiningOp())) && + copiesInto(drop, result)) + { + callCopies.push_back({read, drop}); + } + reportPlaceBorrowOutlives(use.op, drop, name, place); return true; } diff --git a/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp b/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp index 2d60b63b5..72b3c2687 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp @@ -131,18 +131,130 @@ namespace own_signature } } - auto callsOnly = [&](mlir_ts::FuncOp funcOp) { + // A method no other method overrides: a call through its class's vtable, or of it bound to + // its object (`b.forEach(f)`), reaches it alone. A family holds every method of a slot's + // name, of any class: another member overrides it when its class extends this one (a base is + // the first field of a class's storage), or may, when its storage is not known here. + auto classOf = [&](llvm::StringRef symbol) { return symbol.drop_back(methodName(symbol).size() + 1); }; + auto extends = [&](llvm::StringRef derived, llvm::StringRef base) { + auto storage = classStorages.lookup(derived); + for (auto depth = 0; storage && depth < 64; ++depth) + { + auto fields = storage.getFields(); + auto next = fields.empty() ? mlir_ts::ClassStorageType() : mlir::dyn_cast(fields.front().type); + if (!next) + { + return false; + } + + if (next.getName().getValue() == base) + { + return true; + } + + storage = next; + } + + return true; + }; + + auto notOverridden = [&](mlir_ts::FuncOp funcOp) { + auto symbol = funcOp.getSymNameAttr(); + auto inVTable = false; + for (auto &[key, members] : families) + { + if (!llvm::is_contained(members, symbol)) + { + continue; + } + + inVTable = true; + for (auto member : members) + { + if (member != symbol && extends(classOf(member.getValue()), classOf(symbol.getValue()))) + { + return false; + } + } + } + + return inVTable; + }; + + // The calls a use of a function's symbol makes: the use itself, a direct call, or those made + // through the method it binds. Null when the symbol goes anywhere else. + auto callsOf = [&](mlir_ts::FuncOp funcOp, mlir::Operation *user, llvm::SmallVectorImpl &found) { + if (auto callee = directCallee(user)) + { + found.push_back(user); + return callee.getValue() == funcOp.getSymName(); + } + + if (!mlir::isa(user) || !notOverridden(funcOp) || + !onlyCalled(user->getResult(0))) + { + return isClassVTableEntry(user) && notOverridden(funcOp); + } + + // `ts.CallInternal(ts.GetMethod(m), ts.GetThis(m), ...)`: its arguments are the method's + // parameters, `this` first + for (auto *boundUser : user->getResult(0).getUsers()) + { + if (mlir::isa(boundUser)) + { + continue; + } + + if (!mlir::isa(boundUser)) + { + return false; + } + + for (auto *call : boundUser->getResult(0).getUsers()) + { + auto args = callArgs(call); + if (!mlir::isa(call) || args.empty() || + !args.front().getDefiningOp()) + { + return false; + } + + found.push_back(call); + } + } + + return true; + }; + + // The function a call made through a method's symbol calls, when it is the only one + auto methodCalled = [&](mlir::Operation *call) { + auto getMethodOp = calleeValue(call) ? calleeValue(call).getDefiningOp() : mlir_ts::GetMethodOp(); + auto *ref = getMethodOp ? getMethodOp.getBoundFunc().getDefiningOp() : nullptr; + mlir::FlatSymbolRefAttr identifier; + if (auto refOp = mlir::dyn_cast_or_null(ref)) + { + identifier = refOp.getIdentifierAttr(); + } + else if (auto refOp = mlir::dyn_cast_or_null(ref)) + { + identifier = refOp.getIdentifierAttr(); + } + + auto funcOp = identifier ? functions.lookup(identifier.getValue()) : mlir_ts::FuncOp(); + return funcOp && notOverridden(funcOp) ? funcOp : mlir_ts::FuncOp(); + }; + + auto callsOnly = [&](mlir_ts::FuncOp funcOp, llvm::SmallVectorImpl &calls) { auto &users = usersOf[funcOp]; - return !users.empty() && llvm::all_of(users, [&](mlir::Operation *user) { - auto callee = directCallee(user); - return callee && callee.getValue() == funcOp.getSymName(); - }); + return !users.empty() && + llvm::all_of(users, [&](mlir::Operation *user) { return callsOf(funcOp, user, calls); }); }; for (auto &entry : functions) { auto funcOp = entry.second; - if (funcOp.isDeclaration() || callableFromOutside(funcOp) || declaresFacts(funcOp) || !callsOnly(funcOp)) + llvm::SmallVector calls; + if (funcOp.isDeclaration() || callableFromOutside(funcOp) || declaresFacts(funcOp) || !callsOnly(funcOp, calls)) { continue; } @@ -156,7 +268,7 @@ namespace own_signature auto index = static_cast(argument.getArgNumber()); CallbackFamily family; - for (auto *user : usersOf[funcOp]) + for (auto *user : calls) { auto args = callArgs(user); auto shift = 0; @@ -195,7 +307,7 @@ namespace own_signature auto passesToClosed = [&](mlir::OpOperand &use) { auto *call = use.getOwner(); auto callee = directCallee(call); - auto calleeOp = callee ? functions.lookup(callee.getValue()) : mlir_ts::FuncOp(); + auto calleeOp = callee ? functions.lookup(callee.getValue()) : (isCall(call) ? methodCalled(call) : mlir_ts::FuncOp()); if (!calleeOp) { return false; @@ -267,8 +379,10 @@ namespace own_signature return; } + // a closed family with no members: a method no one calls but through its vtable, never - the + // call frees nothing auto found = callbackFamilies.find({funcOp.getOperation(), index}); - if (found == callbackFamilies.end() || !found->second.closed || found->second.members.empty()) + if (found == callbackFamilies.end() || !found->second.closed) { return; } diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 459e08419..7a73179ca 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -857,6 +857,65 @@ namespace own_signature return owned; } + llvm::SmallVector OwnershipSignaturePass::takenOnEveryPath(mlir_ts::FuncOp funcOp, llvm::ArrayRef kept) + { + if (kept.empty()) + { + return {}; + } + + if (auto found = everyPathCache.find(funcOp); found != everyPathCache.end()) + { + return found->second; + } + + auto &body = funcOp.getBody(); + mlir::DominanceInfo dominance(funcOp); + llvm::SmallVector exits; + funcOp.walk([&](mlir_ts::ReturnInternalOp returnOp) { exits.push_back(body.findAncestorOpInRegion(*returnOp)); }); + + llvm::SmallVector taken; + for (auto index : kept) + { + // the statements that keep the parameter, as decideParam sees a move + llvm::SmallVector takers; + for (auto *user : body.front().getArgument(index).getUsers()) + { + auto varOp = mlir::dyn_cast(user); + auto position = -1; + if (!varOp || !isParameterSlot(varOp, position)) + { + continue; + } + + for (auto *slotUser : varOp.getResult().getUsers()) + { + if (auto loadOp = mlir::dyn_cast(slotUser)) + { + forEachUse(loadOp.getResult(), [&](mlir::Operation *use, mlir::Value used) { + if (keeps(use, used)) + { + takers.push_back(body.findAncestorOpInRegion(*use)); + } + }); + } + } + } + + // a parameter kept only through what this pass cannot see (a mixed return): as before + auto everyPath = takers.empty() || llvm::all_of(exits, [&](mlir::Operation *exit) { + return exit && llvm::any_of(takers, [&](mlir::Operation *taker) { return taker && dominance.dominates(taker, exit); }); + }); + if (everyPath) + { + taken.push_back(index); + } + } + + everyPathCache[funcOp] = taken; + return taken; + } + void OwnershipSignaturePass::computeFacts() { llvm::DenseMap pinned; @@ -878,7 +937,7 @@ namespace own_signature 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) - takenParams[entry.second] = facts.owned; + takenParams[entry.second] = takenOnEveryPath(entry.second, facts.owned); if (auto mixed = mixedReturnParam(entry.second); mixed >= 0 && !llvm::is_contained(facts.owned, mixed)) { facts.owned.insert(llvm::upper_bound(facts.owned, mixed), mixed); @@ -1309,7 +1368,20 @@ namespace own_signature } else if (mlir::isa(op)) { - drops.any |= reachesOutside(op->getOperand(0), funcOp); + if (reachesOutside(op->getOperand(0), funcOp)) + { + // the elements of an array of its element type, as a store into one drops them + auto refType = mlir::dyn_cast(op->getOperand(0).getType()); + auto arrayType = refType ? mlir::dyn_cast(refType.getElementType()) : mlir_ts::ArrayType(); + if (arrayType) + { + drops.add({-1, mlir_ts::RefType::get(arrayType.getElementType())}); + } + else + { + drops.any = true; + } + } } else if (mlir::isa(op)) { diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 9055f176c..77813a559 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -6,6 +6,7 @@ #include "mlir/Pass/Pass.h" #include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/Dominance.h" #include "mlir/IR/SymbolTable.h" #include "mlir/Interfaces/FunctionInterfaces.h" @@ -473,6 +474,10 @@ class OwnershipSignaturePass : public mlir::PassWrapper> takenParams; + // Of a function's kept parameters, those taken on every path to a return: a move dominates + // each (`if (found) { e.value = v; return true; } return false;` takes `v` on one path only). + llvm::SmallVector takenOnEveryPath(mlir_ts::FuncOp funcOp, llvm::ArrayRef kept); + llvm::DenseMap> everyPathCache; // ---- Facts a signature says (`@keeps`, `@borrows`, `@lends`) ---- // diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 06dd1623c..2e9ae9b6d 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -3904,7 +3904,9 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_borrowing_record own_borrowing_record_arg own_reduce own_fresh_call_result own_ternary_outer_loop own_destructure_elements own_tuple_record_values own_value_record own_value_loop own_value_temporaries - own_call_field_drops own_immortal_keepers) + own_call_field_drops own_immortal_keepers + 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) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") tslang_add_test(NAME test-compile-own-${own_test} COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") # The promise: no counting at all in what own emits. @@ -4385,7 +4387,6 @@ set(own_error_cases "own_err_borrowed_result_family|an override in its class family disagrees" "own_err_param_kept_used|:19:11: error: '[^']*' is used here after its value was moved" "own_err_any_unboxed_outlives|:11:11: error: '[^']*' borrows the result of '___unbox>>' but is used here after it may be released or overwritten" - "own_err_param_kept_some_paths|:13:9: error: '[^']*' is moved here on some paths only" "own_err_param_kept_loop|:19:9: error: '[^']*' is moved inside a loop but was made outside it" "own_err_param_kept_not_owned|is given to 'keep', which keeps it, but -mm=own cannot move it here" "own_err_delete|'delete' is not supported by -mm=own yet" @@ -4508,7 +4509,8 @@ set(own_error_cases "own_err_lends_index_64|'@lends' of 'K[.]pick' names 'p63', but a method's '@lends' can name only its first 64 arguments, the receiver among them" "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 value' is a parameter, kept here, but -mm=own cannot make the callers of 'S.chars' give it up" - "own_err_string_call_keeps_twice|:19:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_generator_method_reassigned|:17:5: error: '[^']*' borrows '[^']*' but is used here after '[^']*' is released or overwritten" + "own_err_callback_method_overridden|:12:53: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_string_pushed_twice|:9:5: error: '[^']*' is used here after its value was moved" "own_err_shared_borrow_write|:12:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_shared_borrow_call|:19:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" diff --git a/tslang/test/tester/own/own_err_callback_method_overridden.ts b/tslang/test/tester/own/own_err_callback_method_overridden.ts new file mode 100644 index 000000000..ef12c0f30 --- /dev/null +++ b/tslang/test/tester/own/own_err_callback_method_overridden.ts @@ -0,0 +1,26 @@ +// -mm=own rejects: `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 { + constructor(public n: number) {} +} + +class Bag { + items: Node[] = []; + + forEach(f: (s: Node) => void) { + for (let i = 0; i < this.items.length; i++) f(this.items[i]); + } +} + +class Bag2 extends Bag { + forEach(f: (s: Node) => void) { + this.items = []; + } +} + +function main() { + const b: Bag = new Bag2(); + b.items.push(new Node(3)); + b.forEach((s) => print(s.n)); +} diff --git a/tslang/test/tester/own/own_err_generator_method_reassigned.ts b/tslang/test/tester/own/own_err_generator_method_reassigned.ts new file mode 100644 index 000000000..0ec6e332d --- /dev/null +++ b/tslang/test/tester/own/own_err_generator_method_reassigned.ts @@ -0,0 +1,18 @@ +// -mm=own rejects: the generator `w.letters()` borrows `w`, through the vtable of a class that +// is not `@final`, and `w` is given a new value while the generator is still read. It compiled when +// the method kept `this`; then the bound check did not see the object through `ts.GetThis`. +class Word { + constructor(public text: string) {} + + @borrows("this") + *letters() { + for (const c of this.text) yield c; + } +} + +function main() { + let w = new Word("abc"); + const it = w.letters(); + w = new Word("zz"); + for (const c of it) print(c); +} diff --git a/tslang/test/tester/own/own_err_param_kept_some_paths.ts b/tslang/test/tester/own/own_err_param_kept_some_paths.ts deleted file mode 100644 index d4fe30b81..000000000 --- a/tslang/test/tester/own/own_err_param_kept_some_paths.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -mm=own, phase 4 rejects: `keepIf` keeps its parameter only when `f` is true, and has nothing -// to release it with on the other path. -class C { - constructor(public x: number) {} -} - -class H { - c: C | null = null; -} - -function keepIf(h: H, c: C, f: boolean) { - if (f) { - h.c = c; - } -} - -function main() { - const h = new H(); - keepIf(h, new C(1), true); - print(h.c!.x); -} diff --git a/tslang/test/tester/own/own_err_string_call_keeps_twice.ts b/tslang/test/tester/own/own_err_string_call_keeps_twice.ts deleted file mode 100644 index 50ee9dcea..000000000 --- a/tslang/test/tester/own/own_err_string_call_keeps_twice.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -mm=own rejects, and does not copy: a field's string given twice to a call that keeps both -// arguments. A keeping call's retains are in the callee, so `main` has no retain to turn into a -// copy: the call takes the value without one (spec 22.4). -class P { - a = ""; - b = ""; -} - -const p = new P(); - -function both(x: string, y: string) { - p.a = x; - p.b = y; -} - -function main() { - const h = new P(); - h.a = "s" + 1; - both(h.a, h.a); - print(p.a, p.b); -} diff --git a/tslang/test/tester/own/own_generator_method_this.ts b/tslang/test/tester/own/own_generator_method_this.ts new file mode 100644 index 000000000..037b35825 --- /dev/null +++ b/tslang/test/tester/own/own_generator_method_this.ts @@ -0,0 +1,110 @@ +// -mm=own: a generator method whose state borrows `this` (`@borrows("this")`) leaves the object to +// its caller, who uses it after the loop. Through the vtable of a class that is not `@final` too, and +// through a method that only returns the generator (a forwarder). The state reads the object's +// fields through `this` at each step; a yielded tuple of strings takes copies of them. Each case +// churns the heap between steps, so an object freed early reads garbage. +class C { + v: number[] = []; + constructor(public x: number) {} +} + +function churn() { + const junk: C[] = []; + for (let i = 0; i < 64; i++) { + const c = new C(999); + c.v.push(99); + junk.push(c); + } +} + +class Bag { + names: string[] = []; + counts: number[] = []; + + add(name: string, count: number) { + this.names.push(name); + this.counts.push(count); + } + + @borrows("this") + private *iter() { + for (let i = 0; i < this.names.length; i++) { + const name = this.names[i]; + const count = this.counts[i]; + yield <[name: string, count: number]>[name, count]; + } + } + + @borrows("this") + private *iterNames() { + for (let i = 0; i < this.names.length; i++) { + const name = this.names[i]; + yield name; + } + } + + @borrows("this") + entries() { + return this.iter(); + } + + @borrows("this") + names_() { + return this.iterNames(); + } + + total() { + let n = 0; + for (const [name, count] of this.iter()) { + churn(); + n += count + name.length; + } + + return n; + } +} + +@final +class Word { + constructor(public text: string) {} + + @borrows("this") + *letters() { + for (const c of this.text) yield c; + } +} + +function main() { + const b = new Bag(); + b.add("ab", 1); + b.add("cde", 2); + + let joined = ""; + for (const [name, count] of b.entries()) { + churn(); + joined += name + count; + } + + assert(joined == "ab1cde2"); + + let names = ""; + for (const name of b.names_()) { + churn(); + names += name; + } + + assert(names == "abcde"); + assert(b.total() == 8); + + // the object is still the caller's after each loop + b.add("f", 3); + assert(b.total() == 12); + + const w = new Word("xyz"); + let s = ""; + for (const c of w.letters()) s += c; + for (const c of w.letters()) s += c; + assert(s == "xyzxyz" && w.text == "xyz"); + + print("done."); +} diff --git a/tslang/test/tester/own/own_length_drops_elements.ts b/tslang/test/tester/own/own_length_drops_elements.ts new file mode 100644 index 000000000..533b7907a --- /dev/null +++ b/tslang/test/tester/own/own_length_drops_elements.ts @@ -0,0 +1,30 @@ +// -mm=own: a method that sets an array's length (or pops, shifts, splices it) may free the elements of +// arrays of that element type, and nothing else. A borrow of an element of another type lent to it +// outlives the call: `grow` here cannot free a string out of `names`. +class Entry { + constructor(public key: string, public n: number) {} +} + +class Table { + entries: Entry[] = []; + + grow(size: number) { + this.entries.length = size; + } + + put(key: string, n: number) { + this.grow(this.entries.length + 1); + this.entries[this.entries.length - 1] = new Entry(key, n); + } + + fill(names: string[]) { + for (let i = 0; i < names.length; i++) this.put(names[i], i); + } +} + +function main() { + const t = new Table(); + t.fill(["a" + 1, "b" + 2]); + assert(t.entries.length == 2 && t.entries[0].key == "a1" && t.entries[1].n == 1); + print("done."); +} diff --git a/tslang/test/tester/own/own_loop_read_again.ts b/tslang/test/tester/own/own_loop_read_again.ts new file mode 100644 index 000000000..d8a7c0616 --- /dev/null +++ b/tslang/test/tester/own/own_loop_read_again.ts @@ -0,0 +1,32 @@ +// -mm=own: a value read in a loop and given to a call later in the same iteration is that +// iteration's. A `continue` before the call goes around the loop, where the slot is given its next +// value, and back to the read: that is a new read, not one the call is given (findBetween). The +// strings yielded are the loop's own; `keep` takes each. +function* words() { + yield "a" + 1; + yield "b" + 2; + yield "c" + 3; +} + +class Keep { + items: string[] = []; + + add(s: string) { + this.items.push(s); + } +} + +function skips(s: string) { + return s == "b2"; +} + +function main() { + const k = new Keep(); + for (const w of words()) { + if (skips(w)) continue; + k.add(w); + } + + assert(k.items.length == 2 && k.items[0] == "a1" && k.items[1] == "c3"); + print("done."); +} diff --git a/tslang/test/tester/own/own_method_callbacks.ts b/tslang/test/tester/own/own_method_callbacks.ts new file mode 100644 index 000000000..bf3d9dec2 --- /dev/null +++ b/tslang/test/tester/own/own_method_callbacks.ts @@ -0,0 +1,46 @@ +// -mm=own: what a method calls through a callback parameter is what its callers pass (spec 33's +// callback families), for a method called through its class's vtable too, when no method overrides +// it. Here every callback frees nothing, so `forEach` may lend them its elements. A method no one +// calls with a callback (`each` below) calls nothing through it. +class Node { + constructor(public n: number) {} +} + +class Bag { + items: Node[] = []; + + forEach(f: (s: Node) => void) { + for (let i = 0; i < this.items.length; i++) f(this.items[i]); + } + + each(f: (s: Node) => void) { + for (let i = 0; i < this.items.length; i++) f(this.items[i]); + } +} + +// a class of the same shape, unrelated to Bag: its `forEach` overrides nothing of Bag's +class Other { + items: Node[] = []; + + forEach(f: (s: Node) => void) { + for (let i = 0; i < this.items.length; i++) f(this.items[i]); + } +} + +function show(s: Node) { + print(s.n); +} + +function main() { + const b = new Bag(); + b.items.push(new Node(3)); + b.items.push(new Node(4)); + b.forEach((s) => print(s.n)); + b.forEach(show); + + const o = new Other(); + o.items.push(new Node(5)); + o.forEach(show); + + print("done."); +} diff --git a/tslang/test/tester/own/own_param_kept_some_paths.ts b/tslang/test/tester/own/own_param_kept_some_paths.ts new file mode 100644 index 000000000..3f6eeaa83 --- /dev/null +++ b/tslang/test/tester/own/own_param_kept_some_paths.ts @@ -0,0 +1,44 @@ +// -mm=own (spec 33): a parameter kept on some paths only is released on the others. `keepIf` keeps +// `c` only when `f` is true; `put` keeps it under two conditions, returning on each path. It was an +// error before (own_err_param_kept_some_paths): there was nothing to release it with. +class C { + constructor(public x: number) {} +} + +class H { + c: C | null = null; +} + +function keepIf(h: H, c: C, f: boolean) { + if (f) { + h.c = c; + } +} + +function put(h: H, c: C, found: boolean, over: boolean): boolean { + if (found) { + if (over) { + h.c = c; + return true; + } + + return false; + } + + return true; +} + +function main() { + const h = new H(); + keepIf(h, new C(1), true); + keepIf(h, new C(2), false); + assert(h.c!.x == 1); + + const g = new H(); + assert(put(g, new C(3), true, true)); + assert(!put(g, new C(4), true, false)); + assert(put(g, new C(5), false, true)); + assert(g.c!.x == 3); + + print("done."); +} diff --git a/tslang/test/tester/own/own_string_copy_call.ts b/tslang/test/tester/own/own_string_copy_call.ts new file mode 100644 index 000000000..64dae3fdf --- /dev/null +++ b/tslang/test/tester/own/own_string_copy_call.ts @@ -0,0 +1,70 @@ +// -mm=own, strings as values (spec 22): a string read out of a place, given to a call that may free +// it - a callback, which nothing can say `@nodrops` of - or to a call that keeps it, gets a copy. A +// tuple made of borrowed strings starts from copies of them. Each original is overwritten after, so +// a borrow instead of a copy reads the new value or freed memory. +class Bag { + items: string[] = []; + + forEach(f: (s: string) => void) { + for (let i = 0; i < this.items.length; i++) f(this.items[i]); + } + + keep(s: string) { + this.items.push(s); + } + + fill(from: string[]) { + for (let i = 0; i < from.length; i++) this.keep(from[i]); + } +} + +class P { + a = ""; + b = ""; +} + +const p = new P(); + +function both(x: string, y: string) { + p.a = x; + p.b = y; +} + +function pair(a: string[]): [string, number] { + const s = a[0]; + return [s, 1]; +} + +function main() { + // the callback overwrites the very element it was given + const b = new Bag(); + b.items.push("a" + 1); + let r = ""; + b.forEach((s) => { + b.items[0] = "zzzzzzzzzzzzzzzz"; + r += s; + }); + assert(r == "a1"); + + // a keeping call takes a copy of each element; the source is the caller's still + const src = ["b" + 2, "c" + 3]; + const k = new Bag(); + k.fill(src); + src[0] = "yyyyyyyyyyyyyyyy"; + assert(k.items[0] == "b2" && k.items[1] == "c3" && src[1] == "c3"); + + // a field's string given twice to a call that keeps both: each is a copy + const h = new P(); + h.a = "s" + 1; + both(h.a, h.a); + h.a = "xxxxxxxxxxxxxxxx"; + assert(p.a == "s1" && p.b == "s1"); + + // a tuple of a borrowed element + const a = ["d" + 4]; + const t = pair(a); + a[0] = "wwwwwwwwwwwwwwww"; + assert(t[0] == "d4" && t[1] == 1); + + print("done."); +} diff --git a/tslang/test/tester/own/own_tuple_param_kept.ts b/tslang/test/tester/own/own_tuple_param_kept.ts new file mode 100644 index 000000000..d1a9aa818 --- /dev/null +++ b/tslang/test/tester/own/own_tuple_param_kept.ts @@ -0,0 +1,33 @@ +// -mm=own: a tuple made of borrowed strings stored into an element - also cast to a named tuple, +// which reads its fields out into a new one - starts from copies of them (spec 22). The function +// keeps nothing: its callers keep their strings, and may give the same one to it twice. +type Entry = [key: string, n: number]; + +class Table { + entries: Entry[] = []; + + put(key: string, n: number) { + this.entries.length = this.entries.length + 1; + this.entries[this.entries.length - 1] = [key, n]; + } +} + +function putBoth(a: Table, b: Table, k: string) { + a.put(k, 1); + b.put(k, 2); +} + +function main() { + const t = new Table(); + const keys = ["a" + 1]; + t.put(keys[0], 7); + keys[0] = "zzzzzzzzzzzzzzzz"; + t.put("b" + 2, 8); + const k = "c" + 3; + t.put(k, 9); + const u = new Table(); + putBoth(t, u, k); + assert(t.entries[0][0] == "a1" && t.entries[0][1] == 7 && t.entries[1][0] == "b2" && t.entries[2][0] == "c3"); + assert(t.entries[3][0] == "c3" && u.entries[0][0] == "c3" && k == "c3" && keys[0] == "zzzzzzzzzzzzzzzz"); + print("done."); +}