Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5427,6 +5427,29 @@ object, and a parameter to interface parameters and reads the objects after; a l
interface and one an array keeps still take their copies. It churns between steps, under own, rc, gc and
none.

Not here: a literal capturing a `let` (a cell), which errors as `captured by a closure that escapes`
with or without an interface; and `return applyO({ w: (x) => x + item.n })` for an object-type parameter,
`a closure that escapes owns what it captures`.
Not here: a literal capturing a `let` (a cell), and `return applyO({ w: (x) => x + item.n })` for an
object-type parameter; see spec 69.

## 69. An object literal whose arrows capture a `let` or a parameter, 2026-10-29

`let d = new Item(4); apply({ w: (x) => x + d.n }); d.n` was `'this value' is captured by a closure that
escapes`, and `function viaParam(item: Item) { return applyO({ w: (x) => x + item.n }); }` was `a closure
that escapes owns what it captures ... its value is the caller's`. Two shapes, two causes:

- **A typed literal's arrow is a closure stored into an unboxed record** (spec 36) - the record built
for `apply`'s object-type parameter. `followClosure` took the store into the record's field for an
escape, and an escaping closure owns its cells. The record owns nothing, so the store is not one: the
record's reads, its reads of that field (in place, or `ts.ExtractProperty` of a read), and the calls it
is given are the closure's uses, as a local's reads are.
- **A literal's `.captured` box was also taken for a generator's state** (`classifyStateBoxes`): every
object literal with arrows is state-shaped, and a state owns its cells and its copies. A box
`classifyLiteralCaptures` decides borrows (specs 67, 68) is no state's now, and it borrows a cell of a
`let` of this frame the way a closure that does not escape does: rc's `ts.RetainCell` for it and the
box's own go (`captureRetains`), and `decideClosures` checks that nothing using the literal comes after
the cell is released or moved into an escaping closure. Any other cell (one read out of an enclosing
function's box) leaves the literal to the state path, as before. The record path (spec 68) takes the
same cells: `tsfrecb_` frees the box, and the frame frees the cell.

`own_literal_let_captures` captures `let`s - inline in a call, in a `const` literal called and given on,
given to an interface - assigns them after, and captures parameters in literals given to an object-type
and an interface parameter, churning between steps, under own, rc, gc and none.
127 changes: 126 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferenceClosures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ namespace own_inference
// filled field by field, and stored once into a literal's `.captured`: `{ w: (x) => x * b.n }`
// builds the literal in a local, then copies it into the object `ts.New` made
llvm::SmallVector<mlir_ts::StoreOp> fills;
llvm::SmallVector<mlir::Operation *> boxRetains;
mlir_ts::VariableOp literalOp;
int32_t capturedPosition = -1;
for (auto &use : boxOp->getUses())
Expand All @@ -154,6 +155,11 @@ namespace own_inference
// rc's count of the box, for the literal's reference
if (mlir::isa<mlir_ts::RetainCellOp, mlir_ts::ReleaseCellOp>(user))
{
if (mlir::isa<mlir_ts::RetainCellOp>(user))
{
boxRetains.push_back(user);
}

continue;
}

Expand Down Expand Up @@ -214,6 +220,7 @@ namespace own_inference

// the literal stays here: nothing stores, returns, captures or keeps it
auto box = std::make_shared<Closure>();
box->box = boxOp.getResult();
llvm::SmallVector<BorrowUse> uses;
auto newOp = objects.front().getDefiningOp<mlir_ts::NewOp>();
if (llvm::is_contained(recordBorrowedFields(newOp), capturedPosition))
Expand Down Expand Up @@ -263,7 +270,26 @@ namespace own_inference
for (auto storeOp : fills)
{
auto value = storeOp.getValue();
if (mlir::isa<mlir_ts::RefType>(value.getType()) || holdsNoBlock(value))
// a cell of a `let` of this frame (spec 69): borrowed as a closure that does not escape
// borrows it, the cell's own releases bounding the literal's uses (decideClosures)
if (mlir::isa<mlir_ts::RefType>(value.getType()))
{
if (!isCellVariable(value))
{
return;
}

if (auto *retain = retainBefore(value, storeOp))
{
box->retains.push_back(retain);
}

box->fills.push_back({0, storeOp});
box->hasCells = true;
continue;
}

if (holdsNoBlock(value))
{
continue;
}
Expand All @@ -282,6 +308,9 @@ namespace own_inference
borrowed.push_back(storeOp);
}

// ...and the box's own: no state's (classifyStateBoxes)
box->retains.append(boxRetains.begin(), boxRetains.end());

captureRetains.insert(box->retains.begin(), box->retains.end());
for (auto storeOp : borrowed)
{
Expand Down Expand Up @@ -798,6 +827,12 @@ namespace own_inference
return;
}

// an object literal's box that borrows (classifyLiteralCaptures): no state's
if (llvm::any_of(literalBoxes, [&](auto &literalBox) { return literalBox->box == box; }))
{
return;
}

auto closure = std::make_shared<Closure>();
closure->box = box;
llvm::SmallVector<mlir::Operation *> boxRetains;
Expand Down Expand Up @@ -990,6 +1025,44 @@ namespace own_inference
}
}
};
// the closure's field of an unboxed record: the record's reads, and that field's
llvm::SmallVector<std::pair<mlir::Value, int64_t>> records;
auto followUnboxedRecord = [&](mlir_ts::VariableOp recordOp, int64_t position) {
for (auto *recordUser : recordOp->getUsers())
{
if (auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(recordUser))
{
records.push_back({loadOp.getResult(), position});
values.push_back(loadOp.getResult());
}
else if (auto propertyRefOp = mlir::dyn_cast<mlir_ts::PropertyRefOp>(recordUser))
{
// its fields, filled and read in place
for (auto *fieldUser : propertyRefOp->getUsers())
{
if (auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(fieldUser);
loadOp && propertyRefOp.getPosition() != position)
{
continue;
}

if (auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(fieldUser))
{
values.push_back(loadOp.getResult());
}
else if (auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(fieldUser);
!storeOp || storeOp.getReference() != propertyRefOp.getResult())
{
escape = escape ? escape : fieldUser;
}
}
}
else if (!mlir::isa<mlir_ts::DebugVariableOp>(recordUser))
{
escape = escape ? escape : recordUser;
}
}
};

