From 24485c3d35e846873faec8df29621ab804eb1f3d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 9 Nov 2026 18:22:55 +0000 Subject: [PATCH 1/5] TSLANG_ISSUES: items 39-42, -mm=own limits found in the default library Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 229 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 229 insertions(+) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 399c3112f..86c71ec43 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -76,3 +76,232 @@ Regression tests `tslang/test/tester/tests/00tslang_issue_37.ts`, `00tslang_issu Still open from 38: a symbol made at run time can't be a property key (`obj[sym]`). Fields are laid out at compile time, so a symbol needs a run-time value and a way to look a key up. It has not been tried. + +### `-mm=own` limits found in the default library, 2026-11-09 (items 39-42) + +Found while adding `Worker` and making `JSON.stringify` work under `-mm=own` in the default library +(TypeScriptCompilerDefaultLib PRs #80-#85). The library works around each one, and its README names +them as `-mm=own` limits; each needs a compiler change to go away. Every repro below is a complete +file, run with `tslang --nowarn -mm=own --emit=jit file.ts` and again with `-mm=gc`, on Windows x64, +tslang commit 2fffc119 (release build of 2026-11-09 17:35), against the default library at +TypeScriptCompilerDefaultLib 916cd07. Each compiles and runs under `-mm=gc`, with the output given. + +#### 39. A method can't say it gives its receiver back owned, so a chain from a new value can't be returned or kept by a callee + +A method that returns `this` so calls can be chained (`JsonValue.set`, `JsonValue.push`) can only be +declared `@lends("this")` for another module: its result borrows the value it was called on. A chain +that starts from a new value (`JsonValue.newObject().set(...)`) has no owner but that borrow. Kept in a +local it compiles now; returned, or given to a parameter that is kept, it is an error. + +```typescript +// JsonValue is in the default library, another module: its set() and push() are declared +// @lends("this") (they return `this`, so a chain can go on), and that is all a caller knows of them. + +// returning a chain from a new value: under -mm=own "'this value' borrows the result of +// 'JsonValue.set' and cannot be stored, returned or captured" +function person(): JsonValue { + return JsonValue.newObject().set("name", JsonValue.ofString("Ann")).set("age", JsonValue.ofNumber(30)); +} + +function main() { + // compiles under -mm=own: a chain kept in a local + const a = JsonValue.newObject().set("a", JsonValue.ofNumber(1)); + print(a.stringify()); + + print(person().stringify()); + + // a chain given to a parameter that is kept (set's `value`): the same error + const b = JsonValue.newObject(); + b.set("list", JsonValue.newArray().push(JsonValue.ofNumber(1)).push(JsonValue.ofNumber(2))); + print(b.stringify()); +} +``` + +`-mm=own`: + +```text +39_chain_receiver.ts:7:5: error: 'this value' borrows the result of 'JsonValue.set' and cannot be stored, returned or captured + return JsonValue.newObject().set("name", JsonValue.ofString("Ann")).set("age", JsonValue.ofNumber(30)); + ^ +39_chain_receiver.ts:19:5: error: 'this value' borrows the result of 'JsonValue.push' and cannot be stored, returned or captured + b.set("list", JsonValue.newArray().push(JsonValue.ofNumber(1)).push(JsonValue.ofNumber(2))); + ^ +``` + +`-mm=gc`: `{"a":1}`, `{"name":"Ann","age":30}`, `{"list":[1,2]}`. + +To do: a way to declare that a method returns its receiver (`return this` on every path), so that +called on a value the caller owns, or on a temporary, the result is that value, owned by whoever owned +the receiver, rather than a borrow of it. Something like `@returnsThis` / `@lends("this")` that a +temporary receiver turns into a move. Then the default library's `tests/json.ts` can drop its +`__MEMORY_MODEL__ != "own"` branch (`chained()`), and `toJSON()` can return a chain. + +#### 40. Once an arrow captures anything, an arrow inside it can't capture the outer arrow's parameter + +An arrow given a parameter (`self`) stores a second arrow that captures `self`. That compiles under +`-mm=own`, until the outer arrow also captures something from its own enclosing function. Then the +inner arrow's capture of `self` is refused. It is the shape of the default library's `Worker`: +`new Worker((self) => { self.onmessage = (e) => self.postMessage(...); })`. A worker whose function +uses state shared with the creating thread can't also post from its handler (the library's README and +`docs/worker-design.md` name the limit; `tests/worker_terminate.ts` tests the two shapes apart). + +```typescript +class Scope { + handler: () => void; + count: int; + + constructor() { + this.handler = () => {}; + this.count = 0; + } +} + +function run(body: (self: Scope) => void) { + const scope = new Scope(); + body(scope); + scope.handler(); + print(scope.count); +} + +function main() { + const shared = new Shared(new Int32Array(1)); + + // compiles under -mm=own and prints 1: the outer arrow captures nothing + run((self: Scope) => { + self.handler = () => { + self.count++; + }; + }); + + // the same, once the outer arrow captures something: under -mm=own + // "a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: + // its value is the caller's", at the inner arrow + run((self: Scope) => { + const counter = shared; + Atomics.add(counter.value, 0, 1); + self.handler = () => { + self.count++; + }; + }); +} +``` + +`-mm=own`: + +```text +40_closure_param_capture.ts:34:24: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: its value is the caller's + self.handler = () => { + ^ +``` + +`-mm=gc`: `1`, `1`. + +To do: the inner arrow captures `self` the same way in both calls, and `self` is the outer arrow's +parameter in both; what the outer arrow captures should not change whose `self` is. The error also +does not name the variable (item 32 made it name a captured variable in other cases). + +#### 41. An arrow kept in a field can't capture a parameter, and `@keeps` can't say that it does + +A constructor that keeps an arrow capturing one of its parameters is refused ("its value is the +caller's"), and `@keeps("body")`, which would make the caller give `body` up, is refused too: the +compiler finds that the constructor keeps nothing, although the arrow it stores takes `body` with it. +The default library hit this starting a `Worker`'s thread with `Thread.spawn(() => run(body, ...))` in +its constructor; it now keeps a `WorkerStart` object holding `body` (as `ThreadHandle` keeps its +`ThreadStart`) and starts the thread natively. + +```typescript +class Holder { + run: () => int; + + constructor(body: (n: int) => int) { + // the arrow is kept in a field and captures the parameter `body` + this.run = (): int => body(2); + } +} + +function main() { + const h = new Holder((n: int): int => n * 21); + print(h.run()); +} +``` + +`-mm=own`: + +```text +41_keeps_closure_capture.ts:6:20: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: its value is the caller's + this.run = (): int => body(2); + ^ +41_keeps_closure_capture.ts:6:9: note: the closure escapes here + this.run = (): int => body(2); + ^ +``` + +With `@keeps("body")` on the constructor (and `@final export class Holder`): + +```text +41b_keeps_rejected.ts:6:5: error: '@keeps' of 'Holder.constructor' names 'body', but its body keeps nothing + @keeps("body") + ^ +``` + +`-mm=gc`: `42`. + +To do: count a parameter captured by an escaping closure as kept, both when inferring what a function +keeps and when checking `@keeps`, so the closure owns it (the caller moves the argument in). + +#### 42. A class instance can't be taken out of a `T | undefined` field + +Exchanging a field with a local (`[data, this.data] = [this.data, data]`), the way the own-model guide +says to take a value out of a place, works for a string but not for a class instance in a field typed +`T | undefined`. The default library wanted a queue item holding either a message or an error; it now +queues the event objects themselves (`MessageEvent | ErrorEvent`) so nothing has to come out of a +field. + +```typescript +class Item { + constructor(public n: number) {} +} + +// a slot a value is put into and later taken back out of, by exchanging it with a local +class Slot { + constructor(public data: T | undefined) {} + + take(): T { + let data: T | undefined = undefined; + [data, this.data] = [this.data, data]; + return data; + } +} + +function main() { + // compiles under -mm=own and prints "a" + const text = new Slot("a"); + print(text.take()); + + // the same for a class instance: under -mm=own + // "'this value' borrows a field and cannot be stored, returned or captured" + const item = new Slot(new Item(1)); + print(item.take().n); +} +``` + +`-mm=own`: + +```text +42_move_out_of_union_field.ts:11:29: error: 'this value' borrows a field and cannot be stored, returned or captured + [data, this.data] = [this.data, data]; + ^ +42_move_out_of_union_field.ts:11:9: error: 'this value' borrows an element and cannot be stored, returned or captured + [data, this.data] = [this.data, data]; + ^ +42_move_out_of_union_field.ts:12:9: error: 'this value' is merged from several branches (`?:`, `&&`, `||`, `??`, a loop); -mm=own cannot prove which one owns it yet + return data; + ^ +``` + +The same file with only the `Slot` lines compiles under `-mm=own` and prints `a`. +`-mm=gc`: `a`, `1`. + +To do: the exchange of a union-typed field with a local should move the value out for a class +instance as it does for a string, and the `` cast of a `T | undefined` local that holds it should +not count as a merge of branches. From 100b44eb8518dc5832c26be250b0f49f4f061b36 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 9 Nov 2026 18:32:39 +0000 Subject: [PATCH 2/5] -mm=own: a closure kept owns the parameters it captures; a local exchanged with a field takes its value (items 40-42) 40: an arrow that captures something and stores a closure over its object parameter into a field of that object is a back-reference, as one that captures nothing is: the member's `this` of a closure body is the parameter after its box (spec 75). 41: a closure that is kept (stored into a field, a global, an array, or given to a call that keeps it) owns what its box holds of the function's parameters, captured by copy or in a cell, so the function keeps them and `@keeps` may say so (spec 76). The error for a capture that still cannot move names it. 42: `[local, place] = [place, local]` reads and counts both values, then refills the place and assigns the local; under -mm=own the refill's release hands the place's value over to the local (spec 77). `x` of a class `T | undefined` is one select (ts.ValueOrDefault), a view of the optional. Co-Authored-By: Claude Opus 5.5 --- tslang/include/TypeScript/Defines.h | 4 + tslang/lib/TypeScript/LowerToLLVM.cpp | 5 +- tslang/lib/TypeScript/MLIRGenCast.cpp | 10 ++ tslang/lib/TypeScript/MLIRGenImpl.h | 59 +++++++- tslang/lib/TypeScript/OwnershipFacts.h | 22 ++- .../OwnershipInferenceDiagnostics.cpp | 33 +++- .../lib/TypeScript/OwnershipInferencePass.h | 5 + .../OwnershipInferencePlaceReads.cpp | 142 ++++++++++++++++++ .../lib/TypeScript/OwnershipSignaturePass.cpp | 55 ++++++- .../lib/TypeScript/OwnershipSignaturePass.h | 7 + tslang/test/tester/CMakeLists.txt | 9 +- .../tester/own/own_closure_keeps_param.ts | 114 ++++++++++++++ .../own/own_err_back_reference_captures.ts | 3 +- .../own/own_err_closure_kept_param_used.ts | 20 +++ .../test/tester/own/own_swap_local_field.ts | 85 +++++++++++ 15 files changed, 559 insertions(+), 14 deletions(-) create mode 100644 tslang/test/tester/own/own_closure_keeps_param.ts create mode 100644 tslang/test/tester/own/own_err_closure_kept_param_used.ts create mode 100644 tslang/test/tester/own/own_swap_local_field.ts diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 294786cd1..6c8367545 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -39,6 +39,10 @@ // retain nobody performed and free live memory. #define OWNED_RESULT_ATTR_NAME "__owned_result" +// On a `ts.ValueOrDefault`: an explicit cast in the source (`data` of a `T | undefined`) made +// it, so its lowering does not warn that an optional value is read as it is. +#define EXPLICIT_CAST_ATTR_NAME "__explicit_cast" + // -mm=own only, set by OwnershipInferencePass for the lowering. On a `ts.Release` of an array: the // array borrowed its elements (the array a rest parameter is given), so its release frees the // array and not them. diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 1c6c3a182..987e0c6b6 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -6252,7 +6252,10 @@ struct ValueOrDefaultOpLowering : public TsLlvmPatterngetLoc(); - valueOrDefaultOp->emitWarning("casting from optional (undefined) value"); + if (!valueOrDefaultOp->hasAttr(EXPLICIT_CAST_ATTR_NAME)) + { + valueOrDefaultOp->emitWarning("casting from optional (undefined) value"); + } TypeHelper th(rewriter); TypeConverterHelper tch(getTypeConverter()); diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index b27b35f85..b72369f60 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -2184,6 +2184,16 @@ namespace mlirgen return unwrappedValue; } + // a class object or null: the value, or null when there is none (`data` of a `T | + // undefined`). One select, not a branch: under -mm=own the result is a view of the optional, + // the same block or none (spec 77), where a merge of two branches would hide whose it is + if (type == optType.getElementType() && isa(type)) + { + auto valueOrDefault = builder.create(location, type, value); + valueOrDefault->setAttr(EXPLICIT_CAST_ATTR_NAME, builder.getUnitAttr()); + return V(valueOrDefault); + } + // optional to value cast(when we change types) auto hasValue = builder.create(location, mlir_ts::BooleanType::get(builder.getContext()), value); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 5cf86193f..bc487749a 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -7699,6 +7699,48 @@ class MLIRGenImpl return reference; } + // The slot of a local a target names, when an exchange with a place may write it as an assignment + // does: a local of this function that owns what it holds - not a captured one, whose cell another + // frame may read, nor a global. + mlir::Value swappableLocal(mlir::Value targetValue) + { + auto loadOp = targetValue.getDefiningOp(); + auto varOp = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + if (!varOp || varOp.getCaptured().value_or(false) || !isOwningSlot(loadOp.getLoc(), varOp.getResult())) + { + return mlir::Value(); + } + + return varOp.getResult(); + } + + // `[local, place] = [place, local]`: both values are read and counted first, then the place is + // given the local's value and the local the place's, each store releasing what its storage held, + // as an assignment does. Built through an array literal, the place's value would be read out of + // it (under -mm=own a borrow, which may not be stored) and the literal would own a second + // reference to it. The place is written first: its release frees nothing the local is given, + // which -mm=own sees as the place handing its value over to the local (spec 77). + void mlirGenSwapWithLocal(mlir::Location location, mlir::Value local, mlir::Value place) + { + auto placeValue = builder.create(location, mlir::cast(place.getType()).getElementType(), place); + auto localValue = builder.create(location, mlir::cast(local.getType()).getElementType(), local); + MLIRTypeHelper mth(builder.getContext(), compileOptions); + if (mth.ownsHeapMemory(location, placeValue.getType())) + { + builder.create(location, placeValue); + builder.create(location, localValue); + builder.create(location, place); + } + + builder.create(location, localValue, place); + if (mth.ownsHeapMemory(location, placeValue.getType())) + { + builder.create(location, local); + } + + builder.create(location, placeValue, local); + } + // `[p, q] = [q, p]` of two elements or fields: an exchange, which moves nothing. Built through // an array literal, each value would be read out of its place (under -mm=own a borrow, which // may not be stored) and the literal would own a second reference to it. Only a statement's, @@ -7732,7 +7774,22 @@ class MLIRGenImpl auto firstPlace = swappablePlace(V(first)); auto secondPlace = swappablePlace(V(second)); - if (!firstPlace || !secondPlace || firstPlace.getType() != secondPlace.getType()) + if (!firstPlace || !secondPlace) + { + // a local and a place: `[data, this.data] = [this.data, data]` + auto local = firstPlace ? swappableLocal(V(second)) : swappableLocal(V(first)); + auto place = firstPlace ? firstPlace : secondPlace; + if (local && place && local.getType() == place.getType() && isOwningSlot(location, place)) + { + mlirGenSwapWithLocal(location, local, place); + swapped = true; + } + + // otherwise the reads are dead: the assignment reads the places again + return mlir::success(); + } + + if (firstPlace.getType() != secondPlace.getType()) { // the reads are dead: the assignment reads the places again return mlir::success(); diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 581c8677c..b55918b61 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -352,8 +352,10 @@ inline llvm::SmallVector valuesStoredInto(mlir_ts::VariableOp varOp // printed into a string) or boxes (into `any`) makes a new block and is not one. inline bool isView(mlir::Operation *op) { + // (`ts.ValueOrDefault` of a class: the optional's object, or null - the same block or none, spec 77) if (mlir::isa_and_nonnull(op)) + mlir_ts::OptionalValueOp, mlir_ts::ValueOp, mlir_ts::NewInterfaceOp>(op) || + (mlir::isa_and_nonnull(op) && mlir::isa(op->getResult(0).getType()))) { return true; } @@ -1468,7 +1470,23 @@ inline mlir::BlockArgument parameterRead(mlir::Value value) inline bool isMemberThis(mlir::Value value) { auto argument = parameterRead(value); - return argument && argument.getArgNumber() == 0 && mlir::isa(argument.getType()); + if (!argument || !mlir::isa(argument.getType())) + { + return false; + } + + // a closure's body takes its box first (a reference to the tuple of what it captures): its first + // parameter is the one after it, so an arrow that captures something and fills a field of the + // object it is given is the same back-reference as one that captures nothing (spec 75) + auto *block = argument.getOwner(); + auto first = 0u; + if (argument.getArgNumber() > 0 && block->getNumArguments() > 1) + { + auto boxType = mlir::dyn_cast(block->getArgument(0).getType()); + first = boxType && mlir::isa(boxType.getElementType()) ? 1 : 0; + } + + return argument.getArgNumber() == first; } // A copy a closure's own box holds, read out of it (the box is the closure body's first argument): the diff --git a/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp b/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp index 968160e1f..348584b1f 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp @@ -297,11 +297,29 @@ namespace own_inference // reads the slot again for the box's field), the box of a closure that escapes - a // parameter nothing assigns is captured by copy, and its cell used to be refused the same // way (decideEscaping) + // the box's field is named after what it captures, with or without `--di` + std::string captured; auto isBoxFill = [&](mlir::Operation *user) { auto storeOp = mlir::dyn_cast(user); auto propertyRefOp = storeOp ? storeOp.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); - return propertyRefOp && closureOfBox(propertyRefOp.getObjectRef()) && user->getLoc() == op->getLoc(); + if (!propertyRefOp || !closureOfBox(propertyRefOp.getObjectRef()) || user->getLoc() != op->getLoc()) + { + return false; + } + + auto boxType = mlir::dyn_cast(propertyRefOp.getObjectRef().getType()); + auto tupleType = boxType ? mlir::dyn_cast(boxType.getElementType()) : mlir_ts::TupleType(); + auto position = propertyRefOp.getPosition(); + if (tupleType && position < tupleType.size()) + { + if (auto fieldName = mlir::dyn_cast_or_null(tupleType.getFieldInfo(position).id)) + { + captured = fieldName.getValue().str(); + } + } + + return true; }; auto retainOp = mlir::dyn_cast(op); auto retainedRead = retainOp ? retainOp->getOperand(0).getDefiningOp() : mlir_ts::LoadOp(); @@ -311,8 +329,17 @@ namespace own_inference }); if (boxFill) { - op->emitError("a closure that escapes owns what it captures, but -mm=own cannot move this variable " - "into it: its value is the caller's"); + auto diag = op->emitError("a closure that escapes owns what it captures, but -mm=own cannot move "); + if (captured.empty()) + { + diag << "this variable"; + } + else + { + diag << "'" << captured << "'"; + } + + diag << " into it: its value is the caller's"; return true; } diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 2f1a4056d..7d8e1086c 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -863,6 +863,11 @@ class OwnershipInferencePass // objects holds, that nothing sees after the move but its ends, and that is not taken from twice // (specs 64, 65)? bool namedFieldTakeOf(mlir::Operation *read, mlir::Operation *retain, mlir_ts::PropertyRefOp field, FieldTake &take); + // ...or is `kept` rc's retain of `read`, a read of a field or an element of any object, whose + // taker the place is refilled before (spec 77): `[data, this.data] = [this.data, data]`. The + // refill's release, which would free what was read, hands it over to the taker. `refill` is that + // release; nothing but reads and stores of locals runs between the read and the taker. + bool refilledFieldTakeOf(mlir::Operation *read, mlir::Operation *kept, FieldTake &take, mlir::Operation *&refill); // Can `call` be given a copy of `value`, a string read out of a place, in its place (callCopies)? static bool copiesInto(mlir::Operation *call, mlir::Value value); // Does `store` put `value`, a string read out of a place, into another place with no retain of diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 40567e916..0369d0ac3 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -905,6 +905,34 @@ namespace own_inference } } + // ...or out of a place refilled before the taker has what it held (spec 77): `[data, this.data] + // = [this.data, data]`. The refill's release would free it: the value is handed over instead, + // and the refill leaves nothing of it in the place. + mlir::Operation *refill = nullptr; + if (!take.taker && kept && !countedHandle && !backReference && refilledFieldTakeOf(read, kept, take, refill)) + { + takenOps.insert(take.retain); + takenOps.insert(take.taker); + kept = walk(); + takenOps.clear(); + auto usedAfter = llvm::any_of(uses, [&](auto &use) { + return use.op != take.taker && use.op != take.retain && reachableAfter(take.taker, use.op, use.kills); + }); + if (kept || letKept || usedAfter) + { + take = {}; + refill = nullptr; + kept = walk(); + } + else + { + bookkeeping.push_back(take.retain); + bookkeeping.push_back(refill); + toErase.insert(bookkeeping.begin(), bookkeeping.end()); + return true; + } + } + if (take.taker) { bookkeeping.push_back(take.retain); @@ -1267,6 +1295,120 @@ namespace own_inference return true; } + bool OwnershipInferencePass::refilledFieldTakeOf(mlir::Operation *read, mlir::Operation *kept, FieldTake &take, + mlir::Operation *&refill) + { + // a read of a field or an element, of any object: what the place held goes to the taker, the + // place is given another value before that, and its release then frees nothing anyone keeps. + // Not a string, which is copied where it is kept (spec 22), nor a handle, which is counted. + auto loadOp = mlir::dyn_cast(read); + auto place = loadOp ? loadOp.getReference() : mlir::Value(); + if (!place || !mlir::isa_and_nonnull(place.getDefiningOp()) || + isCopyableValueAt(read, loadOp.getType()) || isHandle(loadOp.getResult())) + { + return false; + } + + // rc's retain of the read, in its block + mlir_ts::RetainOp retainOp; + for (auto *user : loadOp->getUsers()) + { + if (auto found = mlir::dyn_cast(user); found && found->getBlock() == read->getBlock()) + { + if (retainOp) + { + return false; + } + + retainOp = found; + } + } + + auto *taker = retainOp ? takerOf(retainOp, loadOp.getResult()) : nullptr; + if (!taker || (kept != retainOp && kept != taker) || taker->getBlock() != read->getBlock()) + { + return false; + } + + // the taker: a store into a local that owns what it holds, or into a place + auto storeOp = mlir::dyn_cast(taker); + auto slot = storeOp ? storeOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + auto intoLocal = slot && isOwningVariable(slot) && !slot.getCaptured().value_or(false); + if (!storeOp || storeOp.getValue() != loadOp.getResult() || (!intoLocal && !isPlace(storeOp.getReference()))) + { + return false; + } + + // From the read to the taker, in order: rc's retain, then the place's release right before a + // store into it - the refill - and nothing but reads, counts and stores of locals besides + // (no call, which might read the place or drop the object). + auto *refillRelease = static_cast(nullptr); + auto retained = false; + for (auto *op = read->getNextNode(); op && op != taker; op = op->getNextNode()) + { + if (op == retainOp.getOperation()) + { + retained = true; + continue; + } + + if (auto releaseSlotOp = mlir::dyn_cast(op); releaseSlotOp && releaseSlotOp.getSlot() == place) + { + auto refillStore = mlir::dyn_cast_or_null(op->getNextNode()); + if (refillRelease || !retained || !refillStore || refillStore.getReference() != place) + { + return false; + } + + refillRelease = op; + continue; + } + + if (auto releaseSlotOp = mlir::dyn_cast(op)) + { + // a local's own release (the taker's assignment), never of the place's object + auto local = releaseSlotOp.getSlot().getDefiningOp(); + auto objectRead = rootOf(place.getDefiningOp()->getOperand(0)).getDefiningOp(); + if (!local || local.getCaptured().value_or(false) || + (objectRead && objectRead.getReference() == local.getResult())) + { + return false; + } + + continue; + } + + if (auto innerStore = mlir::dyn_cast(op)) + { + auto local = innerStore.getReference().getDefiningOp(); + if (innerStore.getReference() != place && !local) + { + return false; + } + + continue; + } + + if (mlir::isa(op) || isView(op)) + { + continue; + } + + return false; + } + + if (!refillRelease) + { + return false; + } + + take.retain = retainOp; + take.taker = taker; + take.field = place; + refill = refillRelease; + return true; + } + bool OwnershipInferencePass::namedFieldTakeOf(mlir::Operation *read, mlir::Operation *retain, mlir_ts::PropertyRefOp field, FieldTake &take) { diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 15708d037..07e891d89 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -894,11 +894,15 @@ namespace own_signature // assigns, which a closure captures by copy too, or a copy the enclosing closure's box // holds: the object is the caller's, which no box can own. A closure that does not escape // borrows it, as it did the cell; one stored into a field of `this` is a back-reference; - // any other one is inference's error + // any other one is inference's error - unless the closure is kept itself (stored into a + // field, a global, an array, or given to a call that keeps it): then it owns the parameter, + // as a field it is stored into would, and the callers give it up (spec 76). Not the + // member's `this`, which its callers cannot give to an object the object owns. if (auto propertyRefOp = storeOp.getReference().getDefiningOp(); propertyRefOp && isBorrowableCapture(used) && closureOfBox(propertyRefOp->getOperand(0))) { - return false; + return storeOp.getValue() == used && parameterRead(used) && !isMemberThis(used) && + keepsClosure(propertyRefOp->getOperand(0)); } // ...or a bound method of `this` stored into a field of `this`: it borrows the object @@ -967,6 +971,32 @@ namespace own_signature return false; } + bool OwnershipSignaturePass::keepsClosure(mlir::Value box) + { + auto boundOp = closureOfBox(box); + if (!boundOp || isBackReferenceBox(box)) + { + return false; + } + + auto kept = false; + forEachUse(boundOp.getResult(), [&](mlir::Operation *use, mlir::Value used) { kept = kept || keeps(use, used); }); + return kept; + } + + int32_t OwnershipSignaturePass::parameterOfCell(mlir_ts::VariableOp cellOp) + { + auto argument = cellOp.getInitializer() ? mlir::dyn_cast(cellOp.getInitializer()) + : mlir::BlockArgument(); + if (!cellOp.getCaptured().value_or(false) || isOwningVariable(cellOp) || !argument || + !argument.getOwner()->isEntryBlock() || !mlir::isa(argument.getOwner()->getParentOp())) + { + return -1; + } + + return static_cast(argument.getArgNumber()); + } + llvm::SmallVector OwnershipSignaturePass::localOwnedParams(mlir_ts::FuncOp funcOp) { llvm::SmallVector owned; @@ -1007,6 +1037,27 @@ namespace own_signature } } + // the parameter's cell, given to a closure that is kept: the closure owns the cell, and + // the value in it, so the function keeps the parameter (spec 76) + for (auto *argumentUser : argument.getUsers()) + { + auto cellOp = mlir::dyn_cast(argumentUser); + if (kept || !cellOp || parameterOfCell(cellOp) != static_cast(argument.getArgNumber()) || + !own_facts::ownsHeap(cellOp.getLoc(), argument.getType())) + { + continue; + } + + for (auto *cellUser : cellOp->getUsers()) + { + auto storeOp = mlir::dyn_cast(cellUser); + auto propertyRefOp = storeOp && storeOp.getValue() == cellOp.getResult() + ? storeOp.getReference().getDefiningOp() + : mlir_ts::PropertyRefOp(); + kept = kept || (propertyRefOp && keepsClosure(propertyRefOp->getOperand(0))); + } + } + if (kept) { owned.push_back(argument.getArgNumber()); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 292d270a8..0df4673af 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -985,6 +985,13 @@ class OwnershipSignaturePass : public mlir::PassWrapper int; + + constructor(body: (n: int) => int) { + this.run = (): int => body(2); + } +} + +// the same, as another module would be told it +@final +export class Declared { + run: () => int; + + @keeps("body") + constructor(body: (n: int) => int) { + this.run = (): int => body(3); + } +} + +// a class instance captured by copy, by a closure kept in a field of `this` +class Counter { + n: number = 1; + get = () => 0; + + setup(item: Item) { + this.get = () => item.n * 10; + } +} + +// ...and by one pushed into an array +const tasks: (() => number)[] = []; + +function schedule(item: Item) { + tasks.push(() => item.n + 100); +} + +class Scope { + handler: () => void; + count: int; + + constructor() { + this.handler = () => {}; + this.count = 0; + } +} + +function run(body: (self: Scope) => void): int { + const scope = new Scope(); + body(scope); + churn(); + scope.handler(); + scope.handler(); + return scope.count; +} + +function main() { + const h = new Holder((n: int): int => n * 21); + churn(); + assert(h.run() == 42, "callback kept by a closure"); + + const d = new Declared((n: int): int => n * 14); + churn(); + assert(d.run() == 42, "@keeps of a callback a closure keeps"); + + const c = new Counter(); + c.setup(new Item(4)); + churn(); + assert(c.get() == 40, "instance kept by a closure in a field"); + + schedule(new Item(5)); + churn(); + assert(tasks[0]() == 105, "instance kept by a closure in an array"); + + // an arrow that captures nothing fills a field of what it is given + assert(run((self: Scope) => { + self.handler = () => { + self.count++; + }; + }) == 2, "back-reference from an arrow capturing nothing"); + + // ...and one that captures a number and a handle + let seen = 0; + const shared = new Shared(new Item(3)); + assert(run((self: Scope) => { + const counter = shared; + seen += counter.value.n; + self.handler = () => { + self.count++; + }; + }) == 2, "back-reference from an arrow that captures"); + assert(seen == 3, "the capturing arrow ran"); + + print("done."); +} diff --git a/tslang/test/tester/own/own_err_back_reference_captures.ts b/tslang/test/tester/own/own_err_back_reference_captures.ts index 7a3ec6d2e..a25704ce9 100644 --- a/tslang/test/tester/own/own_err_back_reference_captures.ts +++ b/tslang/test/tester/own/own_err_back_reference_captures.ts @@ -1,5 +1,6 @@ // A closure stored into a field of `this` that captures something besides `this` (a parameter) is no -// back-reference (spec 70): an escaping closure owns what it captures, and the parameter is the caller's. +// back-reference (spec 70): an escaping closure owns what it captures. The method keeps the parameter +// (spec 76), but `this` is the caller's, which no object it owns can own. class Item { n: number = 2; } diff --git a/tslang/test/tester/own/own_err_closure_kept_param_used.ts b/tslang/test/tester/own/own_err_closure_kept_param_used.ts new file mode 100644 index 000000000..5f11fef66 --- /dev/null +++ b/tslang/test/tester/own/own_err_closure_kept_param_used.ts @@ -0,0 +1,20 @@ +// A method that keeps a closure capturing its parameter keeps the parameter (spec 76): the caller +// gives the argument up, so reading it after the call is a use after a move. +class Item { + constructor(public n: number) {} +} + +class Counter { + get = () => 0; + + setup(item: Item) { + this.get = () => item.n; + } +} + +function main() { + const c = new Counter(); + const item = new Item(4); + c.setup(item); + print(item.n); +} diff --git a/tslang/test/tester/own/own_swap_local_field.ts b/tslang/test/tester/own/own_swap_local_field.ts new file mode 100644 index 000000000..e919667c3 --- /dev/null +++ b/tslang/test/tester/own/own_swap_local_field.ts @@ -0,0 +1,85 @@ +// `[data, this.data] = [this.data, data]`, an exchange of a local and a field or an element (spec +// 77): the field is given the local's value and the local the field's, so a value is taken out of a +// place the way it is under every other model - for a string, a class instance, a `T | undefined` of +// either (and `data` of what came out), an element. Each case churns between steps with blocks +// the size of the ones taken, so a block freed by mistake is reused and read as garbage. +class Item { + v: number[] = []; + constructor(public n: number) {} +} + +function churn() { + const junk: Item[] = []; + for (let i = 0; i < 64; i++) { + const c = new Item(999); + c.v.push(99); + junk.push(c); + } +} + +// a slot a value is put into and later taken back out of +class Slot { + constructor(public data: T | undefined) {} + + take(): T { + let data: T | undefined = undefined; + [data, this.data] = [this.data, data]; + return data; + } + + put(value: T) { + let data: T | undefined = value; + [data, this.data] = [this.data, data]; + } +} + +// a field that always holds one: the local gives the field its own +class Holder { + constructor(public item: Item) {} + + exchange(): Item { + let item = new Item(0); + [item, this.item] = [this.item, item]; + return item; + } +} + +function takeElement(items: Item[], index: int): Item { + let item = new Item(-1); + [item, items[index]] = [items[index], item]; + return item; +} + +function main() { + const text = new Slot("a"); + churn(); + assert(text.take() == "a", "string taken"); + assert(text.data === undefined, "string slot empty"); + + const slot = new Slot(new Item(1)); + churn(); + const taken = slot.take(); + churn(); + assert(taken.n == 1, "item taken"); + assert(slot.data === undefined, "item slot empty"); + slot.put(new Item(2)); + churn(); + assert(slot.take().n == 2, "item put back and taken"); + + const holder = new Holder(new Item(3)); + churn(); + const old = holder.exchange(); + churn(); + assert(old.n == 3, "old item out"); + assert(holder.item.n == 0, "new item in"); + + const items = [new Item(4), new Item(5)]; + churn(); + const out = takeElement(items, 1); + churn(); + assert(out.n == 5, "element taken"); + assert(items[1].n == -1, "element replaced"); + assert(items[0].n == 4, "other element kept"); + + print("done."); +} From 8a7709f4404485dfb8df39a7eaecd13edb37a062 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 9 Nov 2026 18:36:15 +0000 Subject: [PATCH 3/5] own tests: back-reference test without a handle; line of the captures error Co-Authored-By: Claude Opus 5.5 --- tslang/test/tester/CMakeLists.txt | 2 +- tslang/test/tester/own/own_closure_keeps_param.ts | 7 +++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 5f3349868..ace130848 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5213,7 +5213,7 @@ set(own_error_cases "own_err_let_field_captured|:18:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_back_reference_taken|:10:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_back_reference_stored|:15:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" - "own_err_back_reference_captures|:12:20: error: a closure that escapes owns what it captures, but -mm=own cannot move 'this' into it: its value is the caller's" + "own_err_back_reference_captures|:13:20: error: a closure that escapes owns what it captures, but -mm=own cannot move 'this' into it: its value is the caller's" "own_err_closure_kept_param_used|:19:11: error: '[^']*' is used here after its value was moved") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) diff --git a/tslang/test/tester/own/own_closure_keeps_param.ts b/tslang/test/tester/own/own_closure_keeps_param.ts index 50ad8072a..9f328be41 100644 --- a/tslang/test/tester/own/own_closure_keeps_param.ts +++ b/tslang/test/tester/own/own_closure_keeps_param.ts @@ -98,12 +98,11 @@ function main() { }; }) == 2, "back-reference from an arrow capturing nothing"); - // ...and one that captures a number and a handle + // ...and one that captures a variable of its own let seen = 0; - const shared = new Shared(new Item(3)); + const step = new Item(3); assert(run((self: Scope) => { - const counter = shared; - seen += counter.value.n; + seen += step.n; self.handler = () => { self.count++; }; From c28d34e64bca08bef45c9129120a8bc9868551a7 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 9 Nov 2026 19:12:27 +0000 Subject: [PATCH 4/5] -mm=own: a method whose result type is `this` gives a temporary receiver back to the caller (item 39) A method that returns `this` on every path has the fact __own_result_itself beside its result borrow: the signature pass infers it from a body, and a method whose result type is `this` says it (implying `@lends("this")`, which a function only this module calls drops again). Under own a `: this` body that returns another object is an error. The -shared declaration printer writes `: this` for such a method. After the facts settle, a call with the fact whose receiver is a temporary the caller owns (fresh, or a call result that borrows nothing) and uses no more but to release it loses those releases, and its result is fresh: a chain from a new value can be returned or kept (spec 78). Also specs 75-78 and the guide (closures kept, exchanging a local with a place, methods returning `this`). Co-Authored-By: Claude Opus 5.5 --- docs/own-memory-model.md | 64 ++++++- .../2026-09-24-own-memory-model-design.md | 68 ++++++++ tslang/include/TypeScript/Defines.h | 9 + .../MLIRLogic/MLIRDeclarationPrinter.h | 2 +- .../TypeScript/MLIRLogic/MLIRGenStore.h | 2 + tslang/lib/TypeScript/DeclarationPrinter.cpp | 12 +- tslang/lib/TypeScript/LowerToLLVM.cpp | 4 +- tslang/lib/TypeScript/MLIRGenFunctions.cpp | 4 +- tslang/lib/TypeScript/MLIRGenImpl.h | 24 +++ tslang/lib/TypeScript/OwnershipFacts.h | 4 + .../lib/TypeScript/OwnershipSignaturePass.cpp | 157 +++++++++++++++++- .../lib/TypeScript/OwnershipSignaturePass.h | 16 +- tslang/test/tester/CMakeLists.txt | 7 +- .../test/tester/own/own_chain_returns_this.ts | 88 ++++++++++ .../tester/own/own_err_this_result_other.ts | 16 ++ 15 files changed, 461 insertions(+), 16 deletions(-) create mode 100644 tslang/test/tester/own/own_chain_returns_this.ts create mode 100644 tslang/test/tester/own/own_err_this_result_other.ts diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index 3a1aaf834..2794c1b15 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -219,6 +219,30 @@ function main() { 6 2 ``` +A closure kept - stored into a field, a global or an array, or given to a function that keeps it - +owns the parameters it captures, so the function keeps them and its callers give them up, as for a +parameter stored into a field. A closure stored into a field of the object it captures is a +back-reference instead: it borrows that object. + +```typescript +class Holder { + run: () => number; + + constructor(body: (n: number) => number) { + this.run = () => body(2); // the closure is kept, and owns body + } +} + +function main() { + const h = new Holder((n: number) => n * 21); + print(h.run()); +} +``` + +```text +42 +``` + A closure kept for good, in an array that is only ever pushed onto, is covered by [`@immortalizes`](#immortalizes). @@ -441,6 +465,40 @@ function main() { `@lends` with one name is a plain borrow. With several, the result is a record that borrows each of them, and it needs [`@record`](#record). +### A method that returns `this` + +A method whose result type is `this` returns the object it is called on, so calls chain. It lends +`this` without saying `@lends("this")`, and the compiler checks that the body returns `this` on every +path (one that returns another object of the type is an error under own). Called on an object the +caller owns no more after the call - a new one - the result is that object, the caller's to keep: +a chain from a new value can be returned, stored or given to a function that keeps it. A method of +a class only this module uses may say the class instead of `this`; its body shows the same. + +```typescript +export class Bag { + items: number[] = []; + + add(n: number): this { + this.items.push(n); + return this; + } +} + +function filled(): Bag { + return new Bag().add(1).add(2); // the new Bag, given back +} + +function main() { + const b = filled(); + b.add(3); // on b: a borrow of it, used in place + print(b.items.length); +} +``` + +```text +3 +``` + ### `@record` `@record`, always beside `@lends`: the result is a *borrowing record* - a new object the caller @@ -744,8 +802,10 @@ a reference gives it back on every path out of a function. or build the result from copies. - `reverse` and `sort` work on arrays of numbers, strings and class instances. They exchange elements with `[a[i], a[j]] = [a[j], a[i]]`, which moves nothing; swap two elements or two fields - the same way in your own code. A swap through a local (`let t = a[i]; a[i] = a[j]; a[j] = t`) - gives an object in `t` a second owner, which is an error. A callback your function only calls, + the same way in your own code. To take a value out of a place, exchange it with a local: + `let v: T | undefined = undefined; [v, this.f] = [this.f, v]` leaves the place holding what the + local held and the local owning what the place held. A swap through a local (`let t = a[i]; + a[i] = a[j]; a[j] = t`) gives an object in `t` a second owner, which is an error. A callback your function only calls, tests (`compare && compare(a, b)`), hands on to another function (as `sort` hands its comparison to a helper), names again (`const g = f`) or captures in a closure that calls it (`a.forEach((v) => f(v))`, also kept in a local) is known by the functions its callers pass. So is one stored in 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 9df4149e8..0e4d02a15 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 @@ -5641,3 +5641,71 @@ which needs no `--di`. MLIRGen records where a closure first uses each capture (`PassResult::outerVariableUses`) and puts it on the closure (`__capture_uses`, under own only); the errors about a capture point there. The fill and its retain keep the arrow's location, so debug info never holds a location from another function's scope. + +## 75. A back-reference from an arrow that captures, 2026-11-09 + +An arrow given an object stores a closure over that object into one of its fields (spec 70's +back-reference: the field owns the closure, the box borrows the object). The rule asked for the +member's `this`, the function's first parameter of a class type. A closure body takes its box first +(a reference to the tuple of what it captures), so once the outer arrow captured anything its object +parameter was second and the inner closure was taken for one that owns a parameter it cannot +(TSLANG_ISSUES 40). `isMemberThis` now skips a first argument that is a reference to a tuple: the +outer arrow's own captures do not change whose its parameter is. + +## 76. A closure kept owns the parameters it captures, 2026-11-09 + +An escaping closure owns what it captures; a parameter's value is the caller's, so a closure that +captured one was refused (spec 16) unless it was a back-reference. When the closure itself is kept +- stored into a field, a global or an array, or given to a call that keeps it (`keeps`, through views) - +and is no back-reference, the function keeps each parameter its box holds, captured by copy or in a +cell (`keepsClosure`, `localOwnedParams`): its callers move the argument in, as they do for one stored +into a field, and `@keeps` may say so (TSLANG_ISSUES 41). The cell then moves into the box as a kept +parameter's does (decideEscaping). Not the member's `this`, which the object the closure goes into +would own. A closure returned still cannot capture a parameter: its result would be a fact (a result +that owns a parameter) callers have no way to be told. + +The error for a capture that still cannot move names it, from the box's field (`'this'`, `'c'`). + +## 77. A local exchanged with a place, 2026-11-09 + +`[data, this.data] = [this.data, data]` was built through an array literal: the field's value, read +out of it, was a borrow stored into the array (TSLANG_ISSUES 42). MLIRGen now writes an exchange of a +local that owns what it holds and a field or an element of the same type as two reads, both counted, +then the place given the local's value and the local given the place's, each store releasing what +its storage held (`mlirGenSwapWithLocal`), under every model. The place goes first: rc's counts stay +whole, and own sees the place's release, right before the store that refills it, as the hand-over of +the value read to the local: `refilledFieldTakeOf` takes a read whose one taker comes after the +refill, with nothing but reads, counts and stores of locals between (no call, no release of the +object's local), erases rc's retain and the refill's release, and the read is the local's. A string +is copied instead (spec 22). The local's old value moves into the place as any `let` moves into a +field, and the local's assignment after it is a kill (spec 24). + +`data` of a `T | undefined` with T a class was `HasValue ? Value : null`, a merge own could not +follow. It is now one `ts.ValueOrDefault` (marked as an explicit cast, so it does not warn), which is a +view: the optional's object or none. + +## 78. A method that returns its receiver, 2026-11-09 + +A method that returns `this` so calls chain (`set(k, v).set(k2, v2)`) has a result that borrows its +receiver. Called on a temporary (`JsonValue.newObject().set(...)`), that borrow had no owner but the +temporary, released at the end of the statement, so the chain could not be returned or kept +(TSLANG_ISSUES 39). `@lends("this")` cannot mean more: `at()` and `get()` lend an element. + +**The fact.** `__own_result_itself`, beside `__own_result_borrows` naming one argument: the result is +that argument itself on every path - each returned value is the parameter or a read of its unassigned +slot, through views, never `null` (`isParameterItself`). The signature pass infers it from a body, so +a method typed with its class that returns `this` has it; families must agree on it as on the rest. + +**Saying it.** A method whose result type is `this` says it: MLIRGen marks it +(`ts.own_declared_returns_this`) and implies `@lends("this")` (`ts.own_implied_lends`). A function only +this module calls drops the implied `@lends` (its callers go by its body; a declared one would want +every other fact declared too). A body is held to it: one that returns another object of the type +(`clone(): this { return new A() }`, valid TypeScript) is an error under own. A declaration +(`lib.d.ts`) has no body, so its `: this` is what callers know, and the `-shared` declaration printer +writes `: this` for such a method. There is no decorator: `: this` is the one way. + +**The call.** After the facts settle (`transferTemporaryReceivers`, in program order so a chain's next +call sees the one before it): a call with the fact whose argument is fresh, that the callee does not +keep, and that nothing uses after the call but its releases in the same block, loses those releases, +and its result is `__own_fresh_result` - the temporary, now the result's to release. On an object +someone owns the result stays a borrow, bounded by it. diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 6c8367545..973721945 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -380,6 +380,15 @@ // that returns such a record has to say it. A unit attribute on the FuncOp. #define RECORD_DECORATOR "record" #define OWN_DECLARED_RECORD_ATTR_NAME "ts.own_declared_record" +// A method whose result type is `this`: it returns the object it is called on, on every path, not +// another of its type nor a borrow of something in it. Called on a value the caller owns no more +// after the call - a temporary - the result is that value, the caller's to own (own spec 78). A unit +// attribute on the FuncOp, set by MLIRGen beside OWN_DECLARED_LENDS_ATTR_NAME naming `this`. +#define OWN_DECLARED_RETURNS_THIS_ATTR_NAME "ts.own_declared_returns_this" +// Beside OWN_DECLARED_LENDS_ATTR_NAME: no `@lends` said it, the result type `this` did. For a function +// no other module calls, -mm=own goes by its body and drops it (a declared `@lends` would want every +// other fact declared too). +#define OWN_IMPLIED_LENDS_ATTR_NAME "ts.own_implied_lends" // `@copies`: inside this function -mm=own may copy an array whose elements own nothing where it cannot // prove one owner (own spec 71), as it copies a string anywhere. A copy of an array can be told from // the array - a change to one is not a change to the other - so only a function that says so makes diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h b/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h index 20951056b..af767cc3c 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h @@ -44,7 +44,7 @@ namespace typescript void printOwnMarkers(ArrayRef, ArrayRef, ArrayRef, bool, bool, unsigned, ArrayRef = {}); void printFunction(StringRef, ArrayRef, mlir::Type); - void printMethod(bool, StringRef, ArrayRef, mlir::Type, mlir::Type); + void printMethod(bool, StringRef, ArrayRef, mlir::Type, mlir::Type, bool = false); void printAccessor(bool, StringRef, StringRef, mlir_ts::AccessLevel, ArrayRef, mlir::Type, mlir::Type, StringRef); void printIndexer(mlir::Type, mlir::Type); void printNamespaceBegin(NamespaceInfo::TypePtr); diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 149fc35a9..d77e89294 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -177,6 +177,8 @@ struct MethodInfo uint64_t ownLendsMask = 0; // `@record` (OWN_DECLARED_RECORD_ATTR_NAME): what `@lends` names, the result is a record of bool ownRecord = false; + // the result is `this`, the object itself (OWN_DECLARED_RETURNS_THIS_ATTR_NAME, own spec 78) + bool ownReturnsThis = false; // `@immortalizes` (OWN_DECLARED_IMMORTALIZES_ATTR_NAME), as a mask like `@lends`'s, of 32 bits uint32_t ownImmortalizesMask = 0; }; diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index 0b4353655..af2633b5c 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -286,7 +286,8 @@ namespace typescript } } - void MLIRDeclarationPrinter::printMethod(bool isStatic, StringRef name, ArrayRef params, mlir::Type returnType, mlir::Type thisType) + void MLIRDeclarationPrinter::printMethod(bool isStatic, StringRef name, ArrayRef params, mlir::Type returnType, mlir::Type thisType, + bool returnsThis) { if (isStatic) { @@ -297,7 +298,12 @@ namespace typescript printParams(params, thisType); - if (returnType) + // `: this` - the object the method is called on (own spec 78), which the class would not say + if (returnType && returnsThis && !isStatic) + { + os << " : this"; + } + else if (returnType) { os << " : "; print(returnType); @@ -798,7 +804,7 @@ namespace typescript StringRef(method.name).split(CPP_OVERLOAD_SEPARATOR).first, funcType.getParams(), funcType.getNumResults() > 0 ? funcType.getResult(0) : mlir::Type(), - thisTypeOf(method.isStatic, funcType.getParams())); + thisTypeOf(method.isStatic, funcType.getParams()), method.ownReturnsThis); newline(); } diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 987e0c6b6..826f1c547 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -2403,7 +2403,9 @@ struct FuncOpLowering : public TsLlvmPattern // read by -mm=own only if (name == OWN_DECLARED_NO_DROPS_ATTR_NAME || name == OWN_DECLARED_KEEPS_ATTR_NAME || name == OWN_DECLARED_BORROWS_ATTR_NAME || name == OWN_DECLARED_LENDS_ATTR_NAME || - name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME || + name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_RETURNS_THIS_ATTR_NAME || + name == OWN_IMPLIED_LENDS_ATTR_NAME || + name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME || name == OWN_DECLARED_IMMORTALIZES_ATTR_NAME || name == OWN_DECLARED_COPIES_ATTR_NAME || name == OWN_CANNOT_SHARE_ATTR_NAME) { continue; diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 8ac6ee5a2..3206835e5 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1450,8 +1450,8 @@ namespace mlirgen if (auto globalOp = theModule.lookupSymbol(globalName)) { for (auto *name : {OWN_DECLARED_KEEPS_ATTR_NAME, OWN_DECLARED_BORROWS_ATTR_NAME, OWN_DECLARED_LENDS_ATTR_NAME, - OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_IMMORTALIZES_ATTR_NAME, - OWN_DECLARED_PARAM_NAMES_ATTR_NAME}) + OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_RETURNS_THIS_ATTR_NAME, OWN_IMPLIED_LENDS_ATTR_NAME, + OWN_DECLARED_IMMORTALIZES_ATTR_NAME, OWN_DECLARED_PARAM_NAMES_ATTR_NAME}) { if (auto attr = declared->getAttr(name)) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index bc487749a..4154574e7 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3759,6 +3759,29 @@ class MLIRGenImpl } }); + // A method whose result type is `this` returns the object it is called on, as it is: it lends + // its `this` (`@lends("this")` without saying so), and -mm=own holds a body to it (own spec 78). + auto hasAttr = [&](StringRef name) { + return llvm::any_of(attrs, [&](mlir::NamedAttribute &attr) { return attr.getName() == name; }); + }; + auto returnsThisType = functionLikeDeclarationBaseAST->type && functionLikeDeclarationBaseAST->type == SyntaxKind::ThisType; + // (a method's `this` is its first parameter, by that name: `@lends("this")` finds it so) + auto isMethod = funcType && !funcType.getInputs().empty() && mlir::isa(funcType.getInputs().front()) && + (funcType.getInputs().size() == params.size() + 1 || (!params.empty() && params.front()->getName() == "this")); + if (mlir::succeeded(result) && returnsThisType && isMethod) + { + if (!hasAttr(OWN_DECLARED_LENDS_ATTR_NAME)) + { + attrs.push_back({builder.getStringAttr(OWN_DECLARED_LENDS_ATTR_NAME), builder.getDenseI32ArrayAttr({0})}); + attrs.push_back({builder.getStringAttr(OWN_IMPLIED_LENDS_ATTR_NAME), builder.getUnitAttr()}); + } + + if (!hasAttr(OWN_DECLARED_RETURNS_THIS_ATTR_NAME)) + { + attrs.push_back({builder.getStringAttr(OWN_DECLARED_RETURNS_THIS_ATTR_NAME), builder.getUnitAttr()}); + } + } + return result; } @@ -14514,6 +14537,7 @@ class MLIRGenImpl } methodInfo.ownRecord = funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME); + methodInfo.ownReturnsThis = funcOp->hasAttr(OWN_DECLARED_RETURNS_THIS_ATTR_NAME); methodInfo.ownImmortalizesMask = 0; if (auto immortalizes = funcOp->getAttrOfType(OWN_DECLARED_IMMORTALIZES_ATTR_NAME)) diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index b55918b61..d5953fede 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -50,6 +50,10 @@ namespace mlir_ts = mlir::typescript; // nothing it gets back; the record is bounded by the arguments named as a boxed one is, and its // releases, and those of the locals that hold it, give nothing back (spec 36). #define OWN_RESULT_RECORD_UNBOXED_ATTR_NAME "__own_result_record_unboxed" +// Beside OWN_RESULT_BORROWS_ATTR_NAME naming one argument: the result is that argument itself, on +// 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" // 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" diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 07e891d89..38977b138 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -67,7 +67,8 @@ namespace own_signature // what the declaration says of its parameters described the body that is gone: nothing // calls the stub, so nothing needs it for (auto *name : {OWN_DECLARED_KEEPS_ATTR_NAME, OWN_DECLARED_BORROWS_ATTR_NAME, OWN_DECLARED_LENDS_ATTR_NAME, - OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_IMMORTALIZES_ATTR_NAME}) + OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_RETURNS_THIS_ATTR_NAME, + OWN_IMPLIED_LENDS_ATTR_NAME, OWN_DECLARED_IMMORTALIZES_ATTR_NAME}) { funcOp->removeAttr(name); } @@ -183,6 +184,15 @@ namespace own_signature }); findOpen(module); + // the `@lends("this")` a result type `this` implies, on a function only this module calls: its + // callers go by its body, as for any other function here (spec 78) + for (auto &entry : functions) + { + if (entry.second->hasAttr(OWN_IMPLIED_LENDS_ATTR_NAME) && !entry.second.isDeclaration() && !open.contains(entry.second)) + { + entry.second->removeAttr(OWN_DECLARED_LENDS_ATTR_NAME); + } + } // before the facts: a value kept for good is immortal, which keeps nothing of its owner findKeepers(module); decideKeptForGood(module); @@ -196,6 +206,7 @@ namespace own_signature findYieldedFields(module); findImportedStates(module); checkDeclared(); + transferTemporaryReceivers(); for (auto &call : calls) { @@ -574,6 +585,34 @@ namespace own_signature continue; } + // a method whose result type is `this` (spec 78): it lends its `this` alone, and a body here + // returns that object, as it is, on every path + if (funcOp->hasAttr(OWN_DECLARED_RETURNS_THIS_ATTR_NAME)) + { + auto inputs = funcOp.getFunctionType().getInputs(); + auto lends = declaredLends(funcOp); + // (no `@lends` left: the one the result type implied, dropped for a function only this module calls) + if ((!lends.empty() && (lends.size() != 1 || lends.front() != 0)) || inputs.empty() || + !mlir::isa(inputs.front()) || + funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME)) + { + funcOp.emitError("'") << funcOp.getSymName() + << "' returns 'this', so it lends 'this' alone: '@" LENDS_DECORATOR + "' cannot name another parameter, nor '@" RECORD_DECORATOR "' be said"; + signalPassFailure(); + continue; + } + + if (!funcOp.isDeclaration() && !factsLocal.lookup(funcOp).itself) + { + funcOp.emitError("'") << funcOp.getSymName() + << "' has the result type 'this', but its body returns something else than the " + "object it is called on, on some path; -mm=own takes 'this' for that object"; + signalPassFailure(); + continue; + } + } + if (declaresCallerFacts(funcOp)) { auto local = factsLocal.lookup(funcOp); @@ -700,7 +739,7 @@ namespace own_signature } for (auto *name : {OWN_DECLARED_KEEPS_ATTR_NAME, OWN_DECLARED_BORROWS_ATTR_NAME, OWN_DECLARED_LENDS_ATTR_NAME, - OWN_DECLARED_RECORD_ATTR_NAME}) + OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_RETURNS_THIS_ATTR_NAME}) { if (funcOp->hasAttr(name) != declaring->hasAttr(name) || declared(funcOp, name) != declared(declaring, name)) { @@ -810,12 +849,110 @@ namespace own_signature if (found >= 0) { - return {{found}, false}; + ResultBorrows result{{found}, false}; + auto returned = returnedValues(funcOp); + result.itself = !returned.empty() && llvm::all_of(returned, [&](mlir::Value value) { return isParameterItself(value, found); }); + return result; } return {}; } + void OwnershipSignaturePass::transferTemporaryReceivers() + { + // in the order of the program, so a chain's next call sees the one before it fresh; the + // releases go once every call is decided (a walk must not erase what it has yet to visit) + llvm::SmallVector candidates; + getOperation().walk([&](mlir::Operation *op) { + if (op->hasAttr(OWN_RESULT_ITSELF_ATTR_NAME) && op->getNumResults() == 1 && resultBorrowsAll(op).size() == 1) + { + candidates.push_back(op); + } + }); + + llvm::SetVector erased; + for (auto *op : candidates) + { + // a temporary: made fresh, not kept by the callee, given to nothing after the call but + // its releases + auto args = callArgs(op); + auto index = resultBorrowsAll(op).front(); + if (index < 0 || static_cast(index) >= args.size() || llvm::is_contained(ownedParams(op), index)) + { + continue; + } + + // a method called through the object's vtable or by its symbol: the object it is bound to + auto receiver = args[index]; + if (auto object = boundThis(receiver); object && mlir::isa(object.getType())) + { + receiver = object; + } + + // the caller's own: fresh, or what a call that borrows nothing returns (another module's + // `JsonValue.newObject()`), which the caller releases + auto *producer = receiver.getDefiningOp(); + auto owned = isFresh(receiver) || + (producer && isCall(producer) && resultBorrowsAll(producer).empty() && !isRecordResult(producer)); + if (!owned) + { + continue; + } + + llvm::SmallVector releases; + auto temporary = llvm::all_of(receiver.getUsers(), [&](mlir::Operation *user) { + if (user == op) + { + return true; + } + + if (mlir::isa(user) && user->getBlock() == op->getBlock() && op->isBeforeInBlock(user)) + { + releases.push_back(user); + return true; + } + + // a use before the call, whose own uses are before it too or the call itself (rc's + // header of a new object, the method bound to it) + std::function before = [&](mlir::Operation *other, int depth) { + return depth < 4 && other->getBlock() == op->getBlock() && other->isBeforeInBlock(op) && + llvm::all_of(other->getUsers(), [&](mlir::Operation *use) { return use == op || before(use, depth + 1); }); + }; + return before(user, 0); + }); + if (!temporary) + { + continue; + } + + // the result is the temporary itself: its releases are the result's to make + erased.insert(releases.begin(), releases.end()); + op->removeAttr(OWN_RESULT_BORROWS_ATTR_NAME); + op->removeAttr(OWN_RESULT_ITSELF_ATTR_NAME); + op->setAttr(OWN_FRESH_RESULT_ATTR_NAME, mlir::UnitAttr::get(op->getContext())); + } + + for (auto *release : erased) + { + release->erase(); + } + } + + bool OwnershipSignaturePass::isParameterItself(mlir::Value value, int32_t index) + { + auto root = rootOf(value); + if (auto argument = mlir::dyn_cast(root)) + { + return argument.getOwner()->isEntryBlock() && mlir::isa(argument.getOwner()->getParentOp()) && + static_cast(argument.getArgNumber()) == index; + } + + auto loadOp = root.getDefiningOp(); + auto varOp = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + auto position = -1; + return varOp && isParameterSlot(varOp, position) && position == index; + } + int32_t OwnershipSignaturePass::mixedReturnParam(mlir_ts::FuncOp funcOp) { auto param = -1; @@ -1159,6 +1296,7 @@ namespace own_signature facts.borrows = std::move(result.borrows); facts.record = result.record; facts.unboxed = result.unboxed; + facts.itself = result.itself; 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) @@ -1191,6 +1329,8 @@ namespace own_signature lends.erase(std::unique(lends.begin(), lends.end()), lends.end()); facts.borrows = lends; facts.record = calleesDeclare(call.callees, OWN_DECLARED_RECORD_ATTR_NAME); + facts.itself = lends.size() == 1 && !facts.record && + calleesDeclare(call.callees, OWN_DECLARED_RETURNS_THIS_ATTR_NAME); } } @@ -1243,6 +1383,11 @@ namespace own_signature (entry.second.isDeclaration() ? entry.second->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME) : local.record && local.borrows == said.borrows); said.unboxed = said.record && !entry.second.isDeclaration() && local.unboxed; + // the result is the object itself: a declaration's result type `this` says so, a body + // here shows it (checkDeclared holds a body to its `: this`) + 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); if (factsThroughInterface(entry.second, said)) { continue; @@ -1349,10 +1494,16 @@ namespace own_signature op->removeAttr(OWN_RESULT_BORROWS_ATTR_NAME); 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_PARAMS_ATTR_NAME); if (!facts.borrows.empty()) { op->setAttr(OWN_RESULT_BORROWS_ATTR_NAME, mlir::DenseI32ArrayAttr::get(context, facts.borrows)); + if (facts.itself && facts.borrows.size() == 1 && !facts.record) + { + op->setAttr(OWN_RESULT_ITSELF_ATTR_NAME, mlir::UnitAttr::get(context)); + } + if (facts.record) { op->setAttr(OWN_RESULT_RECORD_ATTR_NAME, mlir::UnitAttr::get(context)); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 0df4673af..2be51893f 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -450,6 +450,8 @@ class OwnershipSignaturePass : public mlir::PassWrapper borrows; bool record = false; bool unboxed = false; + // every value returned is the parameter it borrows, read as it is (spec 78) + bool itself = false; }; + // Is `value` parameter `index` itself: the argument, or a read of its slot, seen through views? + static bool isParameterItself(mlir::Value value, int32_t index); + + // A call whose result is its argument itself (OWN_RESULT_ITSELF_ATTR_NAME), given a temporary + // the caller owns and uses no more after the call but to release it: the result is the + // temporary, the caller's own. The temporary's releases go, and the call's result is fresh + // (spec 78): `JsonValue.newObject().set(...).set(...)` returned or kept. + void transferTemporaryReceivers(); + // What the function's result borrows (spec 2.4, 32): the one parameter every heap value it returns // is a borrow of, or, when every such value is a borrowing record, the parameters the records // borrow. A result that holds no block (`null`, a number) agrees with any; a record on one path diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index ace130848..1309bba43 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4405,7 +4405,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_generic_specializations own_callback_cast own_callback_interface_slot own_equal_strings_into_any own_any_copies own_array_copies own_string_pushed_twice own_rest_takes own_shares_elements own_rest_keeps_declared own_interface_getter_let own_callback_assigns_capture - own_param_capture_copies own_swap_local_field own_closure_keeps_param) + own_param_capture_copies own_swap_local_field own_closure_keeps_param own_chain_returns_this) 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. @@ -4445,7 +4445,7 @@ foreach(keeps_mm rc gc none) own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot own_equal_strings_into_any own_rest_keeps_declared own_interface_getter_let own_callback_assigns_capture - own_param_capture_copies own_swap_local_field own_closure_keeps_param) + own_param_capture_copies own_swap_local_field own_closure_keeps_param own_chain_returns_this) tslang_add_test(NAME test-jit-${keeps_mm}-${keeps_test} COMMAND test-runner -jit -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts") tslang_add_test(NAME test-compile-${keeps_mm}-${keeps_test} COMMAND test-runner -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts") endforeach() @@ -5214,7 +5214,8 @@ set(own_error_cases "own_err_back_reference_taken|:10:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_back_reference_stored|:15:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_back_reference_captures|:13:20: error: a closure that escapes owns what it captures, but -mm=own cannot move 'this' into it: its value is the caller's" - "own_err_closure_kept_param_used|:19:11: error: '[^']*' is used here after its value was moved") + "own_err_closure_kept_param_used|:19:11: error: '[^']*' is used here after its value was moved" + "own_err_this_result_other|:7:5: error: 'A.copy' has the result type 'this', but its body returns something else than the object it is called on") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_chain_returns_this.ts b/tslang/test/tester/own/own_chain_returns_this.ts new file mode 100644 index 000000000..5654b10ff --- /dev/null +++ b/tslang/test/tester/own/own_chain_returns_this.ts @@ -0,0 +1,88 @@ +// A method that returns the object it is called on - `return this` on every path, its result type +// `this` or the class - called on a temporary gives that object back to the caller, who owns it +// (spec 78): a chain from a new value can be returned, kept in a field or an array, or given to a +// parameter that keeps it, as under every other model. On an object someone owns, the result stays +// a borrow of it. Each step churns, so anything freed too early reads garbage; every model runs it. +class Junk { + v: number[] = []; + constructor(public n: number) {} +} + +function churn() { + const junk: Junk[] = []; + for (let i = 0; i < 64; i++) { + const j = new Junk(999); + j.v.push(99); + junk.push(j); + } +} + +class Node { + items: Node[] = []; + constructor(public n: number) {} + + static make(n: number): Node { + return new Node(n); + } + + // the result type is the class: the body shows the result is `this` + add(child: Node): Node { + this.items.push(child); + return this; + } + + // the result type `this` says so + with(n: number): this { + this.items.push(new Node(n)); + return this; + } + + total(): number { + let t = this.n; + for (const c of this.items) t += c.total(); + return t; + } +} + +class Holder { + node: Node; + constructor() { + this.node = Node.make(0); + } +} + +function tree(): Node { + return Node.make(1).add(Node.make(2)).with(3); +} + +function main() { + const a = Node.make(10).add(Node.make(1)); + churn(); + assert(a.total() == 11, "kept in a local"); + + const t = tree(); + churn(); + assert(t.total() == 6, "returned"); + + const b = Node.make(100); + b.add(Node.make(1).add(Node.make(2)).with(3)); + churn(); + assert(b.total() == 106, "given to a parameter that keeps it"); + + // on an object someone owns: a borrow of it, used in place + b.with(4).with(5); + churn(); + assert(b.total() == 115, "chained on an owned object"); + + const h = new Holder(); + h.node = Node.make(7).with(1); + churn(); + assert(h.node.total() == 8, "stored into a field"); + + const list: Node[] = []; + list.push(new Node(20).with(2)); + churn(); + assert(list[0].total() == 22, "pushed into an array"); + + print("done."); +} diff --git a/tslang/test/tester/own/own_err_this_result_other.ts b/tslang/test/tester/own/own_err_this_result_other.ts new file mode 100644 index 000000000..cd3047a51 --- /dev/null +++ b/tslang/test/tester/own/own_err_this_result_other.ts @@ -0,0 +1,16 @@ +// A method whose result type is `this` returns the object it is called on, under -mm=own (spec 78): +// one that returns another object of its type is an error, as callers would take the result for +// the object they called it on. +class A { + n = 1; + + copy(): this { + const c = new A(); + c.n = this.n; + return c; + } +} + +function main() { + print(new A().copy().n); +} From 686e229814ebcc611f75d6a3a4f1aa331ded63b3 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Mon, 9 Nov 2026 19:12:40 +0000 Subject: [PATCH 5/5] TSLANG_ISSUES: items 39-42 fixed Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 246 ++++------------------------------------------- 1 file changed, 18 insertions(+), 228 deletions(-) diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 86c71ec43..6e1b72555 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -77,231 +77,21 @@ Regression tests `tslang/test/tester/tests/00tslang_issue_37.ts`, `00tslang_issu Still open from 38: a symbol made at run time can't be a property key (`obj[sym]`). Fields are laid out at compile time, so a symbol needs a run-time value and a way to look a key up. It has not been tried. -### `-mm=own` limits found in the default library, 2026-11-09 (items 39-42) - -Found while adding `Worker` and making `JSON.stringify` work under `-mm=own` in the default library -(TypeScriptCompilerDefaultLib PRs #80-#85). The library works around each one, and its README names -them as `-mm=own` limits; each needs a compiler change to go away. Every repro below is a complete -file, run with `tslang --nowarn -mm=own --emit=jit file.ts` and again with `-mm=gc`, on Windows x64, -tslang commit 2fffc119 (release build of 2026-11-09 17:35), against the default library at -TypeScriptCompilerDefaultLib 916cd07. Each compiles and runs under `-mm=gc`, with the output given. - -#### 39. A method can't say it gives its receiver back owned, so a chain from a new value can't be returned or kept by a callee - -A method that returns `this` so calls can be chained (`JsonValue.set`, `JsonValue.push`) can only be -declared `@lends("this")` for another module: its result borrows the value it was called on. A chain -that starts from a new value (`JsonValue.newObject().set(...)`) has no owner but that borrow. Kept in a -local it compiles now; returned, or given to a parameter that is kept, it is an error. - -```typescript -// JsonValue is in the default library, another module: its set() and push() are declared -// @lends("this") (they return `this`, so a chain can go on), and that is all a caller knows of them. - -// returning a chain from a new value: under -mm=own "'this value' borrows the result of -// 'JsonValue.set' and cannot be stored, returned or captured" -function person(): JsonValue { - return JsonValue.newObject().set("name", JsonValue.ofString("Ann")).set("age", JsonValue.ofNumber(30)); -} - -function main() { - // compiles under -mm=own: a chain kept in a local - const a = JsonValue.newObject().set("a", JsonValue.ofNumber(1)); - print(a.stringify()); - - print(person().stringify()); - - // a chain given to a parameter that is kept (set's `value`): the same error - const b = JsonValue.newObject(); - b.set("list", JsonValue.newArray().push(JsonValue.ofNumber(1)).push(JsonValue.ofNumber(2))); - print(b.stringify()); -} -``` - -`-mm=own`: - -```text -39_chain_receiver.ts:7:5: error: 'this value' borrows the result of 'JsonValue.set' and cannot be stored, returned or captured - return JsonValue.newObject().set("name", JsonValue.ofString("Ann")).set("age", JsonValue.ofNumber(30)); - ^ -39_chain_receiver.ts:19:5: error: 'this value' borrows the result of 'JsonValue.push' and cannot be stored, returned or captured - b.set("list", JsonValue.newArray().push(JsonValue.ofNumber(1)).push(JsonValue.ofNumber(2))); - ^ -``` - -`-mm=gc`: `{"a":1}`, `{"name":"Ann","age":30}`, `{"list":[1,2]}`. - -To do: a way to declare that a method returns its receiver (`return this` on every path), so that -called on a value the caller owns, or on a temporary, the result is that value, owned by whoever owned -the receiver, rather than a borrow of it. Something like `@returnsThis` / `@lends("this")` that a -temporary receiver turns into a move. Then the default library's `tests/json.ts` can drop its -`__MEMORY_MODEL__ != "own"` branch (`chained()`), and `toJSON()` can return a chain. - -#### 40. Once an arrow captures anything, an arrow inside it can't capture the outer arrow's parameter - -An arrow given a parameter (`self`) stores a second arrow that captures `self`. That compiles under -`-mm=own`, until the outer arrow also captures something from its own enclosing function. Then the -inner arrow's capture of `self` is refused. It is the shape of the default library's `Worker`: -`new Worker((self) => { self.onmessage = (e) => self.postMessage(...); })`. A worker whose function -uses state shared with the creating thread can't also post from its handler (the library's README and -`docs/worker-design.md` name the limit; `tests/worker_terminate.ts` tests the two shapes apart). - -```typescript -class Scope { - handler: () => void; - count: int; - - constructor() { - this.handler = () => {}; - this.count = 0; - } -} - -function run(body: (self: Scope) => void) { - const scope = new Scope(); - body(scope); - scope.handler(); - print(scope.count); -} - -function main() { - const shared = new Shared(new Int32Array(1)); - - // compiles under -mm=own and prints 1: the outer arrow captures nothing - run((self: Scope) => { - self.handler = () => { - self.count++; - }; - }); - - // the same, once the outer arrow captures something: under -mm=own - // "a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: - // its value is the caller's", at the inner arrow - run((self: Scope) => { - const counter = shared; - Atomics.add(counter.value, 0, 1); - self.handler = () => { - self.count++; - }; - }); -} -``` - -`-mm=own`: - -```text -40_closure_param_capture.ts:34:24: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: its value is the caller's - self.handler = () => { - ^ -``` - -`-mm=gc`: `1`, `1`. - -To do: the inner arrow captures `self` the same way in both calls, and `self` is the outer arrow's -parameter in both; what the outer arrow captures should not change whose `self` is. The error also -does not name the variable (item 32 made it name a captured variable in other cases). - -#### 41. An arrow kept in a field can't capture a parameter, and `@keeps` can't say that it does - -A constructor that keeps an arrow capturing one of its parameters is refused ("its value is the -caller's"), and `@keeps("body")`, which would make the caller give `body` up, is refused too: the -compiler finds that the constructor keeps nothing, although the arrow it stores takes `body` with it. -The default library hit this starting a `Worker`'s thread with `Thread.spawn(() => run(body, ...))` in -its constructor; it now keeps a `WorkerStart` object holding `body` (as `ThreadHandle` keeps its -`ThreadStart`) and starts the thread natively. - -```typescript -class Holder { - run: () => int; - - constructor(body: (n: int) => int) { - // the arrow is kept in a field and captures the parameter `body` - this.run = (): int => body(2); - } -} - -function main() { - const h = new Holder((n: int): int => n * 21); - print(h.run()); -} -``` - -`-mm=own`: - -```text -41_keeps_closure_capture.ts:6:20: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: its value is the caller's - this.run = (): int => body(2); - ^ -41_keeps_closure_capture.ts:6:9: note: the closure escapes here - this.run = (): int => body(2); - ^ -``` - -With `@keeps("body")` on the constructor (and `@final export class Holder`): - -```text -41b_keeps_rejected.ts:6:5: error: '@keeps' of 'Holder.constructor' names 'body', but its body keeps nothing - @keeps("body") - ^ -``` - -`-mm=gc`: `42`. - -To do: count a parameter captured by an escaping closure as kept, both when inferring what a function -keeps and when checking `@keeps`, so the closure owns it (the caller moves the argument in). - -#### 42. A class instance can't be taken out of a `T | undefined` field - -Exchanging a field with a local (`[data, this.data] = [this.data, data]`), the way the own-model guide -says to take a value out of a place, works for a string but not for a class instance in a field typed -`T | undefined`. The default library wanted a queue item holding either a message or an error; it now -queues the event objects themselves (`MessageEvent | ErrorEvent`) so nothing has to come out of a -field. - -```typescript -class Item { - constructor(public n: number) {} -} - -// a slot a value is put into and later taken back out of, by exchanging it with a local -class Slot { - constructor(public data: T | undefined) {} - - take(): T { - let data: T | undefined = undefined; - [data, this.data] = [this.data, data]; - return data; - } -} - -function main() { - // compiles under -mm=own and prints "a" - const text = new Slot("a"); - print(text.take()); - - // the same for a class instance: under -mm=own - // "'this value' borrows a field and cannot be stored, returned or captured" - const item = new Slot(new Item(1)); - print(item.take().n); -} -``` - -`-mm=own`: - -```text -42_move_out_of_union_field.ts:11:29: error: 'this value' borrows a field and cannot be stored, returned or captured - [data, this.data] = [this.data, data]; - ^ -42_move_out_of_union_field.ts:11:9: error: 'this value' borrows an element and cannot be stored, returned or captured - [data, this.data] = [this.data, data]; - ^ -42_move_out_of_union_field.ts:12:9: error: 'this value' is merged from several branches (`?:`, `&&`, `||`, `??`, a loop); -mm=own cannot prove which one owns it yet - return data; - ^ -``` - -The same file with only the `Slot` lines compiles under `-mm=own` and prints `a`. -`-mm=gc`: `a`, `1`. - -To do: the exchange of a union-typed field with a local should move the value out for a class -instance as it does for a string, and the `` cast of a `T | undefined` local that holds it should -not count as a merge of branches. +Items 39-42, `-mm=own` limits found in the default library on 2026-11-09 (TypeScriptCompilerDefaultLib +PRs #80-#85), are fixed. 39 (a chain from a new value, `JsonValue.newObject().set(...).set(...)`, could +not be returned or kept): a method whose result type is `this` returns the object it is called on, and +called on a temporary the caller owns, its result is that object, the caller's to keep. `: this` says +it, with no decorator, and implies `@lends("this")`; under `-mm=own` a body that returns another object +of the type is an error. A method typed with its class that returns `this` on every path works the same +within its module; for another module, `: this` is how a declaration says it (the `-shared` declaration +printer writes it). The default library's `set` and `push` return `this` now, and `tests/json.ts` runs +its chains under every model. 40 (an arrow that captures something could not store a closure over its +object parameter into a field of that object): it is a back-reference as it is from an arrow that +captures nothing. 41 (a closure kept in a field could not capture a parameter, and `@keeps` could not +say it did): a closure that is kept owns the parameters it captures, so the function keeps them and its +callers give them up; `@keeps("body")` is accepted. The error for a capture that still cannot move names +the variable. 42 (`[data, this.data] = [this.data, data]` did not move a class instance out of a +`T | undefined` field): an exchange of a local and a field or an element hands each value over under +every model, and `data` of such a local is a view of it. Regression tests +`tslang/test/tester/own/own_chain_returns_this.ts`, `own_closure_keeps_param.ts`, +`own_swap_local_field.ts`, `own_err_this_result_other.ts` and `own_err_closure_kept_param_used.ts`.