diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 5efd85439..12f2955b1 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -289,6 +289,40 @@ own now (`bokeh`, `calibrated_timestamps`, `shader_debugprintf`, `simple_compute `simple_pbr`), 143 of the 276 sources still fail. Regression tests `tslang/test/tester/tests/00tslang_issue_53.ts` (every model) and `own/own_err_kept_by_constructor_reset.ts`. +54 (a value merged from a `?:` whose branches each bring a fresh value or null: `const pipeline = +loaded ? device.createPipelineFromDesc(layout, desc) : null; ... this.blitPipelines.push(pipeline)` in +`core/nri_donut_textures.ts`, refused "is merged from several branches; -mm=own cannot prove which one +owns it yet") is fixed. Such a merge is the function's own when every way into it brings a fresh value +that nothing else uses (a call's result, a `new`, another such merge) or null or undefined: rc gave it the +one reference it holds. It moves like the call's result itself, and 50, 52 and 53 follow it after the +move. In a loop's body each iteration's merge is a value of its own. Two checks took a block argument, +which has no defining op, for a value made before the loop: the release at the end of one iteration +looked like a second release of the next iteration's value, and a move in the body looked like a move +of a value made outside the loop. They now take the argument as made where its block starts. A merge at +a loop's head (a value carried from one iteration into the next) is not covered. A merge that takes a +local (`c ? local : null`), a merge moved twice, and one made before a loop and moved in it are still +refused. `nri_donut_textures.ts` is left with one error, which is its own: `new MipBlit(texture, ...)` +keeps `this.textures[t]` in a second object, a second owner (an index would do). Merge errors left in +the sweep: 3. Regression tests `tslang/test/tester/tests/00tslang_issue_54.ts` (every model) and +`own/own_err_merge_moved_twice.ts`. + +55 (an array literal of fields: `const directions = [this.dir, this.dir, this.right, this.right, this.up, +this.up]` in `core/donut_first_person_camera.ts`, `const pipelines = [this.a, this.b, this.c]` and +`for (const p of [this.a, this.b])` in the examples, refused "borrows a field and cannot be stored") is +fixed. An array literal that is only read (its length and its elements), held in a local or used as it +is, and whose elements are each a read out of a field or an element or a parameter, borrows its +elements while it is used, as the array a rest parameter is given already did (spec 49). Its release +gives back the array and not the elements, so the same field twice is fine. Every use of the array, +and of what is read out of it, is a use of each element: a field written, or a call that may write +it, before such a use is still refused, "borrows a field but is used here after it may be released +or overwritten". So is an array written, stored, returned, captured or given to a call, one with a +fresh element, or an element read out of it and stored. Spec section 80 has the rules. In the sweep, +array literals of fields refused went from 18 to 1 (`this.options = [...]` stores it: refused, rightly), +and `donut_first_person_camera.ts` is left with the two errors of a `let` that borrows a field and is +given a new array (`let dir = this.dir; ... dir = rotateAround(...)`). Regression tests +`tslang/test/tester/tests/00tslang_issue_55.ts` (every model, and as an exe) and +`own/own_err_borrowing_array_field_reset.ts`. + For native_ts_graphics, from the same sweep (its code, not the compiler): - `examples/dynamic_primitive_clipping.ts:223`, `desc.setDepthClip(clip)` with `clip` the loop's `int`, fails under every model since #846 (a number is not a `boolean` argument, TS2345). alpha127 still 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 299c6aeb1..6157ad039 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 @@ -5723,3 +5723,31 @@ and its declared `@keeps` and `@lends` apply, as to `obj.set(key, value)`. Found with it, under every model: the call lowered for an indexer's `set` had no result, also when `set` returns one (`set(key, value): this`), so the call disagreed with the function it calls and the lowering to LLVM crashed now and then. It has the setter's results now, unused. + +## 80. An array literal that borrows its elements, 2026-11-14 + +TSLANG_ISSUES 55. `const pipelines = [this.a, this.b, this.c]` and `for (const p of [this.a, this.b])` +were refused, "borrows a field and cannot be stored": an element of an array literal moved into the +array, and a field read cannot move. §49 had the borrowing array a rest parameter is given; this is +the same array held in a local or used as it is. + +`classifyLocalBorrowingArrays` takes a `ts.CreateArray` that is only read, and whose block-holding +elements are each a read out of a place (a field, an element) or of a parameter's slot, with no fresh +value among them: +- held in a local (`ts.Variable` initialized with it, not captured), the local is only read (its + `ts.RetainSlot` and `ts.ReleaseSlot`s aside), or used as it is with a `ts.Release` of its own; +- each read of it is a `ts.LengthOf`, or a `ts.ElementRef` that is only read; +- `walkRecord` of it finds nothing that keeps it and no return. + +Such an array is marked `OWN_BORROWING_ARRAY_ATTR_NAME`, rc's references for its elements go +(`fieldBorrowRetains`), and its releases are marked `OWN_SHALLOW_RELEASE_ATTR_NAME`: a `ts.Release` +or a `ts.ReleaseSlot` (lowered with `emitReleaseArrayShallow`) frees the array and not its elements, +so the same field twice is fine. Every use `walkRecord` found - of the array and of what is read out +of it - is a use of each element (`arrayElementUses`, read by `walkBorrowed`), so an element's source +written or released before any of them is the error it is for a field read held in a local; the +array's own release is not one. The array is one borrow: a use of it bounds every element, also one +it does not read. + +Not here: an array written (`push`, an element stored), stored, returned, captured or given to a +call (the call's array of §49 aside); a literal with a fresh element beside borrowed ones; a local's +value as an element (`[background, tile]`), whose bound is the local's own ends. diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 64241a2e6..645ccc767 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -786,7 +786,18 @@ class ReleaseSlotOpLowering : public TsLlvmPattern { OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); auto releaseSlot = [&]() { - orl.emitReleaseSlot(cast(op.getSlot().getType()).getElementType(), transformed.getSlot()); + auto elementType = cast(op.getSlot().getType()).getElementType(); + // a local array literal that only borrowed its elements (-mm=own's + // classifyLocalBorrowingArrays): the array goes, its elements stay with their owners + if (auto arrayType = dyn_cast(elementType); arrayType && op->hasAttr(OWN_SHALLOW_RELEASE_ATTR_NAME)) + { + TypeHelper th(rewriter); + auto header = rewriter.create(op->getLoc(), th.getPtrType(), transformed.getSlot()); + orl.emitReleaseArrayShallow(arrayType, header); + return; + } + + orl.emitReleaseSlot(elementType, transformed.getSlot()); }; // an interface's field filled by a setter has no slot: the setter lets go of what it held diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 300487f7d..4dfedecf5 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -6,6 +6,7 @@ #include "TypeScript/MLIRLogic/MLIRTypeHelper.h" #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" +#include "mlir/IR/Dominance.h" #include "mlir/Interfaces/ControlFlowInterfaces.h" #include "llvm/ADT/DenseMap.h" @@ -576,8 +577,106 @@ inline bool takenOutOfBorrowedRest(mlir::Operation *def) return rest && !llvm::is_contained(ownedParams(rest.getOwner()->getParentOp()), static_cast(rest.getArgNumber())); } +inline bool isFresh(mlir::Value value); + +// A value merged from branches (TSLANG 54): `const p = loaded ? device.create() : null`. It is the +// function's own when every way into the merge brings a fresh value that nothing else uses, or null +// or undefined, which holds no block - rc gave it the one reference the merge holds. Not across a +// loop: a block that reaches one of its own predecessors carries a value from one iteration into the +// next, which is not decided here. +inline bool isFreshMerge(mlir::BlockArgument argument, unsigned depth = 0) +{ + auto *block = argument.getOwner(); + if (block->isEntryBlock() || block->hasNoPredecessors() || depth > 8) + { + return false; + } + + // a loop header: a predecessor it dominates comes back to it (a merge inside a loop's body is + // fine - each iteration makes its own values) + mlir::DominanceInfo dominance(block->getParentOp()); + for (auto predecessor = block->pred_begin(); predecessor != block->pred_end(); ++predecessor) + { + if (dominance.dominates(block, *predecessor)) + { + return false; + } + + auto branchOp = mlir::dyn_cast((*predecessor)->getTerminator()); + if (!branchOp) + { + return false; + } + + auto operands = branchOp.getSuccessorOperands(predecessor.getSuccessorIndex()); + if (argument.getArgNumber() < operands.getProducedOperandCount()) + { + return false; + } + + auto incoming = operands[argument.getArgNumber()]; + if (!incoming) + { + return false; + } + + // null or undefined, seen through its casts + auto constant = incoming; + while (auto castOp = constant.getDefiningOp()) + { + constant = castOp.getIn(); + } + + if (constant.getDefiningOp() || constant.getDefiningOp() || + constant.getDefiningOp()) + { + continue; + } + + if (auto nested = mlir::dyn_cast(incoming)) + { + if (!nested.hasOneUse() || !isFreshMerge(nested, depth + 1)) + { + return false; + } + + continue; + } + + // the fresh value and the views it reaches the branch through, used by nothing else + for (auto value = incoming;;) + { + if (!value.hasOneUse()) + { + return false; + } + + auto *def = value.getDefiningOp(); + if (def && isView(def) && def->getNumOperands() == 1) + { + value = def->getOperand(0); + continue; + } + + if (!isFresh(value)) + { + return false; + } + + break; + } + } + + return true; +} + inline bool isFresh(mlir::Value value) { + if (auto argument = mlir::dyn_cast(value)) + { + return isFreshMerge(argument); + } + auto *def = value.getDefiningOp(); if (!def || resultBorrows(def) >= 0 || takenOutOfBorrowedRest(def)) { diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index fb53528a6..5af3de8e2 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -425,6 +425,18 @@ namespace own_inference } } + // an element of an array literal that only borrows (TSLANG 55): whatever uses the + // array reads it - and nothing else: its release leaves the element to its owner + if (auto found = arrayElementUses.find(user); found != arrayElementUses.end()) + { + for (auto &arrayUse : found->second) + { + uses.push_back({arrayUse.op, pending.kills, arrayUse.callee}); + } + + continue; + } + if (pending.borrowed && keeping.returns && mlir::isa(user)) { continue; diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 7cfb7fc3d..a1e615f24 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -558,6 +558,124 @@ namespace own_inference }); } + void OwnershipInferencePass::classifyLocalBorrowingArrays() + { + getFunction().walk([&](mlir_ts::CreateArrayOp arrayOp) { + // `const pipelines = [this.a, this.b]` (TSLANG 55): an array literal in a local, made only + // of what it does not own - each a read out of a place (a field, an element) or a + // parameter - and only read: its length and its elements. It borrows its elements as the + // array a rest parameter is given does (spec 49), for as long as it is used. + auto result = arrayOp.getResult(); + if (arrayOp->getNumOperands() == 0 || arrayOp->hasAttr(OWN_BORROWING_ARRAY_ATTR_NAME) || result.use_empty()) + { + return; + } + + // held in a local, or used as it is (`for (const p of [this.a, this.b])`) + auto slot = result.hasOneUse() ? mlir::dyn_cast(*result.getUsers().begin()) : mlir_ts::VariableOp(); + if (slot && (slot.getInitializer() != result || slot.getCaptured().value_or(false))) + { + return; + } + + llvm::SmallVector retains; + for (auto element : arrayOp->getOperands()) + { + if (holdsNoBlock(element)) + { + continue; + } + + auto root = rootOf(element); + auto rootLoad = root.getDefiningOp(); + auto paramSlot = rootLoad ? rootLoad.getReference().getDefiningOp() : mlir_ts::VariableOp(); + int index = -1; + auto isParameter = paramSlot && isParameterSlot(paramSlot, index); + auto *retain = retainBefore(element, arrayOp); + if (!retain || (!placeReadOf(root) && !isParameter)) + { + return; + } + + retains.push_back(retain); + } + + if (retains.empty()) + { + return; + } + + // the local: read, and given back - never written, never passed on + llvm::SmallVector releases; + llvm::SmallVector reads; + if (slot) + { + for (auto *user : slot->getUsers()) + { + if (auto loadOp = mlir::dyn_cast(user)) + { + reads.push_back(loadOp.getResult()); + } + else if (mlir::isa(user)) + { + releases.push_back(user); + } + else if (!mlir::isa(user)) + { + return; + } + } + } + else + { + reads.push_back(result); + } + + // each read: its length, or an element read out of it (and not written); the array used + // as it is is given back by a `ts.Release` of its own + for (auto read : reads) + { + for (auto *user : read.getUsers()) + { + if (mlir::isa(user)) + { + continue; + } + + if (!slot && mlir::isa(user)) + { + releases.push_back(user); + continue; + } + + auto elementRefOp = mlir::dyn_cast(user); + if (!elementRefOp || elementRefOp.getArray() != read || + llvm::any_of(elementRefOp->getUsers(), [](mlir::Operation *refUser) { return !mlir::isa(refUser); })) + { + return; + } + } + } + + // what reads the array reads what it borrows: each use bounds every element (walkBorrowed) + RecordWalk walk; + walkRecord({result}, {}, walk); + if (walk.kept || !walk.returns.empty()) + { + return; + } + + setAttrTracked(arrayOp, OWN_BORROWING_ARRAY_ATTR_NAME); + fieldBorrowRetains.insert(retains.begin(), retains.end()); + arrayElementUses[arrayOp.getOperation()] = walk.uses; + // its releases give back the array, without what it holds + for (auto *release : releases) + { + setAttrTracked(release, OWN_SHALLOW_RELEASE_ATTR_NAME); + } + }); + } + bool OwnershipInferencePass::isBorrowingCell(mlir::Value ref) { auto cellLoad = ref.getDefiningOp(); diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index 730b83176..ad9c08299 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -708,7 +708,14 @@ namespace own_inference } }); + // a block's argument (a merge, TSLANG 54) is made again each time its block is entered: in a + // loop, the release at the end of one iteration and the one of the next are of two values auto *definition = value.getDefiningOp(); + if (auto argument = mlir::dyn_cast(value); argument && !argument.getOwner()->empty()) + { + definition = &argument.getOwner()->front(); + } + for (auto *first : releases) { for (auto *second : releases) @@ -924,7 +931,13 @@ namespace own_inference } }); + // a block's argument (a merge, TSLANG 54) is made where its block starts, each time it is + // entered: a move of it in that loop's body is of that iteration's value auto *definition = value.getDefiningOp(); + if (auto argument = mlir::dyn_cast(value); argument && !argument.getOwner()->empty()) + { + definition = &argument.getOwner()->front(); + } // `c ? h : h2` that is only read borrows `h` and `h2`, and in a loop moves neither. What // reads the merged value reads this one, so each such read can be a use after a move of diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index f79303494..8fa217b69 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -307,6 +307,8 @@ namespace own_inference classifyRecords(); // ...and whether an array given to a rest parameter takes its elements (spec 49) classifyArgumentArrays(); + // ...and whether an array literal in a local only borrows its elements (TSLANG 55) + classifyLocalBorrowingArrays(); // a kept parameter the body may not move on every path is released at its exits (spec 33) releaseKeptParamsAtExits(); auto exitReleasesGone = llvm::make_scope_exit([&]() { @@ -399,6 +401,7 @@ namespace own_inference returnsRecordOf = isRecordResult(f) ? resultBorrowsAll(f) : llvm::SmallVector(); records.clear(); recordStoreUses.clear(); + arrayElementUses.clear(); } // A store of a value that owns a block into a parameter's own slot: the function's argument, which no local diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 3beda949b..8a44a1cee 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -289,6 +289,9 @@ class OwnershipInferencePass // The arrays a rest parameter is given that only borrow their elements for the call (spec 49): // rc's references for the elements go, and the array is released after the call without them. void classifyArgumentArrays(); + // An array literal held in a local, made only of reads of places and parameters and only read + // (TSLANG 55): it borrows its elements while it is used, and its releases are shallow. + void classifyLocalBorrowingArrays(); // Is `ref` a cell read out of the `.captured` box of a generator's state object that borrows: // `ts.Load(ts.PropertyRef(ts.Load(ts.PropertyRef(state, captured)), i))`? @@ -623,6 +626,9 @@ class OwnershipInferencePass // a store of a place read into a borrowing record's field -> the record's uses, which are the // read's uses too (walkBorrowed) llvm::DenseMap recordStoreUses; + // an array literal that only borrows its elements (classifyLocalBorrowingArrays, TSLANG 55) -> + // its uses, and those of what is read out of it: uses of each element (walkBorrowed) + llvm::DenseMap> arrayElementUses; // Can a value of this type point into a heap block - a reference into one, a block of its own, // or a method bound to one? A number or a boolean read out of a borrowed block cannot. diff --git a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp index 3f40e3ccb..23683e810 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp @@ -188,6 +188,18 @@ namespace own_signature return run(at->getBlock(), in[at->getBlock()], at); } + // A value the steps below may follow to where it moves: made here (not a read of a local or a + // place), or merged from branches that each bring a fresh value or null (TSLANG 54). + bool ownValue(mlir::Value root, mlir::Operation *def) + { + if (auto argument = mlir::dyn_cast(root)) + { + return own_facts::isFreshMerge(argument); + } + + return def && !mlir::isa(def); + } + // The fields a constructor keeps its parameters in (TSLANG 53): a parameter stored as it is into a // field of `this` that nothing else in the constructor writes, where `this` never escapes - it // is only read for its fields, so no call the constructor makes can reach the field. By the @@ -502,7 +514,7 @@ namespace own_signature mlir::isa(fieldType); // a string and the like are copied into the field, and a Shared handle counted: // the value stays the function's own, not moved - if (!def || mlir::isa(def) || !own_facts::ownsHeap(root) || + if (!ownValue(root, def) || !own_facts::ownsHeap(root) || own_facts::isCopyableValueAt(fieldStore, root.getType()) || MLIRTypeHelper::isSharedHandleType(root.getType()) || (!narrowed && !fieldReadsAs(field, root.getType()))) { @@ -555,7 +567,7 @@ namespace own_signature auto arrayType = mlir::dyn_cast(mlir::cast(field.getType()).getElementType()); auto root = stripViews(pushOp.getItems().front()); auto *def = root.getDefiningOp(); - if (!arrayType || !def || mlir::isa(def) || !own_facts::ownsHeap(root) || + if (!arrayType || !ownValue(root, def) || !own_facts::ownsHeap(root) || own_facts::isCopyableValueAt(pushOp, root.getType()) || MLIRTypeHelper::isSharedHandleType(root.getType())) { continue; @@ -666,7 +678,7 @@ namespace own_signature auto fieldType = fieldRefType.getElementType(); auto narrowed = fieldType != root.getType() && mlir::isa(root.getType()) && mlir::isa(fieldType); - if (!def || mlir::isa(def) || !own_facts::ownsHeap(root) || + if (!ownValue(root, def) || !own_facts::ownsHeap(root) || own_facts::isCopyableValueAt(callOp, root.getType()) || MLIRTypeHelper::isSharedHandleType(root.getType()) || (fieldType != root.getType() && !narrowed)) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index ee8f62ea1..d226baf95 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1907,9 +1907,11 @@ endforeach() # TSLANG_ISSUES 50: a value moved into a field and used after is a borrow of the field # TSLANG_ISSUES 52: a value pushed into a field array and used after is a borrow of its last element # TSLANG_ISSUES 53: a value a constructor keeps in a field, used after, is a borrow of that field +# TSLANG_ISSUES 54: a `?:` of fresh values or null is the function's own +# TSLANG_ISSUES 55: an array literal of fields, only read, borrows them foreach(issues_mm gc rc none own) foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49 00tslang_issue_50 - 00tslang_issue_52 00tslang_issue_53) + 00tslang_issue_52 00tslang_issue_53 00tslang_issue_54 00tslang_issue_55) tslang_add_test(NAME test-jit-${issues_test}-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") tslang_add_test(NAME test-compile-${issues_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") endforeach() @@ -5455,7 +5457,9 @@ set(own_error_cases "own_err_moved_field_overwritten|:15:25: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_moved_param_field_dropped|:13:15: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_pushed_then_popped|:14:16: error: '[^']*' borrows an element but is used here after it may be released or overwritten" - "own_err_kept_by_constructor_reset|:16:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten") + "own_err_kept_by_constructor_reset|:16:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" + "own_err_merge_moved_twice|:19:9: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_borrowing_array_field_reset|:13:16: error: '[^']*' borrows a field but is used here after it may be released or overwritten") 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_err_borrowing_array_field_reset.ts b/tslang/test/tester/own/own_err_borrowing_array_field_reset.ts new file mode 100644 index 000000000..3c33bce5c --- /dev/null +++ b/tslang/test/tester/own/own_err_borrowing_array_field_reset.ts @@ -0,0 +1,17 @@ +// TSLANG_ISSUES 55: an array literal of fields borrows them while it is used - but a field written +// before a read out of the array frees what the array still holds, so that read is refused. +class Pipe { + id: int = 3; +} + +class K { + a: Pipe = new Pipe(); + b: Pipe = new Pipe(); + run(): int { + const xs = [this.a, this.b]; + this.a = new Pipe(); + return xs[0].id; + } +} + +function main() { print(new K().run()); } diff --git a/tslang/test/tester/own/own_err_merge_moved_twice.ts b/tslang/test/tester/own/own_err_merge_moved_twice.ts new file mode 100644 index 000000000..501617c73 --- /dev/null +++ b/tslang/test/tester/own/own_err_merge_moved_twice.ts @@ -0,0 +1,23 @@ +// TSLANG_ISSUES 54: a value merged from a `?:` of fresh values or null is the function's own, so it +// moves - once. A second store of it is a second owner, refused. +class P { + id: int = 3; +} + +function make(n: int): P { + const p = new P(); + p.id = n; + return p; +} + +class K { + a: P | null = null; + b: P | null = null; + run(c: boolean) { + const p = c ? make(1) : null; + this.a = p; + this.b = p; + } +} + +function main() { new K().run(true); } diff --git a/tslang/test/tester/tests/00tslang_issue_54.ts b/tslang/test/tester/tests/00tslang_issue_54.ts new file mode 100644 index 000000000..0466750a0 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_54.ts @@ -0,0 +1,85 @@ +// TSLANG_ISSUES 54 (-mm=own), from native_ts_graphics' core/nri_donut_textures.ts: a value merged +// from a `?:` whose branches each bring a fresh value or null - `const pipeline = loaded ? +// device.createPipeline(...) : null` - is the function's own, so it can be moved (pushed, stored) +// like the call's result itself, and used after the move as 50 and 52 follow it. + +class Pipe { + id: int = 3; +} + +function make(n: int): Pipe { + const p = new Pipe(); + p.id = n; + return p; +} + +@final +class Device { + make(): Pipe | null { + return new Pipe(); + } +} + +export class K { + pipes: Pipe[] = []; + layout: Pipe | null = null; + + // pushed + load(device: Device, loaded: boolean): int { + const pipeline = loaded ? device.make() : null; + if (!pipeline) { + return -1; + } + + const id = pipeline.id; + this.pipes.push(pipeline); + return id; + } + + // in a loop's body: each iteration merges and moves its own value + loadAll(device: Device, loaded: boolean): int { + for (let i = 0; i < 2; i++) { + const pipeline = loaded ? device.make() : null; + if (!pipeline) { + return -1; + } + + this.pipes.push(pipeline); + } + + return this.pipes.length; + } + + // stored into a field and used after, through it + keep(ok: boolean): int { + const layout = ok ? make(5) : null; + this.layout = layout; + if (!layout) { + return -1; + } + + return layout.id; + } + + // two fresh branches, and one nested in another + pick(c: boolean, d: boolean): int { + const p = c ? make(1) : d ? make(2) : null; + this.layout = p; + const q = c ? make(10) : make(20); + this.pipes.push(q); + return (this.layout ? this.layout.id : 0) + q.id; + } +} + +function main() { + const k = new K(); + assert(k.load(new Device(), true) == 3 && k.load(new Device(), false) == -1 && k.pipes.length == 1); + assert(k.loadAll(new Device(), true) == 3 && k.loadAll(new Device(), false) == -1); + assert(k.keep(true) == 5 && k.keep(false) == -1); + const a = k.pick(true, false); + const b = k.pick(false, true); + const c = k.pick(false, false); + print(a, b, c); + assert(a == 11 && b == 22 && c == 20); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_55.ts b/tslang/test/tester/tests/00tslang_issue_55.ts new file mode 100644 index 000000000..7d3f4a11e --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_55.ts @@ -0,0 +1,69 @@ +// TSLANG_ISSUES 55 (-mm=own), from native_ts_graphics: an array literal made only of fields (and +// parameters) and only read - `const directions = [this.dir, this.dir, this.right, ...]` in +// core/donut_first_person_camera.ts, `for (const p of [this.a, this.b]) p.destroy()` - borrows its +// elements while it is used, and gives back only itself. The same field twice is fine. + +class Pipe { + id: int = 3; + destroy() { + this.id = 0; + } +} + +class Cam { + dir: number[] = [0.0, 0.0, 1.0]; + right: number[] = [1.0, 0.0, 0.0]; + up: number[] = [0.0, 1.0, 0.0]; + + move(step: number): number[] { + const m = [0.0, 0.0, 0.0]; + const directions = [this.dir, this.dir, this.right, this.right, this.up, this.up]; + const signs = [1.0, -1.0, -1.0, 1.0, 1.0, -1.0]; + for (let k = 0; k < directions.length; k += 2) { + for (let i = 0; i < 3; i++) { + m[i] = m[i] + signs[k] * directions[k][i] * step; + } + } + + return m; + } +} + +class K { + a: Pipe = new Pipe(); + b: Pipe = new Pipe(); + + sum(): int { + const pipes = [this.a, this.b, this.a]; + let total = 0; + for (let i = 0; i < pipes.length; i++) { + total += pipes[i].id; + } + + return total; + } + + // straight over the literal, a parameter among the fields, a method called on each + kill(extra: Pipe): int { + let n = 0; + for (const p of [this.a, this.b, extra]) { + n += p.id; + p.destroy(); + } + + return n + this.a.id; + } +} + +function main() { + const m = new Cam().move(2.0); + print(m[0], m[1], m[2]); + assert(m[0] == -2.0 && m[1] == 2.0 && m[2] == 2.0); + + const k = new K(); + k.b.id = 5; + assert(k.sum() == 11); + const extra = new Pipe(); + assert(k.kill(extra) == 11 && k.a.id == 0 && extra.id == 0); + print("done."); +}