while (!values.empty() && !escape)
{
Expand Down Expand Up @@ -1072,6 +1145,34 @@ namespace own_inference
return;
}

// a field of an unboxed record (spec 36), which owns nothing: `apply({ w: (x) => x + d.n })`
// - whatever the record is given to, and whatever is read out of it, may run the closure
if (auto fieldOp = slot ? slot.getDefiningOp<mlir_ts::PropertyRefOp>() : mlir_ts::PropertyRefOp())
{
auto recordOp = fieldOp.getObjectRef().getDefiningOp<mlir_ts::VariableOp>();
if (recordOp && !recordOp.getCaptured().value_or(false) && !unboxedRecordFields(recordOp).empty())
{
followUnboxedRecord(recordOp, fieldOp.getPosition());
return;
}
}

// ...and a record read out of one: the closure's field read, not the others
if (auto extractOp = mlir::dyn_cast<mlir_ts::ExtractPropertyOp>(user))
{
auto record = llvm::find_if(records, [&](auto &entry) { return entry.first == used; });
if (record != records.end())
{
auto position = extractOp.getPosition();
if (position.size() == 1 && position.front() == record->second)
{
values.push_back(extractOp.getResult());
}

return;
}
}

escape = user;
});
}
Expand Down Expand Up @@ -1102,6 +1203,30 @@ namespace own_inference
for (auto &box : literalBoxes)
{
toErase.insert(box->retains.begin(), box->retains.end());

// the cells a literal borrows (spec 69): nothing that uses it after one is given back
auto ok = true;
for (auto &fill : box->fills)
{
auto cell = fill.second.getValue();
auto name = varName(cell.getDefiningOp<mlir_ts::VariableOp>());
for (auto *end : cell.getUsers())
{
if (!mlir::isa<mlir_ts::ReleaseCellOp>(end) && !movesCellAway(end))
{
continue;
}

for (auto *use : box->uses)
{
if (ok && reachableAfter(end, use, box->box.getDefiningOp()))
{
reportClosureOutlives(use, end, "the object literal", name);
ok = false;
}
}
}
}
}

