From dbf3d98974c89a4b734bca3cbf321b01966b0b3d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 30 Oct 2026 21:27:59 +0000 Subject: [PATCH 1/5] -mm=own copies an `any` as it copies a string; @copies for arrays; generators over immortal globals Under own a second owner own cannot prove becomes a copy for a string (spec 22). Now for an `any` box too, so an untyped Map (Map) and a @sharedElements container of `any` work: - ts.StringCopy of an `any` lowers to a new box of the same bytes. A payload that owns nothing is copied with them; a string payload is copied in turn. An object payload has one owner, the box: the copy stops the program with a message, as a failed assert does. - copyForRetain: of several uses (`f(s); f(s)`, `push(s, s)`) the retain copies for the first after it in its block, as rc retained each beside its use. own_err_string_pushed_twice pinned the old rule and said to become a positive when it widened: it is own_string_pushed_twice. - A constant boxed into `any` (`k.keep(42)`) or printed into a string was taken for a literal that holds no block, so its release stayed after the move and the box was freed twice. On main too. - An array whose elements own nothing is copied the same way, but only in a function that says `@copies`: a copy of an array can be told from it. The default library's reduce and reduceRight, whose accumulator starts as an element, say it. - A generator kept in a global that borrows only immortal globals outlives nothing (`const it = map.values()` at the top of a script). Tests: own_any_copies, own_array_copies, own_string_pushed_twice (own, no counting), own_any_object_copy_stops. own_err_shared_elements_any is gone: `any` is an element now. Release ctest 6457/6457. Co-Authored-By: Claude Opus 5.5 --- tslang/include/TypeScript/Defines.h | 6 ++ tslang/lib/TypeScript/LowerToLLVM.cpp | 60 +++++++++++++++- tslang/lib/TypeScript/MLIRGenGenerics.cpp | 19 ++---- tslang/lib/TypeScript/MLIRGenImpl.h | 18 +++++ tslang/lib/TypeScript/OwnershipFacts.h | 38 +++++++++++ .../TypeScript/OwnershipInferenceClosures.cpp | 33 ++++++++- .../lib/TypeScript/OwnershipInferencePass.cpp | 23 +++++-- .../OwnershipInferencePlaceReads.cpp | 6 +- tslang/test/tester/CMakeLists.txt | 17 +++-- tslang/test/tester/own/own_any_copies.ts | 68 +++++++++++++++++++ .../tester/own/own_any_object_copy_stops.ts | 23 +++++++ tslang/test/tester/own/own_array_copies.ts | 47 +++++++++++++ .../tester/own/own_err_shared_elements_any.ts | 10 --- .../tester/own/own_err_string_pushed_twice.ts | 10 --- .../tester/own/own_string_pushed_twice.ts | 20 ++++++ 15 files changed, 351 insertions(+), 47 deletions(-) create mode 100644 tslang/test/tester/own/own_any_copies.ts create mode 100644 tslang/test/tester/own/own_any_object_copy_stops.ts create mode 100644 tslang/test/tester/own/own_array_copies.ts delete mode 100644 tslang/test/tester/own/own_err_shared_elements_any.ts delete mode 100644 tslang/test/tester/own/own_err_string_pushed_twice.ts create mode 100644 tslang/test/tester/own/own_string_pushed_twice.ts diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index d1cfec7e7..84eaf7746 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -368,6 +368,12 @@ // 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" +// `@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 +// one: reduce's accumulator, which starts as an element. The other models ignore it. A unit attribute. +#define COPIES_DECORATOR "copies" +#define OWN_DECLARED_COPIES_ATTR_NAME "ts.own_declared_copies" // `@immortalizes` names the parameters the function keeps for good, in an append-only global (a // keeper, docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): its callers make each // argument immortal. Checked against a body; trusted on a declaration, a C function that keeps a diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 5bd985971..8cfca7e90 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -1235,6 +1235,64 @@ class StringCopyOpLowering : public TsLlvmPattern return rewriter.create(loc, LLVM::ICmpPredicate::ne, pointer, rewriter.create(loc, i8PtrTy)); }; + // An `any` box: a new box of the same bytes. A payload that owns nothing (its descriptor has + // no release routine) is copied with them; a string payload is copied in turn, as above. + if (mlir::isa(op.getIn().getType())) + { + AnyLogic al(op, rewriter, tch, loc, tsLlvmContext->compileOptions); + TypeDescriptorLogic tdl(rewriter, tch, loc); + auto boxCopy = clh.conditionalExpressionLowering( + loc, i8PtrTy, isSet(in), + [&](OpBuilder &, Location) -> mlir::Value { + auto dataOffset = rewriter.create(loc, llvmIndexType, al.getDataPtrOfAny(rewriter.create(loc, i8PtrTy))); + mlir::Value bytes = rewriter.create(loc, llvmIndexType, ValueRange{dataOffset, al.getDataSizeOfAny(in)}); + auto copy = ch.MemoryAlloc(bytes); + ch.MemoryCopy(copy, bytes, in, bytes); + + auto tag = al.getTypeOfAny(in); + auto releasePtr = rewriter.create(loc, i8PtrTy, tdl.getRecordType(), tdl.getRecordPtrFromTag(tag), + ArrayRef{0, TYPE_DESCR_RELEASE}); + auto release = rewriter.create(loc, i8PtrTy, releasePtr); + return clh.conditionalExpressionLowering( + loc, i8PtrTy, isSet(release), + [&](OpBuilder &, Location) -> mlir::Value { + return clh.conditionalExpressionLowering( + loc, i8PtrTy, tdl.isKind(tag, TYPE_KIND_STRING), + [&](OpBuilder &, Location) -> mlir::Value { + auto dataSlot = al.getDataPtrOfAny(copy); + auto text = rewriter.create(loc, i8PtrTy, dataSlot); + rewriter.create(loc, copyOf(text, isSet(text)), dataSlot); + return copy; + }, + [&](OpBuilder &, Location) -> mlir::Value { + // an object payload has one owner, and the box being copied is it: the + // program stops, as a failed assert does (spec 71) + AssertLogic(op, rewriter, tch, loc, tsLlvmContext->compileOptions) + .check(rewriter.create(loc, rewriter.getI1Type(), rewriter.getBoolAttr(false)), + "-mm=own cannot copy an 'any' that holds an object; give the object a Shared"); + return copy; + }); + }, + [&](OpBuilder &, Location) -> mlir::Value { return copy; }); + }, + [&](OpBuilder &, Location) -> mlir::Value { return in; }); + rewriter.replaceOp(op, ValueRange{boxCopy}); + return success(); + } + + // An array whose elements own nothing: a new header over a copy of the data block. A null + // array reads as an empty one, and its copy is an empty array. + if (auto arrayType = mlir::dyn_cast(op.getIn().getType())) + { + ArrayLayout al(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); + auto length = al.length(arrayType, in); + auto bytes = al.bytesFor(arrayType, length); + auto data = ch.MemoryAlloc(bytes); + ch.MemoryCopy(data, bytes, al.data(arrayType, in), bytes); + rewriter.replaceOp(op, ValueRange{al.make(arrayType, data, length)}); + return success(); + } + if (mlir::isa(in.getType())) { rewriter.replaceOp(op, ValueRange{copyOf(in, isSet(in))}); @@ -2311,7 +2369,7 @@ struct FuncOpLowering : public TsLlvmPattern 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_IMMORTALIZES_ATTR_NAME) { + name == OWN_DECLARED_IMMORTALIZES_ATTR_NAME || name == OWN_DECLARED_COPIES_ATTR_NAME) { continue; } diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index b8df0f3b9..b6704fd4a 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -1341,24 +1341,19 @@ namespace mlirgen continue; } + // an `any` (or `unknown`, the same box) is copied as a string is, payload and all auto type = mth.stripLiteralType(std::get<1>(found->getValue())); if (!type || mlir::isa(type) || mlir::isa(type) || - MLIRTypeHelper::isSharedHandleType(type) || !mth.ownsHeapMemory(location, type)) + mlir::isa(type) || MLIRTypeHelper::isSharedHandleType(type) || + !mth.ownsHeapMemory(location, type)) { continue; } - auto diag = emitError(location) << "-mm=own: '" << genericClassInfo->name << "' cannot hold '" << to_print(type) - << "' (its '" << typeParam->getName() - << "'): an element has to be a value, a string or a Shared handle; "; - if (mlir::isa(type)) - { - diag << "give it one of those types"; - } - else - { - diag << "use 'Shared<" << to_print(type) << ">'"; - } + emitError(location) << "-mm=own: '" << genericClassInfo->name << "' cannot hold '" << to_print(type) + << "' (its '" << typeParam->getName() + << "'): an element has to be a value, a string, an any or a Shared handle; use 'Shared<" + << to_print(type) << ">'"; result = mlir::failure(); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 4a0659688..139c7f932 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3446,6 +3446,24 @@ class MLIRGenImpl return; } + // `@copies` names nothing either: it lets -mm=own copy an array in the body (spec 71) + if (name == COPIES_DECORATOR) + { + if (!args.empty()) + { + emitError(location) << "'@" COPIES_DECORATOR "' names no parameter"; + result = mlir::failure(); + return; + } + + if (llvm::none_of(attrs, [](mlir::NamedAttribute &attr) { return attr.getName() == OWN_DECLARED_COPIES_ATTR_NAME; })) + { + attrs.push_back({builder.getStringAttr(OWN_DECLARED_COPIES_ATTR_NAME), builder.getUnitAttr()}); + } + + return; + } + if (name != KEEPS_DECORATOR && name != BORROWS_DECORATOR && name != LENDS_DECORATOR && name != IMMORTALIZES_DECORATOR) { diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 43ff375f7..fb09fa464 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -492,6 +492,15 @@ inline bool isLiteral(mlir::Operation *def) return false; } + // ...but a constant boxed into `any` is a new box, and a number printed into a string a new + // string: blocks of their own, which their releases free (`k.keep(42)` freed the box it kept) + auto out = castOp.getType(); + if (mlir::isa(out) || + (mlir::isa(out) && mlir_ts::castToStringAllocates(castOp.getIn().getType()))) + { + return false; + } + auto *in = castOp.getIn().getDefiningOp(); return in && mlir::isa(in); } @@ -1084,6 +1093,35 @@ inline bool isCopyableString(mlir::Type type) return isText(type); } +// A value -mm=own may copy rather than give a second owner (ts.StringCopy of it): a string as +// above, or an `any` box, copied into a new box with a copy of a string payload in it. Neither can +// change in place, so the copy cannot be told from the original. +inline bool isCopyableValue(mlir::Type type) +{ + return isCopyableString(type) || mlir::isa(type); +} + +// An array whose elements own nothing (`number[]`): a copy is a new header over a copy of the data +// block. It can be told from the original, so it is made only where a function says `@copies`. +inline bool isCopyableArray(mlir::Type type) +{ + auto arrayType = mlir::dyn_cast(type); + return arrayType && !ownsHeap(mlir::UnknownLoc::get(type.getContext()), arrayType.getElementType()); +} + +// What -mm=own may copy at `at`: a copyable value anywhere, and an array in a function that says +// `@copies`. +inline bool isCopyableValueAt(mlir::Operation *at, mlir::Type type) +{ + if (isCopyableValue(type)) + { + return true; + } + + auto funcOp = at ? at->getParentOfType() : mlir_ts::FuncOp(); + return funcOp && funcOp->hasAttr(OWN_DECLARED_COPIES_ATTR_NAME) && isCopyableArray(type); +} + // Some view of `value` is a `ts.NewInterface`, which boxes what it shows into a block. inline bool boxedByView(mlir::Value value) { diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index fac92aa00..aa3fda448 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -594,14 +594,43 @@ namespace own_inference } auto name = ownerName(call->getResult(0)); + auto args = callArgs(call); + + // Borrowing only immortal globals (spec 25: never given another value, never freed) it + // outlives nothing, wherever it is kept: `const it = map.values()` at the top of a script. + // One of them at least: a callback that holds no block says nothing of the array `.map` reads. + auto immortals = 0; + auto boundedByImmortals = llvm::all_of(bounded.asArrayRef(), [&](int32_t index) { + if (static_cast(index) >= args.size()) + { + return true; + } + + auto root = rootOf(args[index]); + if (auto object = boundThis(root)) + { + root = rootOf(object); + } + + if (isImmortalGlobalRead(root)) + { + immortals++; + return true; + } + + return holdsNoBlock(args[index]); + }); + if (boundedByImmortals && immortals > 0) + { + return; + } + llvm::SmallVector uses; if (auto *kept = boundedUses(call->getResult(0), uses)) { reportPlaceBorrowEscapes(kept, name, "its generator's arguments"); return; } - - auto args = callArgs(call); for (auto index : bounded.asArrayRef()) { if (static_cast(index) >= args.size()) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index baa696d39..8f3778ee6 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -851,7 +851,7 @@ namespace own_inference { auto varOp = retainSlotOp.getSlot().getDefiningOp(); auto init = varOp ? varOp.getInitializer() : mlir::Value(); - if (!init || !isCopyableString(init.getType()) || isCellVariable(varOp.getResult())) + if (!init || !isCopyableValueAt(varOp, init.getType()) || isCellVariable(varOp.getResult())) { return false; } @@ -879,13 +879,15 @@ namespace own_inference return true; } - if (!isCopyableString(value.getType())) + if (!isCopyableValueAt(retain, value.getType())) { return false; } - // the one use rc retained it for + // the one use rc retained it for. Of several (`f(s); f(s)` boxing `s` into `any` twice), the + // first after the retain in its block: rc retains each beside the use it takes it for. mlir::OpOperand *taking = nullptr; + mlir::OpOperand *nearest = nullptr; auto several = false; forEachUse(value, [&](mlir::Operation *user, mlir::Value used) { if (mlir::isa(user) || isBorrow(user, used)) @@ -899,11 +901,22 @@ namespace own_inference { several = several || taking; taking = &operand; + if (user->getBlock() == retain->getBlock() && retain->isBeforeInBlock(user) && + (!nearest || user->isBeforeInBlock(nearest->getOwner()))) + { + nearest = &operand; + } } } }); - if (!taking || several || !isCopyableString(taking->get().getType())) + if (several) + { + taking = nearest; + several = false; + } + + if (!taking || several || !isCopyableValueAt(retain, taking->get().getType())) { return false; } @@ -981,7 +994,7 @@ namespace own_inference continue; } - if (!isCopyableString(field.getType()) || borrowsKnownParam(field)) + if (!isCopyableValueAt(retainOp, field.getType()) || borrowsKnownParam(field)) { return false; } diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 54fc60846..4c26f15ae 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -758,14 +758,14 @@ namespace own_inference { // given once: a copy given twice would have two owners. Not an invoke, whose release after // it would go on the normal path only. - return (isCopyableString(value.getType()) || isHandle(value)) && !mlir::isa(call) && + return (isCopyableValueAt(call, value.getType()) || isHandle(value)) && !mlir::isa(call) && llvm::count(call->getOperands(), value) == 1; } bool OwnershipInferencePass::storesCopyOf(mlir::Operation *store, mlir::Value value) { auto storeOp = mlir::dyn_cast(store); - if (!storeOp || storeOp.getValue() != value || !(isCopyableString(value.getType()) || isHandle(value)) || + if (!storeOp || storeOp.getValue() != value || !(isCopyableValueAt(store, value.getType()) || isHandle(value)) || !isPlace(storeOp.getReference())) { return false; @@ -1024,7 +1024,7 @@ namespace own_inference }; if (!slot || slot.getCaptured().value_or(false) || !ownsOrHoldsResults() || !slotType || - !mlir::isa(slotType.getElementType()) || isCopyableString(read->getResult(0).getType())) + !mlir::isa(slotType.getElementType()) || isCopyableValueAt(read, read->getResult(0).getType())) { return false; } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 29d7f6c7a..1d824ceda 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4088,7 +4088,8 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_generator_take own_rest_array_borrows own_string_copies own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures own_interface_generic_method own_back_reference own_field_function_result own_callback_shapes own_callback_extended own_callback_interface - own_generic_specializations own_callback_cast own_callback_interface_slot) + own_generic_specializations own_callback_cast own_callback_interface_slot + own_any_copies own_array_copies own_string_pushed_twice) 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. @@ -4752,7 +4753,6 @@ set(own_error_cases "own_err_generator_method_this|'this value' is a parameter, kept here, but -mm=own cannot make the callers of 'S.chars' give it up" "own_err_generator_method_reassigned|:17:5: error: '[^']*' borrows '[^']*' but is used here after '[^']*' is released or overwritten" "own_err_callback_method_overridden|:12:53: error: '[^']*' borrows a field but is used here after it may be released or overwritten" - "own_err_string_pushed_twice|:9:5: error: '[^']*' is used here after its value was moved" "own_err_shared_borrow_write|:12:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_shared_borrow_call|:19:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_shared_borrow_push|:17:11: error: '[^']*' borrows an element but is used here after it may be released or overwritten" @@ -4824,8 +4824,7 @@ set(own_error_cases "own_err_keeper_exported|:7:5: error: 'Registry[.]register' keeps '#1' for good, but -mm=own cannot tell its callers in other modules. '@immortalizes' would say it in its signature" "own_err_keeper_declared|:5:1: error: '@immortalizes' of 'keep' names 'a', but its body keeps for good 'b'" "own_err_keeper_called_through_value|:6:1: error: 'keep' keeps '#0' for good, but -mm=own cannot make every caller make it immortal: the function is called through a value" - "own_err_shared_elements_object|:13:21: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]: an element has to be a value, a string or a Shared handle. use 'Shared'" - "own_err_shared_elements_any|:8:21: error: -mm=own: 'Bag' cannot hold 'any' [(]its 'T'[)]: an element has to be a value, a string or a Shared handle. give it one of those types" + "own_err_shared_elements_object|:13:21: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]: an element has to be a value, a string, an any or a Shared handle. use 'Shared'" "own_err_shared_elements_inferred|:12:17: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]" "own_err_keeper_popped|:14:9: error: argument '[^']*' is given to 'Registry[.]register', which keeps it, but -mm=own cannot move it here" "own_err_generator_keeps_missing|:9:1: error: '@keeps' of 'mapped<[^']*' names 'iter', but its body keeps 'iter', 'f'" @@ -5189,6 +5188,16 @@ set_tests_properties(test-jit-assert-message-failing PROPERTIES PASS_REGULAR_EXPRESSION "printed before.*assertion failed: n is 7" FAIL_REGULAR_EXPRESSION "Stack dump|unlinked") +# Under own, a copy of an `any` that holds an object stops the program with a message, after the +# output printed before it (spec 71). +add_test(NAME test-jit-own-own_any_object_copy_stops + COMMAND $ --emit=jit --no-default-lib -mm=own + --shared-libs=$ + "${PROJECT_SOURCE_DIR}/test/tester/own/own_any_object_copy_stops.ts") +set_tests_properties(test-jit-own-own_any_object_copy_stops + PROPERTIES PASS_REGULAR_EXPRESSION "printed before.*assertion failed: -mm=own cannot copy an 'any' that holds an object" + FAIL_REGULAR_EXPRESSION "Stack dump|PLEASE submit|not reached") + # An invalid array length stops the program with a message, after the output printed before it, # under every model (#483), when there is no default library: with one it throws a RangeError. The JIT reports it itself on every platform, as for a failing assert. foreach(array_length_name negative huge fraction negative_integer new_negative) diff --git a/tslang/test/tester/own/own_any_copies.ts b/tslang/test/tester/own/own_any_copies.ts new file mode 100644 index 000000000..1c1733071 --- /dev/null +++ b/tslang/test/tester/own/own_any_copies.ts @@ -0,0 +1,68 @@ +// -mm=own copies an `any` rather than give it a second owner, as it copies a string (spec 71): a +// string boxed twice (`f(s); f(s)`) boxes a copy each time, a fresh box given to two calls is two +// boxes, and a @sharedElements container may hold `any`. A box's copy is a new box; a string in it is +// copied too, and a number is copied with the box. Each value is read after churn() has reused +// anything freed too early. +@sharedElements +class Bag { + items: T[] = []; + + add(item: T) { + this.items.push(item); + } + + has(item: T) { + for (const i of this.items) { + if (i == item) return true; + } + + return false; + } +} + +class Keeper { + kept: any[] = []; + + keep(a: any) { + this.kept.push(a); + return true; + } +} + +function churn() { + const hold: string[] = []; + for (let i = 0; i < 64; i++) { + hold.push("churn" + i); + } +} + +function main() { + // the same string boxed into two calls that keep what they are given + const k = new Keeper(); + const s = "Hel" + "lo"; + assert(k.keep(s)); + assert(k.keep(s)); + churn(); + assert(k.kept[0] == "Hello" && k.kept[1] == "Hello", "two boxes of one string"); + assert(s == "Hello", "the string itself"); + + // a fresh box each time + assert(k.keep("Wor" + "ld")); + assert(k.keep("Wor" + "ld")); + churn(); + assert(k.kept[2] == "World" && k.kept[3] == "World", "fresh boxes"); + + // a container of `any`: strings and numbers + const bag = new Bag(); + const word = "w" + 1; + bag.add(word); + bag.add(word); + bag.add(42); + churn(); + assert(bag.items.length == 3, "three items"); + assert(bag.has("w1"), "a string item"); + assert(bag.has(42), "a number item"); + assert(word == "w1", "the string added twice"); + + print("done."); +} diff --git a/tslang/test/tester/own/own_any_object_copy_stops.ts b/tslang/test/tester/own/own_any_object_copy_stops.ts new file mode 100644 index 000000000..c0a926cd9 --- /dev/null +++ b/tslang/test/tester/own/own_any_object_copy_stops.ts @@ -0,0 +1,23 @@ +// -mm=own copies an `any` it cannot give a second owner (spec 71), but an object in it has one owner, +// the box: the copy stops the program with a message, as a failed assert does, after what was printed +// before it. Here one box is kept twice, which needs a copy for each keep. +class C { + constructor(public n: number) {} +} + +class Keeper { + kept: any[] = []; + + keep(a: any) { + this.kept.push(a); + } +} + +function main() { + print("printed before"); + const k = new Keeper(); + const o: any = new C(1); + k.keep(o); + k.keep(o); + print("not reached"); +} diff --git a/tslang/test/tester/own/own_array_copies.ts b/tslang/test/tester/own/own_array_copies.ts new file mode 100644 index 000000000..f786b1e13 --- /dev/null +++ b/tslang/test/tester/own/own_array_copies.ts @@ -0,0 +1,47 @@ +// -mm=own copies an array whose elements own nothing (`number[]`) rather than give it a second owner +// (spec 71): an accumulator that starts as an element and is then given new values - reduceRight over +// rows with no initial value - starts from a copy of the element, so the rows keep theirs and the +// result has one owner. A copy of an array can be told from the array, so only a function that says +// `@copies` gets one. Each value is read after churn() has reused anything freed too early. +@copies +function reduceRows(rows: T[], func: (v: T, t: T) => T): T { + let result = rows[rows.length - 1]; + for (let i = rows.length - 2; i >= 0; i--) result = func(result, rows[i]); + return result; +} + +function join(a: number[], b: number[]) { + const joined: number[] = []; + for (const x of a) joined.push(x); + for (const x of b) joined.push(x); + return joined; +} + +function churn() { + const hold: number[][] = []; + for (let i = 0; i < 64; i++) { + hold.push([i, i + 1, i + 2]); + } +} + +function main() { + const rows: number[][] = [ + [0, 1], + [2, 3], + [4, 5], + ]; + + const joined = reduceRows(rows, join); + churn(); + assert(joined.length == 6 && joined[0] == 4 && joined[5] == 1, "the rows joined from the right"); + assert(rows[2].length == 2 && rows[2][0] == 4, "the last row is its own"); + + // one row: the result is the element itself in JavaScript, and a copy of it under own + const one: number[][] = [[7, 8]]; + const single = reduceRows(one, join); + churn(); + assert(single.length == 2 && single[1] == 8, "the one row"); + assert(one[0].length == 2 && one[0][0] == 7, "the row itself"); + + print("done."); +} diff --git a/tslang/test/tester/own/own_err_shared_elements_any.ts b/tslang/test/tester/own/own_err_shared_elements_any.ts deleted file mode 100644 index 91d4d69f6..000000000 --- a/tslang/test/tester/own/own_err_shared_elements_any.ts +++ /dev/null @@ -1,10 +0,0 @@ -// -mm=own rejects: a @sharedElements container of `any`, which may hold an object. -@sharedElements -class Bag { - items: T[] = []; -} - -function main() { - const bag = new Bag(); - print(bag.items.length); -} diff --git a/tslang/test/tester/own/own_err_string_pushed_twice.ts b/tslang/test/tester/own/own_err_string_pushed_twice.ts deleted file mode 100644 index e17ee4407..000000000 --- a/tslang/test/tester/own/own_err_string_pushed_twice.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Pins a conservative rule: one string pushed twice in one push is rejected under -mm=own, and -// not copied, because rc's two retains for it have no single use each (the `several` guard of -// copyForRetain). With the guard off, the double push compiles and is correct: each retain -// copies a different operand. If the rule is widened, this should become a positive. -function main() { - const s = "s" + 1; - const list: string[] = []; - list.push(s, s); - print(list[0], s); -} diff --git a/tslang/test/tester/own/own_string_pushed_twice.ts b/tslang/test/tester/own/own_string_pushed_twice.ts new file mode 100644 index 000000000..622a0ff50 --- /dev/null +++ b/tslang/test/tester/own/own_string_pushed_twice.ts @@ -0,0 +1,20 @@ +// One string pushed twice in one push: rc's two retains for it each copy a different operand, the +// first after the retain that is still the string (copyForRetain takes the nearest use when there are +// several, spec 71). It was rejected as a use after a move. +function churn() { + const hold: string[] = []; + for (let i = 0; i < 64; i++) { + hold.push("churn" + i); + } +} + +function main() { + const s = "s" + 1; + const list: string[] = []; + list.push(s, s); + churn(); + assert(list[0] == "s1" && list[1] == "s1", "two copies"); + assert(s == "s1", "the string itself"); + print(list[0], s); + print("done."); +} From d7739d178828626b4a76b965fb217fb7cc49d9e3 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 30 Oct 2026 21:28:15 +0000 Subject: [PATCH 2/5] -mm=own: elements taken out of a rest parameter; a double free on `list.push(local)` closed The array a caller gives a rest parameter borrows its elements when they are the caller's (spec 49), but a `pop` or `shift` of it was a value of the function's own: `this.data.push(args.shift())` compiled, and `list.push(item)` freed `item` twice, as did `const first = items.shift()` dropped. - A function that takes an element out of its rest parameter and keeps it keeps the parameter: its callers move what they give into the array (a local is then moved), and the function releases the emptied array at its exits, as it releases a parameter kept on some paths. - An element taken out of a rest parameter the function does not keep is not its own, and the take is an error: read it by its index instead. This is how an Array of objects pushes, unshifts and splices under own. Tests: own_rest_takes (own, no counting), own_err_rest_take_dropped, own_err_rest_take_used_after. Release ctest 6462/6462. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/OwnershipFacts.h | 33 ++++++++- .../TypeScript/OwnershipInferenceClosures.cpp | 14 ++++ .../lib/TypeScript/OwnershipInferencePass.cpp | 1 + .../lib/TypeScript/OwnershipInferencePass.h | 5 ++ .../lib/TypeScript/OwnershipSignaturePass.cpp | 19 +++++ tslang/test/tester/CMakeLists.txt | 4 +- .../tester/own/own_err_rest_take_dropped.ts | 13 ++++ .../own/own_err_rest_take_used_after.ts | 15 ++++ tslang/test/tester/own/own_rest_takes.ts | 72 +++++++++++++++++++ 9 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/own/own_err_rest_take_dropped.ts create mode 100644 tslang/test/tester/own/own_err_rest_take_used_after.ts create mode 100644 tslang/test/tester/own/own_rest_takes.ts diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index fb09fa464..a1c4eee1b 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -511,10 +511,41 @@ inline bool isLiteral(mlir::Operation *def) // survive the affine lowering), or another own module's `..new` (OWN_FRESH_RESULT_ATTR_NAME). A // declared callee, an indirect call, a parameter, a load, a value merged from branches, or a result // that borrows an argument is not fresh. +// The rest parameter (`...args`) whose local `slot` is: the last argument of a function whose type +// takes a rest. Null for any other slot. +inline mlir::BlockArgument restParameterOf(mlir::Value slot) +{ + auto varOp = slot.getDefiningOp(); + auto argument = varOp && varOp.getInitializer() ? mlir::dyn_cast(varOp.getInitializer()) + : mlir::BlockArgument(); + if (!argument || argument.getArgNumber() + 1 != argument.getOwner()->getNumArguments()) + { + return {}; + } + + auto funcOp = mlir::dyn_cast(argument.getOwner()->getParentOp()); + auto funcType = funcOp ? mlir::dyn_cast(funcOp.getFunctionType()) : mlir_ts::FunctionType(); + return funcType && funcType.isVarArg() ? argument : mlir::BlockArgument(); +} + +// An element taken out (`pop`, `shift`) of a rest parameter its function does not keep (spec 72): the +// array a caller gives a rest parameter only borrows its elements when they are the caller's (spec 49), +// so what comes out of it is a borrow too, not a value of the function's own. +inline bool takenOutOfBorrowedRest(mlir::Operation *def) +{ + if (!mlir::isa(def)) + { + return false; + } + + auto rest = restParameterOf(def->getOperand(0)); + return rest && !llvm::is_contained(ownedParams(rest.getOwner()->getParentOp()), static_cast(rest.getArgNumber())); +} + inline bool isFresh(mlir::Value value) { auto *def = value.getDefiningOp(); - if (!def || resultBorrows(def) >= 0) + if (!def || resultBorrows(def) >= 0 || takenOutOfBorrowedRest(def)) { return false; } diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index aa3fda448..a6b86dc69 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -582,6 +582,20 @@ namespace own_inference }); } + void OwnershipInferencePass::checkRestTakes() + { + getFunction().walk([&](mlir::Operation *op) { + if (!takenOutOfBorrowedRest(op) || !reporting()) + { + return; + } + + op->emitError("an element taken out of a rest parameter is the caller's: -mm=own lets a function take one " + "only when it keeps what it takes; read it by its index instead"); + signalPassFailure(); + }); + } + void OwnershipInferencePass::checkBoundedResults() { getFunction().walk([&](mlir::Operation *call) { diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 8f3778ee6..197d0cb87 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -233,6 +233,7 @@ namespace own_inference decideCells(); checkBorrowedReads(); checkBoundedResults(); + checkRestTakes(); checkBorrowingRecords(); checkRecordResults(); toErase.insert(fieldBorrowReleases.begin(), fieldBorrowReleases.end()); diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 922b73434..b878ad5a5 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -307,6 +307,11 @@ class OwnershipInferencePass // uses: the state object's release gives back nothing it borrows. void checkBoundedResults(); + // An element taken out (`pop`, `shift`) of a rest parameter the function does not keep (spec 72): + // a caller's array may only borrow the elements it gives, so what comes out is the caller's. A + // function that keeps what it takes keeps the parameter, and its callers give the elements up. + void checkRestTakes(); + // The ends of a capture box given to a call with a bounded result: each release of a closure on // it (the box goes with its last), and each end of what a field of it was filled from. Reports // and returns false when a use of the result comes after one. diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 2643494ed..e817e1c3b 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -882,6 +882,16 @@ namespace own_signature kept = kept || keeps(use, used); }); } + + // an element taken out of a rest parameter and kept (`this.data.push(args.shift())`): + // the function takes what its callers move into the array, so it keeps the array and + // they give their elements up (spec 72) + if (mlir::isa(slotUser) && restParameterOf(varOp.getResult())) + { + forEachUse(slotUser->getResult(0), [&](mlir::Operation *use, mlir::Value used) { + kept = kept || keeps(use, used); + }); + } } } @@ -929,8 +939,10 @@ namespace own_signature { // the statements that keep the parameter, as decideParam sees a move llvm::SmallVector takers; + auto rest = false; for (auto varOp : parameterSlotsOf(body.front().getArgument(index))) { + rest = rest || restParameterOf(varOp.getResult()); for (auto *slotUser : varOp.getResult().getUsers()) { if (auto loadOp = mlir::dyn_cast(slotUser)) @@ -945,6 +957,13 @@ namespace own_signature } } + // a rest parameter kept only for the elements taken out of it (spec 72): the array itself is + // never taken, so the function releases it + if (takers.empty() && rest) + { + continue; + } + // a parameter kept only through what this pass cannot see (a mixed return): as before auto everyPath = takers.empty() || llvm::all_of(exits, [&](mlir::Operation *exit) { return exit && llvm::any_of(takers, [&](mlir::Operation *taker) { return taker && dominance.dominates(taker, exit); }); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 1d824ceda..26cc4da31 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4089,7 +4089,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures own_interface_generic_method own_back_reference own_field_function_result own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot - own_any_copies own_array_copies own_string_pushed_twice) + own_any_copies own_array_copies own_string_pushed_twice own_rest_takes) 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. @@ -4826,6 +4826,8 @@ set(own_error_cases "own_err_keeper_called_through_value|:6:1: error: 'keep' keeps '#0' for good, but -mm=own cannot make every caller make it immortal: the function is called through a value" "own_err_shared_elements_object|:13:21: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]: an element has to be a value, a string, an any or a Shared handle. use 'Shared'" "own_err_shared_elements_inferred|:12:17: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]" + "own_err_rest_take_dropped|:6:19: error: an element taken out of a rest parameter is the caller's" + "own_err_rest_take_used_after|:14:11: error: '[^']*' is used here after its value was moved" "own_err_keeper_popped|:14:9: error: argument '[^']*' is given to 'Registry[.]register', which keeps it, but -mm=own cannot move it here" "own_err_generator_keeps_missing|:9:1: error: '@keeps' of 'mapped<[^']*' names 'iter', but its body keeps 'iter', 'f'" "own_err_generator_keeps_used_after|:15:11: error: '[^']*' is used here after its value was moved" diff --git a/tslang/test/tester/own/own_err_rest_take_dropped.ts b/tslang/test/tester/own/own_err_rest_take_dropped.ts new file mode 100644 index 000000000..a1458b510 --- /dev/null +++ b/tslang/test/tester/own/own_err_rest_take_dropped.ts @@ -0,0 +1,13 @@ +// -mm=own rejects: an element taken out of a rest parameter the function does not keep is the +// caller's (spec 72), and `first` would free `item`, which main still reads. It was accepted, and +// the program freed `item` twice. +class Item { constructor(public name: string) {} } +function dropFirst(...items: Item[]) { + const first = items.shift(); + print(first.name); +} +function main() { + const item = new Item("kept"); + dropFirst(item); + print(item.name); +} diff --git a/tslang/test/tester/own/own_err_rest_take_used_after.ts b/tslang/test/tester/own/own_err_rest_take_used_after.ts new file mode 100644 index 000000000..43e680894 --- /dev/null +++ b/tslang/test/tester/own/own_err_rest_take_used_after.ts @@ -0,0 +1,15 @@ +// -mm=own rejects: `push` keeps the elements it takes out of its rest parameter (spec 72), so `item` +// moves into the call, and main reads it after. It was accepted, and the program freed `item` twice. +class Item { constructor(public name: string) {} } +class List { + data: Item[] = []; + push(...args: Item[]) { + while (args.length > 0) this.data.push(args.shift()); + } +} +function main() { + const list = new List(); + const item = new Item("a"); + list.push(item); + print(item.name); +} diff --git a/tslang/test/tester/own/own_rest_takes.ts b/tslang/test/tester/own/own_rest_takes.ts new file mode 100644 index 000000000..54ab18b5a --- /dev/null +++ b/tslang/test/tester/own/own_rest_takes.ts @@ -0,0 +1,72 @@ +// A function that takes the elements out of its rest parameter and keeps them keeps the parameter +// (spec 72): its callers move what they give into the array, it moves each out (`shift`, `pop`), and +// it releases the emptied array. An Array-like class of objects pushes, unshifts and splices that +// way. Each value is read after churn() has reused anything freed too early. +class Item { + constructor(public name: string) {} +} + +class List { + data: T[] = []; + + push(...args: T[]) { + while (args.length > 0) this.data.push(args.shift()); + return this.data.length; + } + + unshift(...args: T[]) { + while (args.length > 0) this.data.unshift(args.pop()); + return this.data.length; + } + + // the removed elements are moved out, not read: each is swapped to the end, the first last, and + // popped off in order + splice(start: int, count: int, ...items: T[]) { + const last = this.data.length - 1; + for (let k = 0; k < count; k++) { + for (let j = start; j < last - k; j++) { + [this.data[j], this.data[j + 1]] = [this.data[j + 1], this.data[j]]; + } + } + + const removed: T[] = []; + for (let k = 0; k < count; k++) removed.push(this.data.pop()); + + for (let i = 0; items.length > 0; i++) this.data.splice(start + i, 0, items.shift()); + + return removed; + } +} + +function churn() { + const hold: Item[] = []; + for (let i = 0; i < 64; i++) hold.push(new Item("churn" + i)); +} + +function names(list: List) { + let s = ""; + for (const item of list.data) s += item.name; + return s; +} + +function main() { + const list = new List(); + list.push(new Item("a"), new Item("b"), new Item("c")); + + // a local moves into the call + const d = new Item("d"); + list.push(d); + churn(); + assert(names(list) == "abcd", "pushed"); + + list.unshift(new Item("p"), new Item("q")); + churn(); + assert(names(list) == "pqabcd", "unshifted"); + + const removed = list.splice(2, 2, new Item("x")); + churn(); + assert(removed.length == 2 && removed[0].name == "a" && removed[1].name == "b", "removed"); + assert(names(list) == "pqxcd", "spliced"); + + print("done."); +} From cb9784f21438b3eb5bdc39c26b49d5d81212da65 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 30 Oct 2026 21:38:38 +0000 Subject: [PATCH 3/5] -mm=own: @sharesElements - a method that would share an element is an error where it is called A generic class's methods are all made with it, so Array failed under own on slice, concat, fill, filter and the others that give an element a second place, though nothing called them. Such a method or function says `@sharesElements`: - MLIRGen marks what it makes for a type argument that owns a block of its own and is not a string, an `any` or a handle (OWN_CANNOT_SHARE_ATTR_NAME): a fact of the types, the same in every model. - The own signature pass, first, makes its body a stop (an assert and a default return), keeping its vtable slot. What the removed body made for itself - a generator's `next`, named in its constant state record - goes with it once nothing else refers to it, and so do its own markers. - Inference reports a call or a reference to it: "'slice' would give an element of type 'Item' a second owner, which -mm=own cannot do; hold the elements as 'Shared'". Spec 71-73 written for this branch (any copies and @copies, rest-parameter takes, this). Tests: own_shares_elements (own, rc, gc, none, no counting), own_err_shares_elements_called. Release ctest 6466/6466. Co-Authored-By: Claude Opus 5.5 --- .../2026-09-24-own-memory-model-design.md | 89 +++++++++++++++++++ tslang/include/TypeScript/Defines.h | 7 ++ tslang/lib/TypeScript/LowerToLLVM.cpp | 3 +- tslang/lib/TypeScript/MLIRGenImpl.h | 23 +++++ .../TypeScript/OwnershipInferenceClosures.cpp | 40 +++++++++ .../lib/TypeScript/OwnershipInferencePass.cpp | 1 + .../lib/TypeScript/OwnershipInferencePass.h | 4 + .../lib/TypeScript/OwnershipSignaturePass.cpp | 87 ++++++++++++++++++ tslang/test/tester/CMakeLists.txt | 3 +- .../own/own_err_shares_elements_called.ts | 19 ++++ tslang/test/tester/own/own_shares_elements.ts | 41 +++++++++ 11 files changed, 315 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/own/own_err_shares_elements_called.ts create mode 100644 tslang/test/tester/own/own_shares_elements.ts 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 8d5f0a184..fba162415 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 @@ -5522,3 +5522,92 @@ objects with an arrow field each run in a flat 49 MB under own. Not here: an arrow field reading a getter (`fn = () => this.prop` with `get prop()`) fails in every model, because its arrow is kept as returning void (PR #744). A call through a field returning a string, under `--no-default-lib`, is `borrows a field but is used here after ...` whatever the field holds, as before. + +## 71. Copies of `any`, of arrays in `@copies`, and generators over immortal globals, 2026-10-30 + +The default library's untyped Map (`new Map()` is `Map`) and `reduceRight` over arrays of +arrays were `not own` by design (§49, the containers ruling of 2026-10-26). USER decisions, 2026-10-30: +an `any` is copied as a string is (not counted: a counted box would put counting in every own program +that catches, since a caught value is an `any`); an `any` that holds an object stops the program where +it would be copied; an array is copied only in a function that says so. + +- **An `any` is a copyable value** (`isCopyableValue`): §22's dry run, then copies for the retains it + could not erase, now takes an `any` beside a string. `ts.StringCopy` of an `any` lowers to a new box + of the same bytes (`{size, tag, data}`). A payload whose descriptor has no release routine owns + nothing and is copied with them; a string payload is copied in turn. Any other payload (a class or + object literal, an interface, a closure, an array or tuple holding blocks) has one owner, the box: the + copy stops the program, as a failed assert does, with "-mm=own cannot copy an 'any' that holds an + object; give the object a Shared" (`own_any_object_copy_stops`). Nothing counts. +- **`@sharedElements` takes `any`** (and `unknown`, the same box): its elements are copied as strings + are. An object still goes in as Shared, and the message names `any` among what may. +- **The nearest use** (`copyForRetain`): a retain whose value has several consuming uses (`f(s); f(s)` + boxing `s` twice, `push(s, s)`) copies for the first use after it in its block, as rc retained each + beside its use. `own_err_string_pushed_twice` pinned the old rule and asked to become a positive when + it widened: it is `own_string_pushed_twice`. +- **A constant boxed or printed is a block** (`isLiteral`): `42` and a number cast to a string were + taken for literals that hold no block, so their release stayed after a move and `k.keep(42)` freed the + box twice. On main too. +- **`@copies`** (`OWN_DECLARED_COPIES_ATTR_NAME`, no arguments): in a function that says it, an array + whose elements own nothing (`number[]`, `isCopyableArray`) is copied as well: a new header over a copy + of the data block. A copy of an array can be told from it (a push to one is not a push to the other), + so it is not made anywhere else: `own_err_field_alias` and `own_err_two_owners` stay errors. The + default library's `reduce` and `reduceRight` say it: with no initial value their accumulator starts as + a copy of an element (`own_array_copies`). +- **A generator over immortal globals** (§25) may be kept anywhere (`checkBoundedResults`): `const it = + map.values()` at the top of a script. At least one bounded argument has to be one; a callback that + holds no block says nothing of the array `.map` reads (`own_err_generator_map_outlives`). + +`own_any_copies` boxes one string into two keeping calls, fresh boxes into two, and strings and numbers +into a @sharedElements container, under own, rc, gc and none; own emits no counting. Not here: a +`const` string boxed once into a call that keeps it (`const s = "a" + "b"; c.has(s)`) is still `takes a +second reference`, on main too. + +## 72. Elements taken out of a rest parameter, 2026-10-30 + +The array a caller gives a rest parameter borrows its elements when they are the caller's (§49). A +`pop` or `shift` of it was nevertheless a value of the function's own (`isFresh`): `this.data.push( +args.shift())` compiled, and `list.push(item)` freed `item` twice, as did `const first = +items.shift()` dropped. On main. + +- **Taking and keeping keeps the parameter** (the signature pass's `localOwnedParams`): a `pop` or + `shift` of a rest parameter (`restParameterOf`: the last argument of a function whose type takes a + rest) whose result is kept makes the function keep the parameter. Its callers then move what they + give into the array, as for any kept parameter (`classifyArgumentArrays` leaves an array given to a + keeping call alone), so a local given is moved (`own_err_rest_take_used_after`). +- **The emptied array is released** (`takenOnEveryPath`): nothing takes the array itself, so the + function releases it at its exits, as it releases a parameter kept on some paths only. +- **Taking without keeping is an error** (`checkRestTakes`, `takenOutOfBorrowedRest`): what comes out of + a rest parameter the function does not keep is the caller's. "an element taken out of a rest parameter + is the caller's: -mm=own lets a function take one only when it keeps what it takes; read it by its + index instead" (`own_err_rest_take_dropped`). + +`own_rest_takes` pushes, unshifts and splices objects into an Array-like class (fresh ones and a +local), under own, rc, gc and none; own emits no counting. The default library's Array does the +same. Not here: a function that *declares* `@keeps` on such a parameter skips the release +(`declaresCallerFacts`), so the library relies on inference, not the decorator. + +## 73. Methods that share elements: `@sharesElements`, 2026-10-30 + +USER decision, 2026-10-30: the default library's Array owns its objects (no `@sharedElements` on +Array; Map and Set keep it), and a method that gives an element a second place is an error where it is +called. All methods of a generic class are made with it, so `copyWithin`, `slice`, `concat`, `fill`, +`filter`, `filter2`, `toSorted`, `toReversed`, `with`, `entries`, `values` and the iterator failed for +Array whether called or not. + +- **`@sharesElements`** (no arguments) on such a method or function: MLIRGen marks what it makes + (`OWN_CANNOT_SHARE_ATTR_NAME`, the type printed) when a type argument owns a block of its own and is + not a string, an `any` or a handle. That is a fact of the types, the same in every model (§4.3), and + only own reads it. +- **The body becomes a stop** (the signature pass, first, `stubCannotShare`): `assert(false, ...)` and + a default return, so nothing analyses it, and it keeps its place in the vtable. The functions the + removed body made for itself (a generator's `next`, named in its constant state record) go with it + once nothing else refers to them. What the declaration said of its parameters (`@borrows`) goes too. +- **A call is the error** (`checkCannotShare`): a call or reference to a marked function, by `callee` + or `identifier`: "'slice' would give an element of type 'Item' a second owner, which -mm=own cannot + do; hold the elements as 'Shared'". + +`own_shares_elements` makes a class with a marked method for objects (the rest works) and for numbers +(the method works), under own, rc, gc and none; `own_err_shares_elements_called` calls it for objects. +The default library marks the functions above in `__Array` and in Array; Array's push, unshift +and splice move elements as §72 says, and splice removes by swapping each to the end and popping it. + diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 84eaf7746..5b463ad7a 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -374,6 +374,13 @@ // one: reduce's accumulator, which starts as an element. The other models ignore it. A unit attribute. #define COPIES_DECORATOR "copies" #define OWN_DECLARED_COPIES_ATTR_NAME "ts.own_declared_copies" +// `@sharesElements`, on a generic method or function that gives an element a second place (`slice`, +// `concat`, `fill`): made for a type argument that owns a block of its own and is not a string, an +// `any` or a Shared (an object, an array), it is marked with that type (OWN_CANNOT_SHARE_ATTR_NAME, +// a string attribute). -mm=own cannot give such an element a second owner (own spec 73): the body +// stops the program if it is ever reached, and a call to it is an error. The other models ignore it. +#define SHARES_ELEMENTS_DECORATOR "sharesElements" +#define OWN_CANNOT_SHARE_ATTR_NAME "ts.own_cannot_share" // `@immortalizes` names the parameters the function keeps for good, in an append-only global (a // keeper, docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): its callers make each // argument immortal. Checked against a body; trusted on a declaration, a C function that keeps a diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 8cfca7e90..755ad4e68 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -2369,7 +2369,8 @@ struct FuncOpLowering : public TsLlvmPattern 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_IMMORTALIZES_ATTR_NAME || name == OWN_DECLARED_COPIES_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/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 139c7f932..59e303015 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3446,6 +3446,29 @@ class MLIRGenImpl return; } + // `@sharesElements` names nothing: made for an element type that owns a block of its own, + // the function is marked with it (spec 73) + if (name == SHARES_ELEMENTS_DECORATOR) + { + MLIRTypeHelper mth(builder.getContext(), compileOptions); + for (auto &entry : genContext.typeParamsWithArgs) + { + auto type = mth.stripLiteralType(std::get<1>(entry.getValue())); + if (!type || mlir::isa(type) || + MLIRTypeHelper::isSharedHandleType(type) || !mth.ownsHeapMemory(location, type)) + { + continue; + } + + if (llvm::none_of(attrs, [](mlir::NamedAttribute &attr) { return attr.getName() == OWN_CANNOT_SHARE_ATTR_NAME; })) + { + attrs.push_back({builder.getStringAttr(OWN_CANNOT_SHARE_ATTR_NAME), builder.getStringAttr(to_print(type))}); + } + } + + return; + } + // `@copies` names nothing either: it lets -mm=own copy an array in the body (spec 71) if (name == COPIES_DECORATOR) { diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index a6b86dc69..ac842603b 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -596,6 +596,46 @@ namespace own_inference }); } + void OwnershipInferencePass::checkCannotShare() + { + if (getFunction()->hasAttr(OWN_CANNOT_SHARE_ATTR_NAME)) + { + return; + } + + getFunction().walk([&](mlir::Operation *op) { + auto symbol = op->getAttrOfType("callee"); + if (!symbol) + { + symbol = op->getAttrOfType("identifier"); + } + + auto callee = symbol ? mlir::SymbolTable::lookupNearestSymbolFrom(op, symbol) : mlir_ts::FuncOp(); + auto elementType = callee ? callee->getAttrOfType(OWN_CANNOT_SHARE_ATTR_NAME) : mlir::StringAttr(); + if (!elementType || !reporting()) + { + return; + } + + // the method's own name: `Array>.slice` is `slice` + std::string name; + auto depth = 0; + for (auto c : callee.getSymName()) + { + depth += c == '<' ? 1 : c == '>' ? -1 : 0; + if (depth == 0 && c != '>') + { + name = c == '.' ? std::string() : name + c; + } + } + + op->emitError("'") << name << "' would give an element of type '" << elementType.getValue() + << "' a second owner, which -mm=own cannot do; hold the elements as 'Shared<" + << elementType.getValue() << ">'"; + signalPassFailure(); + }); + } + void OwnershipInferencePass::checkBoundedResults() { getFunction().walk([&](mlir::Operation *call) { diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index 197d0cb87..80dd0ab57 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -234,6 +234,7 @@ namespace own_inference checkBorrowedReads(); checkBoundedResults(); checkRestTakes(); + checkCannotShare(); checkBorrowingRecords(); checkRecordResults(); toErase.insert(fieldBorrowReleases.begin(), fieldBorrowReleases.end()); diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index b878ad5a5..9c389f5bb 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -312,6 +312,10 @@ class OwnershipInferencePass // function that keeps what it takes keeps the parameter, and its callers give the elements up. void checkRestTakes(); + // A call to, or a reference to, a function made for an element type it cannot give a second owner + // (`@sharesElements`, OWN_CANNOT_SHARE_ATTR_NAME, spec 73): `slice` of an Array. + void checkCannotShare(); + // The ends of a capture box given to a call with a bounded result: each release of a closure on // it (the box goes with its last), and each end of what a field of it was filled from. Reports // and returns false when a use of the result comes after one. diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index e817e1c3b..70673d198 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -8,9 +8,96 @@ namespace own_signature { + // A function made for an element type -mm=own cannot give a second owner (`@sharesElements`, spec + // 73): its body becomes a stop, so nothing analyses what it would do. It keeps its place in a + // vtable; a call to it is inference's error. + static void stubCannotShare(mlir::ModuleOp module) + { + llvm::SmallVector work; + module.walk([&](mlir_ts::FuncOp funcOp) { + if (funcOp->hasAttr(OWN_CANNOT_SHARE_ATTR_NAME) && !funcOp.getBody().empty()) + { + work.push_back(funcOp); + } + }); + + llvm::SmallPtrSet stubbed; + while (!work.empty()) + { + auto funcOp = work.pop_back_val(); + if (!stubbed.insert(funcOp).second) + { + continue; + } + + auto elementType = funcOp->getAttrOfType(OWN_CANNOT_SHARE_ATTR_NAME); + auto &body = funcOp.getBody(); + + // what the body made for itself - a generator's `next`, a closure - goes with it once + // nothing else refers to it + llvm::SetVector made; + // (a generator's state is a constant record that names its `next`) + funcOp.walk([&](mlir::Operation *op) { + op->getAttrDictionary().walk([&](mlir::FlatSymbolRefAttr symbol) { + if (auto callee = module.lookupSymbol(symbol); callee && callee != funcOp) + { + made.insert(callee); + } + }); + }); + + auto *stub = new mlir::Block(); + for (auto argument : body.front().getArguments()) + { + stub->addArgument(argument.getType(), argument.getLoc()); + } + + body.dropAllReferences(); + while (!body.empty()) + { + body.front().erase(); + } + + body.push_back(stub); + + // 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}) + { + funcOp->removeAttr(name); + } + + auto location = funcOp.getLoc(); + mlir::OpBuilder builder(stub, stub->begin()); + auto never = builder.create(location, mlir_ts::BooleanType::get(builder.getContext()), + builder.getBoolAttr(false)); + std::string message = "-mm=own cannot give an element of type '" + elementType.getValue().str() + + "' a second owner: '" + funcOp.getSymName().str() + "'"; + builder.create(location, never, mlir::Value(), builder.getStringAttr(message)); + llvm::SmallVector results; + for (auto type : funcOp.getFunctionType().getResults()) + { + results.push_back(builder.create(location, type)); + } + + builder.create(location, results); + + for (auto made : made) + { + if (!made.getBody().empty() && mlir::SymbolTable::symbolKnownUseEmpty(made, module)) + { + made->setAttr(OWN_CANNOT_SHARE_ATTR_NAME, elementType); + work.push_back(made); + } + } + } + } + void OwnershipSignaturePass::runOnOperation() { auto module = getOperation(); + stubCannotShare(module); module.walk([&](mlir_ts::FuncOp funcOp) { functions[funcOp.getSymName()] = funcOp; }); module.walk([&](mlir_ts::GlobalOp globalOp) { globals[globalOp.getSymName()] = globalOp; }); module.walk([&](mlir_ts::AddressOfOp addressOfOp) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 26cc4da31..512fe0bdf 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4089,7 +4089,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures own_interface_generic_method own_back_reference own_field_function_result own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot - own_any_copies own_array_copies own_string_pushed_twice own_rest_takes) + own_any_copies own_array_copies own_string_pushed_twice own_rest_takes own_shares_elements) 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. @@ -4828,6 +4828,7 @@ set(own_error_cases "own_err_shared_elements_inferred|:12:17: error: -mm=own: 'Bag' cannot hold 'Node' [(]its 'T'[)]" "own_err_rest_take_dropped|:6:19: error: an element taken out of a rest parameter is the caller's" "own_err_rest_take_used_after|:14:11: error: '[^']*' is used here after its value was moved" + "own_err_shares_elements_called|:18:11: error: 'twice' would give an element of type 'Item' a second owner" "own_err_keeper_popped|:14:9: error: argument '[^']*' is given to 'Registry[.]register', which keeps it, but -mm=own cannot move it here" "own_err_generator_keeps_missing|:9:1: error: '@keeps' of 'mapped<[^']*' names 'iter', but its body keeps 'iter', 'f'" "own_err_generator_keeps_used_after|:15:11: error: '[^']*' is used here after its value was moved" diff --git a/tslang/test/tester/own/own_err_shares_elements_called.ts b/tslang/test/tester/own/own_err_shares_elements_called.ts new file mode 100644 index 000000000..6ca35a71d --- /dev/null +++ b/tslang/test/tester/own/own_err_shares_elements_called.ts @@ -0,0 +1,19 @@ +// -mm=own rejects: `twice` says `@sharesElements`, and made for an object element type it would give +// each element a second owner (spec 73). The call is the error; the method itself is stubbed. +class Item { + constructor(public name: string) {} +} +class Bag { + items: T[] = []; + @sharesElements + twice() { + const both: T[] = []; + for (const v of this.items) both.push(v); + for (const v of this.items) both.push(v); + return both; + } +} +function main() { + const bag = new Bag(); + print(bag.twice().length); +} diff --git a/tslang/test/tester/own/own_shares_elements.ts b/tslang/test/tester/own/own_shares_elements.ts new file mode 100644 index 000000000..6e611da57 --- /dev/null +++ b/tslang/test/tester/own/own_shares_elements.ts @@ -0,0 +1,41 @@ +// A method that gives an element a second place says `@sharesElements` (spec 73). Made for an element +// type that owns a block of its own (an object), -mm=own stubs it and the rest of the class works; made +// for numbers, it works as it is. (A generator a stubbed function makes goes with it: the default +// library's Array.values.) +class Item { + constructor(public name: string) {} +} + +class Bag { + items: T[] = []; + + add(item: T) { + this.items.push(item); + } + + get(i: int) { + return this.items[i]; + } + + @sharesElements + twice() { + const both: T[] = []; + for (const v of this.items) both.push(v); + for (const v of this.items) both.push(v); + return both; + } +} + +function main() { + const bag = new Bag(); + bag.add(new Item("a")); + bag.add(new Item("b")); + assert(bag.get(1).name == "b", "objects without the sharing methods"); + + const numbers = new Bag(); + numbers.add(1); + numbers.add(2); + assert(numbers.twice().length == 4, "numbers share"); + + print("done."); +} From c1ddef1889ae50552e6fd65f974a8fdf3ffa9fbb Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 30 Oct 2026 22:05:28 +0000 Subject: [PATCH 4/5] -mm=own: a number taken out of a rest parameter is a copy; a stubbed body keeps its own debug scope - takenOutOfBorrowedRest held for any pop/shift of a rest parameter, so a function that summed `...args: number[]` with args.pop() was an error under own (DefaultLib array_every and array_constructors_overload). Only an element that owns a block is the caller's. - stubCannotShare gave the new body the function's location; with --di LLVM said the !dbg attachment pointed at the wrong subprogram. It takes the old body's first location. Tests: own_rest_takes sums numbers out of a rest parameter. Release ctest 6466/6466. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/OwnershipFacts.h | 5 ++++- tslang/lib/TypeScript/OwnershipSignaturePass.cpp | 5 ++++- tslang/test/tester/own/own_rest_takes.ts | 9 +++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index a1c4eee1b..23a6c9f5c 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -531,9 +531,12 @@ inline mlir::BlockArgument restParameterOf(mlir::Value slot) // An element taken out (`pop`, `shift`) of a rest parameter its function does not keep (spec 72): the // array a caller gives a rest parameter only borrows its elements when they are the caller's (spec 49), // so what comes out of it is a borrow too, not a value of the function's own. +inline bool ownsHeap(mlir::Value value); + inline bool takenOutOfBorrowedRest(mlir::Operation *def) { - if (!mlir::isa(def)) + // a number taken out is a copy of it, whoever's the array is + if (!mlir::isa(def) || !ownsHeap(def->getResult(0))) { return false; } diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 70673d198..2021be678 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -46,6 +46,10 @@ namespace own_signature }); }); + // where the body began: a debug location of this function's own scope (the function's location + // may be the instantiation's, another subprogram's) + auto location = body.front().empty() ? funcOp.getLoc() : body.front().front().getLoc(); + auto *stub = new mlir::Block(); for (auto argument : body.front().getArguments()) { @@ -68,7 +72,6 @@ namespace own_signature funcOp->removeAttr(name); } - auto location = funcOp.getLoc(); mlir::OpBuilder builder(stub, stub->begin()); auto never = builder.create(location, mlir_ts::BooleanType::get(builder.getContext()), builder.getBoolAttr(false)); diff --git a/tslang/test/tester/own/own_rest_takes.ts b/tslang/test/tester/own/own_rest_takes.ts index 54ab18b5a..4da75670a 100644 --- a/tslang/test/tester/own/own_rest_takes.ts +++ b/tslang/test/tester/own/own_rest_takes.ts @@ -38,6 +38,13 @@ class List { } } +// a number taken out of a rest parameter is a copy: the function need not keep it +function sum(...args: number[]) { + let s = 0; + while (args.length > 0) s += args.pop(); + return s; +} + function churn() { const hold: Item[] = []; for (let i = 0; i < 64; i++) hold.push(new Item("churn" + i)); @@ -68,5 +75,7 @@ function main() { assert(removed.length == 2 && removed[0].name == "a" && removed[1].name == "b", "removed"); assert(names(list) == "pqxcd", "spliced"); + assert(sum(1, 2, 3) == 6, "sum"); + print("done."); } From 9eb5464929ac16d86e1cf8f13a40e7a81486cc24 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Fri, 30 Oct 2026 22:40:44 +0000 Subject: [PATCH 5/5] -mm=own: a rest parameter declared kept (`@keeps("args")`) is released once emptied A function whose rest parameter is inferred kept (spec 72) releases the emptied array at its exits, but one that says `@keeps("args")` never did: pinFacts set OWN_PARAMS_RELEASED only for functions without declared caller facts, so every call leaked its rest array. A declared keep of the rest parameter is now released the same way an inferred one is; other declared keeps are unchanged. Tests: own_rest_keeps_declared (own, no counting, rc, gc, none) and test-own-rest-keeps-declared-released, which reads the IR (fails before the fix). Release ctest 6476/6476. Co-Authored-By: Claude Opus 5.5 --- .../lib/TypeScript/OwnershipSignaturePass.cpp | 9 ++++- tslang/test/tester/CMakeLists.txt | 12 +++++- .../test/tester/own-rest-keeps-declared.cmake | 28 +++++++++++++ .../tester/own/own_rest_keeps_declared.ts | 39 +++++++++++++++++++ 4 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 tslang/test/tester/own-rest-keeps-declared.cmake create mode 100644 tslang/test/tester/own/own_rest_keeps_declared.ts diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 2021be678..1fcc41db3 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -1309,11 +1309,16 @@ namespace own_signature setFacts(funcOp, effective); funcOp->removeAttr(OWN_FACTS_LOST_ATTR_NAME); funcOp->removeAttr(OWN_PARAMS_RELEASED_ATTR_NAME); - // a signature's `@keeps` is checked against the body as it is (checkDeclared) + // a signature's `@keeps` is checked against the body as it is (checkDeclared). But a rest + // parameter it names is the array the callers move their elements into (spec 72): the body + // takes the elements out, and the emptied array is released as an inferred keep's is + auto ownFunc = mlir::dyn_cast(funcOp); + auto funcType = ownFunc ? mlir::dyn_cast(ownFunc.getFunctionType()) : mlir_ts::FunctionType(); + auto restIndex = funcType && funcType.isVarArg() ? static_cast(funcType.getNumInputs()) - 1 : -1; llvm::SmallVector released; for (auto index : effective.owned) { - if (!declaresCallerFacts(funcOp) && !llvm::is_contained(takenParams.lookup(funcOp), index)) + if ((!declaresCallerFacts(funcOp) || index == restIndex) && !llvm::is_contained(takenParams.lookup(funcOp), index)) { released.push_back(index); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 512fe0bdf..a5ae26f5a 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4089,7 +4089,8 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures own_interface_generic_method own_back_reference own_field_function_result own_callback_shapes own_callback_extended own_callback_interface own_generic_specializations own_callback_cast own_callback_interface_slot - own_any_copies own_array_copies own_string_pushed_twice own_rest_takes own_shares_elements) + own_any_copies own_array_copies own_string_pushed_twice own_rest_takes own_shares_elements + own_rest_keeps_declared) 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. @@ -4127,7 +4128,7 @@ foreach(keeps_mm rc gc none) own_generator_take own_rest_array_borrows own_string_copies own_captured_string_callback own_callback_and_call own_callback_captured own_literal_closures own_literal_variable_closures own_temporary_field_take own_union_narrowed_calls own_named_field_take own_let_field_take own_literal_captures own_literal_object_captures own_literal_interface_captures own_literal_let_captures own_interface_generic_method own_back_reference own_field_function_result own_callback_shapes own_callback_extended own_callback_interface - own_generic_specializations own_callback_cast own_callback_interface_slot) + own_generic_specializations own_callback_cast own_callback_interface_slot own_rest_keeps_declared) 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() @@ -4193,6 +4194,13 @@ add_test(NAME test-own-caught-value-call set_tests_properties(test-own-caught-value-call PROPERTIES PASS_REGULAR_EXPRESSION "ts.Func" FAIL_REGULAR_EXPRESSION "error|Stack dump") +# A rest parameter its function says it keeps (`@keeps`) is released once emptied under own, as an +# inferred keep's is (spec 72); no run can see the leak, so the IR is read. +add_test(NAME test-own-rest-keeps-declared-released + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/own/own_rest_keeps_declared.ts" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-rest-keeps-declared.cmake") + # A read through an interface field a getter may fill is freed after its last use under own, on the # getter's path only (own_interface_getter_read.ts): the release is placed by inference. add_test(NAME test-own-interface-getter-read-released diff --git a/tslang/test/tester/own-rest-keeps-declared.cmake b/tslang/test/tester/own-rest-keeps-declared.cmake new file mode 100644 index 000000000..02fffd54d --- /dev/null +++ b/tslang/test/tester/own-rest-keeps-declared.cmake @@ -0,0 +1,28 @@ +# Under own a rest parameter its function says it keeps (`@keeps("args")`, own_rest_keeps_declared.ts) is +# released at the function's exit once its elements are moved out, as an inferred keep's is (spec 72). No run +# shows a leak, so the IR is read (--emit=mlir-affine): `List.push` releases its rest array before it returns. +cmake_minimum_required(VERSION 3.17.3) +execute_process(COMMAND "${TSLANG}" --emit=mlir-affine --no-default-lib -mm=own "${FILE}" + OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result) +# the IR is printed to stderr +string(APPEND out "${err}") +if(NOT result EQUAL 0) + message(FATAL_ERROR "tslang failed (${result}):\n${out}") +endif() + +# the body of `List.push`, from its `ts.Func` to the next one +string(FIND "${out}" "ts.Func @List.push " begin) +if(begin EQUAL -1) + message(FATAL_ERROR "no function `List.push` in:\n${out}") +endif() +string(SUBSTRING "${out}" ${begin} -1 body) +string(SUBSTRING "${body}" 1 -1 rest) +string(FIND "${rest}" "ts.Func @" end) +if(NOT end EQUAL -1) + math(EXPR end "${end} + 1") + string(SUBSTRING "${body}" 0 ${end} body) +endif() + +if(NOT body MATCHES "\"ts[.]ReleaseSlot\"[(]%[0-9]+[)] : [(]!ts[.]ref 0) this.data.push(args.shift()); + return this.data.length; + } +} + +function churn() { + const hold: Item[] = []; + for (let i = 0; i < 64; i++) hold.push(new Item("churn" + i)); +} + +function main() { + const list = new List(); + list.push(new Item("a"), new Item("b")); + + // a local moves into the call + const c = new Item("c"); + list.push(c); + churn(); + + let s = ""; + for (const item of list.data) s += item.name; + assert(s == "abc", "pushed"); + + print("done."); +}