for (auto &closure : closures)
Expand Down
4 changes: 3 additions & 1 deletion tslang/lib/TypeScript/OwnershipSignatureRecords.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,9 @@ namespace own_signature
}

auto value = fillOp.getValue();
if (mlir::isa<mlir_ts::RefType>(value.getType()) || (!holdsNoBlock(value) && !hasOwnerOfItsOwn(value)))
// a cell of a `let` of this frame, which frees it (spec 69), or a copy
if (mlir::isa<mlir_ts::RefType>(value.getType()) ? !isCellVariable(value)
: !holdsNoBlock(value) && !hasOwnerOfItsOwn(value))
{
return false;
}
Expand Down
4 changes: 2 additions & 2 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4022,7 +4022,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o
own_generator_this_param own_copy_within_returned_param own_swap_elements
own_callback_forwarded own_optional_record_read own_param_default_kept own_literal_into_array
own_generator_take own_rest_array_borrows own_string_copies
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures
own_callback_shapes own_callback_extended own_callback_interface
own_generic_specializations own_callback_cast own_callback_interface_slot)
tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts")
Expand Down Expand Up @@ -4060,7 +4060,7 @@ foreach(keeps_mm rc gc none)
own_copy_within_returned_param own_swap_elements own_callback_forwarded
own_optional_record_read own_param_default_kept own_literal_into_array
own_generator_take own_rest_array_borrows own_string_copies
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures
own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures
own_callback_shapes own_callback_extended own_callback_interface
own_generic_specializations own_callback_cast own_callback_interface_slot)
tslang_add_test(NAME test-jit-${keeps_mm}-${keeps_test} COMMAND test-runner -jit -mm=${keeps_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${keeps_test}.ts")
Expand Down
70 changes: 70 additions & 0 deletions tslang/test/tester/own/own_literal_let_captures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// An object literal whose arrows capture a `let` or a parameter (spec 69): a literal that stays in the
// function borrows the `let`'s cell, as a closure that does not escape does - inline in a call, held in
// a `const`, given to an object-type or an interface parameter - and the variable is read and assigned
// after. A parameter captured by a literal given to a call that returns a number is a borrow too. Each
// step churns, so anything freed too early reads garbage; every model runs it.
class Item {
constructor(public n: number) {}
}

interface Scaler {
w(x: number): number;
}

function churn() {
const junk: Item[] = [];
for (let i = 0; i < 64; i++) junk.push(new Item(999));
}

function apply(o: { w: (x: number) => number }) {
return o.w(3);
}

function applyI(s: Scaler) {
return s.w(3);
}

function viaParam(item: Item) {
return apply({ w: (x: number) => x + item.n });
}

function viaParamI(item: Item) {
const q = { w: (x: number) => x + item.n };
return applyI(q) + q.w(1);
}

function test(i: number) {
let s: number = 0;
let d = new Item(i);
s += apply({ w: (x: number) => x + d.n });
churn();
s += d.n;

d = new Item(2);
const q = { w: (x: number) => x * d.n };
s += q.w(1) + apply(q);
churn();
s += d.n;

let e = new Item(4);
s += applyI({ w: (x: number) => x + d.n + e.n });
churn();
e = new Item(5);
s += e.n;

s += viaParam(d) + viaParamI(e);
churn();
return s;
}

function main() {
let ok = 0;
for (let i = 0; i < 300; i++) {
// (3 + i) + i, (2 + 6) + 2, (3 + 2 + 4) + 5, (3 + 2) + (3 + 5) + (1 + 5)
if (test(i) == 3 + 2 * i + 10 + 14 + 19) ok++;
churn();
}

assert(ok == 300, "ok");
print("done.");
}
Loading