From 6d42f2ee3246e4a8cee196bc0cd0a6e96237683a Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 5 Dec 2026 19:07:17 +0000 Subject: [PATCH 1/2] -mm=own: walk gaps of TSLANG 235 fixed; a release in this function that a local borrow outlives is deferred to the function's exit; README GPU and own performance - copies of walking locals, never-assigned lets given to lending calls, and lets stepped from a lending call's result borrow what the walk borrows; a parameter walked through a copy is not a move - a field given a fresh value while a local still uses its old one: the old value is kept in a function-local temporary and released at the exit (once, no loop, no try); 15 former refusals run as own_deferred_* tests; `this.head = h.next` (the new value part of the old) stays refused - README: GPU kernels section with an example, -mm=own vs Rust/C++ table; TSLANG_ISSUES 247 Co-Authored-By: Claude Opus 5.5 --- README.md | 41 +- TSLANG_ISSUES.md | 494 ++++++++++++++++++ docs/own-memory-model.md | 49 +- .../2026-12-05-own-deferred-release-design.md | 38 +- .../OwnershipInferenceBorrowers.cpp | 164 +++++- .../lib/TypeScript/OwnershipInferencePass.cpp | 133 +++++ .../lib/TypeScript/OwnershipInferencePass.h | 12 +- .../OwnershipInferencePlaceReads.cpp | 22 +- .../lib/TypeScript/OwnershipSignaturePass.cpp | 14 + tslang/test/tester/CMakeLists.txt | 46 +- ...=> own_counted_result_borrows_argument.ts} | 4 +- ..._deferred_borrowed_result_holder_stored.ts | 41 ++ .../own_deferred_borrowed_result_outlives.ts | 35 ++ ...wn_deferred_borrowing_array_field_reset.ts | 32 ++ ...rred_borrowing_record_place_overwritten.ts | 33 ++ .../tester/own/own_deferred_field_alias.ts | 27 + .../own/own_deferred_fill_after_fill_call.ts | 39 ++ .../tester/own/own_deferred_lends_outlives.ts | 35 ++ .../own/own_deferred_list_lookahead_cut.ts | 46 ++ .../own_deferred_merge_read_overwritten.ts | 35 ++ .../own_deferred_moved_param_field_dropped.ts | 32 ++ ...wn_deferred_read_after_move_overwritten.ts | 29 + ...wn_deferred_split_let_field_overwritten.ts | 34 ++ .../tester/own/own_deferred_union_moved.ts | 28 + .../own_deferred_walk_lent_copy_cleared.ts | 25 + .../own/own_deferred_weakref_after_release.ts | 17 + .../own_err_borrowed_result_holder_stored.ts | 32 -- .../own/own_err_borrowed_result_outlives.ts | 20 - .../own_err_borrowing_array_field_reset.ts | 17 - ..._err_borrowing_record_place_overwritten.ts | 29 - .../own/own_err_deferred_release_in_loop.ts | 4 + tslang/test/tester/own/own_err_field_alias.ts | 11 - .../own/own_err_fill_after_fill_call.ts | 29 - .../test/tester/own/own_err_lends_outlives.ts | 21 - .../tester/own/own_err_list_lookahead_cut.ts | 21 - .../own/own_err_merge_read_overwritten.ts | 31 -- .../own/own_err_moved_param_field_dropped.ts | 16 - .../own_err_read_after_move_overwritten.ts | 11 - .../own_err_split_let_field_overwritten.ts | 21 - tslang/test/tester/own/own_err_union_moved.ts | 12 - .../test/tester/own/own_err_walk_alias_cut.ts | 9 + .../test/tester/own/own_err_walk_copy_cut.ts | 9 + .../tester/own/own_err_walk_copy_stored.ts | 10 + .../own/own_err_walk_lent_copy_cleared.ts | 10 + .../own/own_err_weakref_after_release.ts | 4 - .../tests/00tslang_issue_235_own_deferred.ts | 79 +++ .../tests/00tslang_issue_235_own_gaps.ts | 104 ++++ 47 files changed, 1670 insertions(+), 335 deletions(-) rename tslang/test/tester/own/{own_err_result_borrows_argument.ts => own_counted_result_borrows_argument.ts} (69%) create mode 100644 tslang/test/tester/own/own_deferred_borrowed_result_holder_stored.ts create mode 100644 tslang/test/tester/own/own_deferred_borrowed_result_outlives.ts create mode 100644 tslang/test/tester/own/own_deferred_borrowing_array_field_reset.ts create mode 100644 tslang/test/tester/own/own_deferred_borrowing_record_place_overwritten.ts create mode 100644 tslang/test/tester/own/own_deferred_field_alias.ts create mode 100644 tslang/test/tester/own/own_deferred_fill_after_fill_call.ts create mode 100644 tslang/test/tester/own/own_deferred_lends_outlives.ts create mode 100644 tslang/test/tester/own/own_deferred_list_lookahead_cut.ts create mode 100644 tslang/test/tester/own/own_deferred_merge_read_overwritten.ts create mode 100644 tslang/test/tester/own/own_deferred_moved_param_field_dropped.ts create mode 100644 tslang/test/tester/own/own_deferred_read_after_move_overwritten.ts create mode 100644 tslang/test/tester/own/own_deferred_split_let_field_overwritten.ts create mode 100644 tslang/test/tester/own/own_deferred_union_moved.ts create mode 100644 tslang/test/tester/own/own_deferred_walk_lent_copy_cleared.ts create mode 100644 tslang/test/tester/own/own_deferred_weakref_after_release.ts delete mode 100644 tslang/test/tester/own/own_err_borrowed_result_holder_stored.ts delete mode 100644 tslang/test/tester/own/own_err_borrowed_result_outlives.ts delete mode 100644 tslang/test/tester/own/own_err_borrowing_array_field_reset.ts delete mode 100644 tslang/test/tester/own/own_err_borrowing_record_place_overwritten.ts create mode 100644 tslang/test/tester/own/own_err_deferred_release_in_loop.ts delete mode 100644 tslang/test/tester/own/own_err_field_alias.ts delete mode 100644 tslang/test/tester/own/own_err_fill_after_fill_call.ts delete mode 100644 tslang/test/tester/own/own_err_lends_outlives.ts delete mode 100644 tslang/test/tester/own/own_err_list_lookahead_cut.ts delete mode 100644 tslang/test/tester/own/own_err_merge_read_overwritten.ts delete mode 100644 tslang/test/tester/own/own_err_moved_param_field_dropped.ts delete mode 100644 tslang/test/tester/own/own_err_read_after_move_overwritten.ts delete mode 100644 tslang/test/tester/own/own_err_split_let_field_overwritten.ts delete mode 100644 tslang/test/tester/own/own_err_union_moved.ts create mode 100644 tslang/test/tester/own/own_err_walk_alias_cut.ts create mode 100644 tslang/test/tester/own/own_err_walk_copy_cut.ts create mode 100644 tslang/test/tester/own/own_err_walk_copy_stored.ts create mode 100644 tslang/test/tester/own/own_err_walk_lent_copy_cleared.ts delete mode 100644 tslang/test/tester/own/own_err_weakref_after_release.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_235_own_deferred.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_235_own_gaps.ts diff --git a/README.md b/README.md index ab490eb9e..0c1031d9e 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ them on the fly via a built-in JIT — no Node.js or JavaScript runtime required - [Quick start](#quick-start) - [Memory models](#memory-models) +- [GPU kernels](#gpu-kernels) - [Documentation](#documentation) - [Showcase: native_ts_graphics](#showcase-native_ts_graphics) - [Community](#community) · [License](#license) · [Contributing](#contributing) @@ -81,8 +82,44 @@ How heap memory is managed is selected with `-mm=`: | `-mm=own` | single ownership inferred at compile time, like Rust's borrow checker - no collector, no counting | **in development**; ownership that cannot be proven is a compile error | See [memory-models.md](docs/memory-models.md) and the [`-mm=own` guide](docs/own-memory-model.md). -Under `-mm=own` tslang runs within 1.1-1.4x of idiomatic Rust on an object-heavy ray tracer and on -par with it on array loops — see [Performance](docs/performance.md). + +`-mm=own` is Rust-style ownership: the compiler decides at compile time where each object is freed, +so a program runs with no collector and no reference counts, and its speed is close to Rust's +(release builds, ms, lower is better): + +| benchmark | `-mm=own` | Rust | C++ (clang -O3) | +| --- | --- | --- | --- | +| ray tracer, classes and `switch` (Rust: enums and `match`; Linux) | 50 | 50 | | +| ray tracer, interfaces and closures (Rust: plain values; Windows) | 76 | 56 | 52 | +| array loops: matmul / hash (Linux) | 26.7 / 48.0 | 20.6 / 44.4 | 30.1 / 42.8 | + +Written with every object in an `Rc` (a `shared_ptr` in C++), as code that shares objects freely must be, +the interface ray tracer takes 500 ms in Rust and 834 ms in C++. The details, the machines and the +other models are in [Performance](docs/performance.md). + +## GPU kernels + +A function marked `@kernel` runs on the GPU, one thread per index, on NVIDIA, AMD and Intel GPUs, +both from executables and from the JIT. No GPU SDK is needed to compile or to run: the program loads +the GPU's driver itself. + +```typescript +@kernel +function add(i: int, a: number[], b: number[], c: number[]) { + c[i] = a[i] + b[i]; +} + +function main() { + const a: number[] = [1, 2, 3]; + const b: number[] = [10, 20, 30]; + const c: number[] = [0, 0, 0]; + gpuLaunch(add, 3, a, b, c); + print(c); // [ 11, 22, 33 ] +} +``` + +The interface ray tracer above, one GPU thread per pixel (`rtbench_gpu.ts`), renders 512x512 in 1.9 ms on an RTX 5080. See +[GPU kernels](docs/gpu.md) for `gpuMap`/`gpuReduce`/`gpuSort`, shared memory, atomics and more. ## Documentation diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index ac1880884..5826f8fe2 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -813,6 +813,500 @@ owner. So is a function returning its parameter (`const c = id(new V(1))`, #638) `this` is taken over. Regression tests `tslang/test/tester/tests/00tslang_issue_85.ts` (every model), `own/own_err_global_concat_borrowed.ts` and `own/own_err_global_chain_other_global.ts`. +234. Bitwise operators on integer literals above 0x7fffffff don't wrap to int32, and an int `+` wraps +where JavaScript's number doesn't (2026-12-04, pre-alpha143, JIT, Windows x64). Found porting +golden-line's `hash32` / `mulberry32` (src/core/rng.js), which rely on JavaScript's ToInt32/ToUint32: + +```ts +function main() { + console.log("xorK", 0x9e3779b9 ^ 5); + const k = 0x9e3779b9; + console.log("xorV", k ^ 5); + let s = 0x6d2b79f5; + console.log("sum", s + 0x6d2b79f5); + console.log("sumushr", (s + 0x6d2b79f5) >>> 0); + const big = 3663131626; + console.log("bigor", big | 0, big >>> 0, big ^ 0); +} +``` + +tslang prints `xorK 2654435772`, `xorV 2654435772`, `sum -631835670`, `sumushr 3663131626`, +`bigor 3663131626 3663131626 3663131626`; node prints `xorK -1640531524`, `sum 3663131626`, +`bigor -631835670 3663131626 -631835670`. So (a) a literal above int32 is a 64-bit integer, and `^`, `|` +on it stay 64-bit instead of ToInt32 (JavaScript's `x | 0` is the usual way to wrap); (b) `let s = +0x6d2b79f5` is an `int`, so `s + 0x6d2b79f5` wraps at 32 bits where JavaScript gives the double sum (the +`>>> 0` of it happens to agree). `Math.imul`, `>>` and `>>>` of an `int` were right. (b) is the documented +`int` inference (memory note: `0` is int); (a) breaks code ported as is and gives no warning. Workaround +in native_ts_graphics (core/golden_line_world.ts): the constants written as the negative int32 they wrap +to, `x >>> n` as `(x >> n) & mask` on `int`s, and an explicit `toInt32(x: number): int` for doubles. +Also seen: two nested `for (const r of sorted) ... for (const o of sorted)` over the same array warn +"variable .a redeclared" (the inner loop's hidden index), though the result was right. + +235. Assignments to a nullable local inside a `while (p !== null)` loop are lost: the loop keeps the +narrowed value (2026-12-04, pre-alpha145, JIT, Windows x64). Found porting three.js's earcut (the +linked-list merge sort of its z-order pass) for golden-line's train: the sort never advanced, corrupted +the links and hung. Repro (a merge sort over `nextZ`): + +```ts +class ZN { + i: int; + z: int; + prevZ: ZN | null = null; + nextZ: ZN | null = null; + constructor(i: int, z: int) { this.i = i; this.z = z; } +} +function nn(n: ZN | null): ZN { return n!; } +function sortLinked(listIn: ZN) { + let list: ZN | null = listIn; + let numMerges: int = 0; + let inSize: int = 1; + do { + let p: ZN | null = list; + list = null; + let tail: ZN | null = null; + numMerges = 0; + while (p !== null) { + numMerges++; + let q: ZN | null = p; + let pSize: int = 0; + for (let i: int = 0; i < inSize; i++) { + pSize++; + q = nn(q).nextZ; + if (q === null) { break; } + } + let qSize: int = inSize; + while (pSize > 0 || (qSize > 0 && q !== null)) { + let e: ZN = nn(p); + let takeP = false; + if (pSize != 0) { + if (qSize == 0 || q === null) { takeP = true; } else if (nn(p).z <= nn(q).z) { takeP = true; } + } + if (takeP) { e = nn(p); p = e.nextZ; pSize--; } else { e = nn(q); q = e.nextZ; qSize--; } + if (tail !== null) { nn(tail).nextZ = e; } else { list = e; } + e.prevZ = tail; + tail = e; + } + p = q; + } + nn(tail).nextZ = null; + inSize *= 2; + } while (numMerges > 1); +} +function main() { + const zs: int[] = [5, 3, 9, 1, 7, 2]; + const nodes: ZN[] = []; + for (let i = 0; i < zs.length; i++) { nodes.push(new ZN(i, zs[i])); } + for (let i = 0; i + 1 < nodes.length; i++) { nodes[i].nextZ = nodes[i + 1]; nodes[i + 1].prevZ = nodes[i]; } + sortLinked(nodes[0]); + let s = ""; + for (let i = 0; i < nodes.length; i++) { const n = nodes[i]; const pz = n.prevZ; const nz = n.nextZ; s += `${n.i}:${pz === null ? -1 : nn(pz).i}/${nz === null ? -1 : nn(nz).i} `; } + console.log(s); +} +``` + +tslang prints `0:1/3 1:1/2 2:1/5 3:3/-1 4:5/-1 5:5/-1` (links point back at themselves); with the loop +condition written through a helper, `function isNull(n: ZN | null): boolean { return n === null; }` and +`while (!isNull(p))`, it prints the right order, `0:1/4 1:5/0 2:4/-1 3:-1/5 4:0/2 5:3/1`. So the `p !== +null` narrowing seems to pin `p` for the loop and drop `p = e.nextZ` / `p = q` made in nested blocks. A +simpler loop of the same shape (one level of nesting) works. Workaround in native_ts_graphics +(core/golden_line_extrude.ts): `earIsNull(n)` in every loop condition and null test over the list. +Probably the same miscompile: this program (an inner `while (n > 0 || p !== null)` that ends with +`if (p === null) { break; }`) stops the JIT run with exception 0x80000003 instead of printing `C steps +1`, most likely `n!` meeting a null that correct code never reaches; the same loop without the inner +`|| p !== null` runs right: + +```ts +class L { i: int; next: L | null = null; constructor(i: int) { this.i = i; } } +function nn(n: L | null): L { return n!; } +function main() { + const a = new L(0); const b = new L(1); const c = new L(2); + a.next = b; b.next = c; + let p: L | null = a; + let steps: int = 0; + while (p !== null) { + let n: int = 1; + while (n > 0 || p !== null) { const e = nn(p); p = e.next; n--; if (p === null) { break; } } + steps++; + if (steps > 10) { console.log("stuck"); break; } + } + console.log(`C steps ${steps}`); +} +``` + +236. `-mm=own` (pre-alpha145): a callee that reassigns any object or array field, or calls `Map.set`, ends +every borrow its caller holds, even of unrelated objects. Found porting native_ts_graphics' golden_line +world to own (2026-12-04). Two examples: +- In `Ter.sum` below, `this.near(n)`'s list stays borrowed across `this.feat(s)`. `feat` only calls + `this.fslots.set(...)` on a `Map` and pushes a new `Feat`, yet the borrow is refused: "a value + that borrows the result of 'Ter.near' is used here after it may be released or overwritten", released + at `this.feat(s)`. Replace the Map with an `int[]` slot table and it compiles. +- `this.bag = order` in a callee (`int[]` field) gives the same error for a borrowed `int[]` result of + another field: `c_reassign.ts` below. With `this.bag.push(3)` instead, it compiles. + +```ts +@final class Seg { constructor(public index: int, public z0: number) {} } +@final class Lay { segs: Seg[] = []; ensure(n: int) { while (this.segs.length < n) this.segs.push(new Seg(this.segs.length, this.segs.length * 10.0)); } + range(n: int): int[] { this.ensure(n); const out: int[] = []; for (let i = 0; i < n; i++) out.push(i); return out; } } +@final class Feat { v = 0.0; } +@final export class Ter { + lay = new Lay(); + private slots = new Map(); private lists: int[][] = []; + private fslots = new Map(); private feats: Feat[] = []; + @lends("this") near(n: int): int[] { + const slot = this.slots.get(n); + if (slot !== undefined) return this.lists[slot]; + this.slots.set(n, this.lists.length); this.lists.push(this.lay.range(n)); + return this.lists[this.lists.length - 1]; + } + @lends("this") feat(s: Seg): Feat { + const slot = this.fslots.get(s.index); + if (slot !== undefined) return this.feats[slot]; + this.fslots.set(s.index, this.feats.length); this.feats.push(new Feat()); + return this.feats[this.feats.length - 1]; + } + sum(n: int): number { + let t = 0.0; + for (const i of this.near(n)) { const s = this.lay.segs[i]; const f = this.feat(s); t += f.v + s.z0; } + return t; + } +} +function main() { print(new Ter().sum(5)); } +``` + +```ts +// c_reassign.ts +@final export class T { + n = 0; bag: int[] = []; lists: int[][] = [[1, 2]]; + @lends("this") get(): int[] { return this.lists[0]; } + work() { const o: int[] = [1]; this.bag = o; } + run(): int { let s = 0; for (const i of this.get()) { this.work(); s += i; } return s; } +} +function main() { print(new T().run()); } +``` + +Maybe the check is meant to work by type only. But a `Map` and an `int[]` field hold nothing a +borrow could point into. Workaround in golden_line_world.ts: `wlSlotGet` / `wlSlotSet` int-array slot +tables, and refill `bag` in place. + +237. `-mm=own` (pre-alpha145): emptying any local `int[]` ends borrows of unrelated objects. That covers +`grid.length = 0`, `splice` and a `pop` loop: `f` below is refused after `grid.length = 0`. A fresh array +for each iteration compiles. The same happens for `xs.length = 0` when `xs` borrows `this.xs` ("cannot be +stored"); `this.xs.length = 0` compiles. + +```ts +class F { v = 2.0; } +class T { list: F[] = [new F()]; get(i: int): F { return this.list[i]; } } +function run(t: T, n: int): number { + const f = t.get(0); + const grid: int[] = []; + let s = 0.0; + for (let k = 0; k < n; k++) { s += f.v; grid.length = 0; grid.push(k); } + return s + grid[0]; +} +function main() { print(run(new T(), 3)); } +``` + +238. `-mm=own` (pre-alpha145): a closure passed straight to a function that only calls it is taken to +move a class-instance local it captures. The second use below gives "'B' is used here after its value was +moved", and inside a loop the error is "moved inside a loop". The doc says a closure that does not escape +borrows what it captures, and an `int[]` local captured the same way is borrowed. Workaround (golden_line_saloon.ts): +a module function that takes the instance as a parameter and builds the closure there. + +```ts +type UVFn = (u: number, v: number) => number[]; +@final class Back { k: number = 2.0; pt(x: number): number { return x * this.k; } } +function surf(fn: UVFn, n: int): number[] { + const out: number[] = []; + for (let i = 0; i < n; i++) { const r = fn(i / n, 0.5); out.push(r[0]); } + return out; +} +export function noLoop(): number { + const B = new Back(); + const a = surf((u: number, v: number): number[] => [B.pt(u), v], 4); + const b = surf((u: number, v: number): number[] => [B.pt(u), v], 4); + return a[0] + b[0] + B.pt(1.0); +} +``` + +239. `-mm=own` (pre-alpha145): `const pts = tube.pts; t.copy(pts[0]);`, where `copy` returns `this`, +gives "'pts' borrows 'tube.pts' and cannot be stored". Nothing stores it: `t.copy(tube.pts[0])` +compiles, and so does a `void` `copy`. + +```ts +@final class P { constructor(public x: number) {} copy(v: P): this { this.x = v.x; return this; } } +class Tube { pts: P[] = []; } +function f(tube: Tube): number { const pts = tube.pts; const t = new P(0.0); t.copy(pts[0]); return t.x; } +function main() { const tb = new Tube(); tb.pts.push(new P(2.0)); print(f(tb)); } +``` + +240. `-mm=own` (pre-alpha145): a borrowed field receiver is treated differently depending on how the +argument is written. `Bucket.add` below calls a stored callback (`Shared`), so it may free anything. +- `m1` (`const B = this.B; B.add(PAINT.a)`, where `PAINT.a` is a getter returning a new `Style`) + compiles. +- `m5` passes the same `Style` held in a local first and is refused: "'B' borrows 'this.B' but is used + here after it may be released or overwritten". So is `B.add(new Style())`. +- A parameter receiver (`m6(B: Bucket, ...)`) compiles in every form. + +Either all of these are errors, or none should be. + +```ts +export type VFn = (x: number) => number[]; +@final export class Style { fn0: Shared | null = null; v = 1.0; } +export function recipe(v: number): Style { const s = new Style(); s.v = v; return s; } +@final export class Paints { get a(): Style { return recipe(1.0); } } +export const PAINT: Paints = new Paints(); +@final export class Bucket { + out: number[] = []; + add(s: Style): this { const f = s.fn0; if (f) { const r = f.value(1.0); this.out.push(r.length); } this.out.push(s.v); return this; } +} +@final export class Loco { + B = new Bucket(); + m1(): void { const B = this.B; B.add(PAINT.a); B.add(PAINT.a); } // compiles + m3(): void { const B = this.B; B.add(new Style()); } // error + m5(): void { const B = this.B; const st = PAINT.a; B.add(st); } // error + m6(B: Bucket, st: Style): void { B.add(st); B.add(st); } // compiles +} +``` + +Also not yet minimized: in core/golden_line_traingeo.ts, `const r = fn(this.p[k], ...)` (a `PFn` callback +parameter of an exported class's method, `r` read only as `r[0]`) gives "'r' takes a second reference"; +the same method alone in a module compiles. Workaround: `geoTake(dst, fn(...), n)` copies the result +through an argument. Item 235's workaround (`earIsNull`) is gone from golden_line_extrude.ts: its earcut +now keeps nodes in an index pool. + +241. `-mm=own` (pre-alpha145): what a method's callers may keep borrowed across a call to it depends on +where an unrelated function is declared in its module. In native_ts_graphics (branch golden-line-farms, on +28b1605), `core/golden_line_lineside.ts`'s `LsPlanner.planChunk` passes. Add one empty function just before +`export class LsPlanner {`: + +```ts +function lsNothing(): void { +} +``` + +Then every borrow a caller holds across `planChunk` is refused. That covers `this.world`, +`this.world.value`, `this.world.value.terrain`, the chunk mesh `shared.value` and `this.planner`, each with +"... is used here after it may be released or overwritten". The same empty function at the end of the +module compiles. So does a comment in its place. Nothing calls it. + +Repro: the file below, beside the native_ts_graphics checkout, run with +`tslang --opt --opt_level=3 -mm=own --own-fallback=error --jit-cache=false --emit=jit t_own3.ts`. It prints +`0` with the module as committed and five errors at the `planChunk` line with the function added. + +```ts +import { World, SEED, TerrainMesh } from "I:/native_ts_graphics/core/golden_line_world"; +import * as K from "I:/native_ts_graphics/core/golden_line_structkit"; +import * as L from "I:/native_ts_graphics/core/golden_line_lineside"; + +@final +class Host { + world: Shared; + planner = new L.LsPlanner(); + constructor(world: Shared) { + this.world = world; + } + add(index: int, shared: Shared): void { + const terrain = this.world.value.terrain; + const mesh = shared.value; + const g = K.skBuildGround(terrain, mesh, index); + const items = this.planner.planChunk(terrain, g, mesh); // the errors point here + console.log(`${items.walls.length}`); + } +} + +function main() { + const world = new Shared(new World(SEED)); + const host = new Host(world); + const mesh = new Shared(world.value.buildChunk(1)); + host.add(1, mesh); +} +``` + +Suspect: the ownership inference's per-function summaries are computed in declaration order. A function +declared before the class seems to change the order in which `planChunk` and the helpers it calls (the +module's `lsSpanNear`, `lsTownAt`, `lsWallLine` and the planner's private methods) are summarized. One of +them is then summarized before its callees and keeps a conservative "may free anything". + +Workaround in native_ts_graphics (the farms port, branch golden-line-farms): the new module-level farm +code in golden_line_lineside.ts (`LsFarmSite`, `lsSiteFarm` and its helpers) sits at the end of the +module, after `LsPlanner`. + +242. `-mm=own` (pre-alpha145): assigning a `string` field ends the borrow of a nullable field read from a +call's result. `const plan = t.feature(0).plan; if (plan == null) return;` then `this.name = plan.name` +makes a later `plan.yaw` an error: "'plan' borrows a field but is used here after it may be released or +overwritten", released at the string assignment. The `string` held in `this.name` before can't point into +`plan`. Found porting native_ts_graphics' golden_line station town (2026-12-04). Run as written +(`tslang --emit=jit -mm=own --own-fallback=error --jit-cache=false own_call_nullable.ts`). Without +`-mm=own`, and under `-mm=rc`, it prints `Thorncombe 5 0.5`. Three things to note: +- It compiles if `plan` is not nullable (`plan: Plan = new Plan()`, no null test), or if `plan` is read + straight from a field (`const plan = h.plan`) rather than from a method's result. `@lends("this")` on + `feature` makes no difference, and neither does a constructor instead of a method. +- Only the second use after the assignment is refused. `this.zc = plan.zc` right after it compiles. +- Copying the string to a local first (`const nm = plan.name; ...; this.name = nm;`) still fails at + `this.name = nm`. + +```ts +// own_call_nullable.ts +@final class Plan { name = "Thorncombe"; zc = 5.0; yaw = 0.5; } +@final class Feat { plan: Plan | null = new Plan(); } +@final class Ter { + feats: Feat[] = [new Feat()]; + @lends("this") feature(i: int): Feat { return this.feats[i]; } +} +@final class Ctx { + name = ""; + zc = 0.0; + yaw = 0.0; + fill(t: Ter): void { + const plan = t.feature(0).plan; + if (plan == null) return; + this.name = plan.name; // assigning a string field... + this.zc = plan.zc; // (still accepted) + this.yaw = plan.yaw; // ...refused: "'plan' borrows a field but is used here after it may be released" + } +} +function main() { const t = new Ter(); const c = new Ctx(); c.fill(t); print(c.name, c.zc, c.yaw); } +``` + +Workaround in native_ts_graphics (core/golden_line_station.ts, `SnCtx`'s constructor): the string field +is assigned last, after every other read of `plan`. + +243. Link (pre-alpha145, gc and own): a module that writes `x ? x.handle : null` for a field `x: C | null`, +where `C` is a class of another module, defines the symbol `C..missing`, which the module declaring `C` +defines too, so the program fails to link: `golden_line_steam.ts.obj : error LNK2005: BindingSet..missing +already defined in donut.ts.obj`. Repro (`--emit=obj`, then look for the symbol in the object; +`I:/native_ts_graphics/core/donut.ts` declares `BindingSet` with `readonly handle: BindingSetHandle`, a +`declare class`): + +```ts +import { App, BindingSet } from "I:/native_ts_graphics/core/donut"; +export class Holder { + set: BindingSet | null = null; + release(app: App) { + app.releaseResources([this.set ? this.set.handle : null]); + this.set = null; + } +} +``` + +`h.obj` contains `BindingSet..missing`; the same file with only the field (or `const s = this.set; return +!s;`, or `this.set = app.createBindingSetForLayout(...)`) does not. A local class with an `int` field in +the same shape (`[this.box ? this.box.v : 0]`) does not define `Box..missing` either, so the `declare +class` typed field (or the `T | null` element type of the array) seems to matter. Workaround in +native_ts_graphics (core/golden_line_steam.ts): the field is `BindingSet = new BindingSet(null)`, checked +with `isNull()`, as the other golden_line modules do. + +244. `-mm=own` (pre-alpha145): assigning `length` through a local alias of an array field is refused as if +the alias were stored: "'items' borrows 'this.items' and cannot be stored, returned or captured". Run +with `tslang -mm=own --own-fallback=error --emit=jit` (gc prints `0`): + +```ts +@final +class Holder { + private items: int[] = [1, 2, 3]; + clear(): int { + const items = this.items; + items.length = 0; + return this.items.length; + } +} + +function main() { + const h = new Holder(); + print(h.clear()); +} +``` + +Workaround in native_ts_graphics (core/golden_line_plume.ts): `this.items.length = 0;` first, then the +alias. + +245. `-mm=own` (pre-alpha145): a local bound to a ternary whose two branches are borrowed method results is +refused as if it were stored: "a value that borrows the result of 'Terrain.bridgeSpan' cannot be stored, +returned or captured". Each branch alone (`const f = terrain.bridgeSpan(0);`) is accepted. In the real +module the error came as a pile of unrelated borrows (`terrain.track`, `layout.segments[]`, ...), all at +the ternary. Run with `tslang -mm=own --own-fallback=error --emit=jit` (gc prints `1`): + +```ts +class Span { a = 1.0; b = 2.0; } +@final +class Terrain { + private t: Span = new Span(); + private r: Span = new Span(); + tunnelSpan(i: int): Span { return this.t; } + bridgeSpan(i: int): Span { return this.r; } +} +function first(terrain: Terrain, tunnel: boolean): number { + const f = tunnel ? terrain.tunnelSpan(0) : terrain.bridgeSpan(0); + return f.a; +} +function main() { + print(first(new Terrain(), true)); +} +``` + +Workaround in native_ts_graphics (core/golden_line_shots.ts, shNextSegment): an if/else that copies the +two span ends into locals. Not reduced yet, same module: `const plan = terrain.townPlan; if (plan) { const +d = x - track.X(zz); ... plan.zc ... }` is refused ("'plan' borrows the result of 'Terrain.get_townPlan' +but is used here after it may be released or overwritten"), where `track` is `terrain.track` and +`Track.X` grows its own `xs` array; a small program of that shape compiles, so the World being held as +`Shared` may matter. Workaround: call `track.X` before taking `plan`. + +246. 234-245 re-checked on pre-alpha146 (2026-12-05), each repro above run again and each native_ts_graphics +workaround reverted in place and built with `-mm=own --own-fallback=error`: +- Fixed, workaround gone: 234 (golden_line_world.ts / tender.ts / plume.ts write the hash constants in hex + and `>>>` as rng.js and plume.js do), 237 (water.ts empties one `grid` per cell, textures.ts empties its + locals), 239 (treegen.ts reads `const pts = tube.pts`), 242 (station.ts assigns `name` first), 244 + (plume.ts empties through its locals). 238's closure in tender.ts's `coalLump` (`g.warp((x, y, z) => + ... rand.next() ...)`) compiles again too. +- The repro passes, the real module still fails: + - 236: golden_line_world.ts with its `Map` caches back makes callers in golden_line_trees.ts and + golden_line_structkit.ts fail ("'track' borrows the result of 'World.get_track' but is used here after + it may be released or overwritten", 19 errors in trees.ts alone), and `this.bag = order` in + `Layout` makes structkit.ts:1228 fail ("a value that borrows the result of 'Terrain.near' is used + here after it may be released or overwritten"). So a `Map.set`, or a reassigned `int[]` field, two + modules away still ends every borrow. + - 238: golden_line_saloon.ts's chair-back closure given to `surface()` inside a `for` loop: "'B' is moved + inside a loop but was made outside it". The repro's loop-free case compiles; the loop form doesn't. + - 240's unminimized part: `const r = fn(...)` for a callback parameter in golden_line_traingeo.ts (warp, + surface, orient, lid, loops, extra channels) still gives "'r' takes a second reference; -mm=own cannot + prove a move or a borrow here yet" (seven sites), so `geoTake` stays. + - cabLimb's closures in golden_line_cab.ts (`radiusAt`, `frame`, `ring`, `cap` capturing `part`, `u`, + `w`, `curve`): "'frame' borrows a field but is used here after it may be released or overwritten", + "'part' is used here after its value was moved". +- Still failing as written: 241 (second repro), 243 (`BindingSet..missing` still defined), 245. +- 235's two repros now fail under own ("'p' borrows 'e.next' and cannot be stored, returned or captured"), + and run right under gc; the entry was about gc, so this may be new or may have always been so. + +247. 235's own refusals and the rest of the walk gaps (2026-12-05), fixed; and a first form of deferred releases +(docs/superpowers/specs/2026-12-05-own-deferred-release-design.md, "What is built"): +- Walks own refused though nothing is freed, now accepted with gc's output: a `let` never assigned that borrows + a field and is given to a call lending it back inside a loop (`let c = this.head; while (..) { const e = + nn(c); .. }`); a copy of a walking local the loop condition did not narrow (`while (p) { const e = p; p = + e.next; }`, `const e = p!` under `n > 0 || p !== null`), from a local or a parameter head; a `let` given a + lending call's result of a walking local and stepped (`let z = nn(c); z = z!.next`). Such a copy borrows what + the walk borrows (classifyLocalBorrowingLets takes copies of borrowing locals; a slot that only borrows frees + nothing where it is assigned again), and a parameter walked through a copy is not a move (walksDownOnly). + Copies stored, cut under or cleared while used stay errors (own_err_walk_copy_stored, own_err_walk_copy_cut, + own_err_walk_alias_cut, own_err_walk_lent_copy_cleared). +- A field assigned in the function while a local borrow of its old value is still used (`let q = a; q = + q.next; a.next = null; print(q.i)`): the old value is kept in a function-local temporary and freed at the + function's exit, instead of the error. Only where the assignment runs at most once (no loop round it) and + the function has no `try` that may throw; a cut on every turn of a loop is still refused + (own_err_deferred_release_in_loop, own_err_walk_const_head_cut). Where TSLANG 219 already counts the borrow + (a parameter's field), the count is kept. + The field has to be given a fresh value (a constant, `null`, a literal, `new C()`): `this.head = h.next` gives + it a part of the old value, which the exit's release would free too, so it stays refused + (own_err_list_pop_used_after). It holds for any local borrow, not only walks: 15 former refusals now run with + gc's output (own/own_deferred_*.ts: spec 29's moved-in value read after its field is overwritten, a result + lent out of the field, a literal or array literal borrowing it, merges; TSLANG 47, 50, 55, 66, 84). + own_err_walk_lent_copy_cleared clears through a call now, which is not deferred. +- own_err_result_borrows_argument is accepted now: `pts` takes its own reference (TSLANG 219, USER RULING + 11-27) and prints 2 as gc does; it is own_counted_result_borrows_argument. own_err_list_cut_through_alias + stays refused, now at the use after the cut. +- Still open from 246's list: 241 (its second repro not reproduced on this build). + +Tests `00tslang_issue_235_own_gaps.ts`, `00tslang_issue_235_own_deferred.ts` (every model), the own errors above. + ## TypeScript compiler tests sweep (2026-11-17) Items 86-125 were found on 2026-11-17 by compiling TypeScript's own compiler tests diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index 8aa68b675..f5417bff5 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -91,7 +91,10 @@ A `let` that is only given other locals' values, or fields', and is assigned aga list from a local head is that case (`let node = head; while (node) { ...; node = node.next; }`), from a `const` head too (`const a = new L(0); for (let q: L | null = a; q; q = q.next)`), and so is a step through a call that gives back the node it is given (`q = nn(q).next`). -Giving the head up, or cutting the list, while the walk still reads it is an error. +Giving the head up while the walk still reads it is an error. Cutting the list in the same function +(`q = q.next; a.next = null; print(q.i)`) is allowed when the cut runs at most once (not inside a loop, +not in a function with a `try` that may throw): the part cut off is freed at the function's exit instead +of where it is unlinked. A cut on every turn of a loop is still an error. A local that borrows out of a container and is still used after a call that may free what it borrows takes a reference of its own instead of being an error. The same holds when this function frees it @@ -226,27 +229,45 @@ e3_field_borrow.ts:7:5: error: 'this value' borrows a field and cannot be stored ^ ``` -**A borrow used after its owner let go.** Overwriting `h.node` frees the `Node` that `first` -borrows: +**A borrow used after its owner let go.** `this.head = h.next` frees the `Node` that `h` borrows: ```typescript -function main() { - const h = new Holder(); - const first = h.node; // borrows the Node h owns - h.node = new Node(1); // frees that Node while first still names it: compile error - print(first.value); +class Node { + next: Node | null = null; + constructor(public value: number) {} +} +class List { + head: Node | null = null; + pop(): number { + const h = this.head; // borrows the Node the list owns + if (!h) return -1; + this.head = h.next; // frees that Node, and gives the list its next + return h.value; // compile error + } } ``` ```text -e4_overwrite.ts:8:11: error: 'this value' borrows a field but is used here after it may be released or overwritten - print(first.value); - ^ -e4_overwrite.ts:7:5: note: it may be released or overwritten here - h.node = new Node(1); // frees that Node while first still names it: compile error - ^ +e4_overwrite.ts:11:16: error: 'h' borrows 'this.head' but is used here after it may be released or overwritten + return h.value; // compile error + ^ +e4_overwrite.ts:10:9: note: it may be released or overwritten here + this.head = h.next; // frees that Node, and gives the list its next + ^ ``` +Read what is needed first (`const v = h.value;` before the assignment). Two kinds of overwrite are +not errors: + +- **A local the compiler can count** takes a reference of its own (see below): `const first = h.node; h.node = new Node(1); print(first.value)` prints the old + `Node`'s value. +- **A field given a fresh value in this function while a local still uses the old one** (`= null`, + `= new Node(1)`, a literal): the old value is kept in a hidden local and freed when the function + returns, instead of where it is overwritten. This holds when the assignment runs at most once + (not inside a loop) and the function has no `try` that may throw. A walking local is the usual case + (`let q = a; q = q.next; a.next = null; print(q.i)`). The value the field is given has to be + fresh: `this.head = h.next` gives it a part of the old value, which stays an error as above. + A call can free things too. A call of a function that may overwrite or free what the caller borrows ends the borrow, and the note then points at the call. A call of a function the compiler knows nothing about - a C function, a virtual method another module may override - may free diff --git a/docs/superpowers/specs/2026-12-05-own-deferred-release-design.md b/docs/superpowers/specs/2026-12-05-own-deferred-release-design.md index 9f679e1e7..09c95803a 100644 --- a/docs/superpowers/specs/2026-12-05-own-deferred-release-design.md +++ b/docs/superpowers/specs/2026-12-05-own-deferred-release-design.md @@ -1,6 +1,40 @@ # `-mm=own` deferred releases: free after the borrow ends instead of refusing -Date: 2026-12-05. Status: draft for discussion. No code yet. +Date: 2026-12-05. Status: a first part is built (see "What is built"); the rest is a draft for discussion. + +## What is built + +A narrower form than the design below, in `OwnershipInferencePass::deferrableRelease` and +`applyDeferredReleases`: + +- **Only the release of a field's old value made by this function's own assignment** (`a.next = null`: + rc's `ReleaseSlot` right before the `Store` into a `PropertyRef`), when a local borrow is still used + after it (`let q = a; q = q.next; a.next = null; q.i`), and only where the real run would otherwise + report "borrows ... but is used here after it may be released or overwritten". +- **Only a release that runs at most once:** its block is on no cycle of the function's control flow. A cut + inside a loop (`r2`, `own_err_walk_const_head_cut`, `own_err_deferred_release_in_loop`) is still refused; + the deferral list below is not built. +- **Only in a function with an exit and no `invoke`/landing pad** (no `try` whose body may throw). +- **Only when the field is given a fresh value**: a constant, `null`, a literal, `new C()`, or a local only ever + given one. A value read out of memory may be part of the old value (`this.head = h.next`): the exit's release + would free it with the old value, and own moves it out of the old value, so a later `h.next` reads null. That + stays refused (`own_err_list_pop_used_after`). +- **Any local borrow, not only a walk:** a moved-in value read after its new field is overwritten + (`n.v = a; n.v = [2]; a.length`, spec 29), a result lent out of the field, a literal or array literal + borrowing it, a merge (TSLANG 47, 50, 55, 66, 84). Fifteen tests that were refusals now run, printing what gc + prints (`own/own_deferred_*.ts`).- **Released at the function's exit, not at the borrow's end:** the old value is loaded into a temporary + made at the function's entry (empty, so a cut on a branch that did not run frees nothing), and the + temporary is released before the function's one `ReturnInternal`. This is later than the borrow's end, + which only keeps the memory longer. +- **A count comes first:** the dry run still fails on the conflict, so where the TSLANG 219 repair already + gives the borrower a reference of its own (a borrow of a parameter's field), that is what is used; the + deferral applies to what is still refused after the repairs. +- Tests: `00tslang_issue_235_own_deferred.ts` (every model, with allocations after each cut), and + `own_err_deferred_release_in_loop.ts` (still refused). + +The borrow-inference gaps in the last row of the table below (`d12`, `g5`, `v5`, `w2`, `e3`, +`bfull_nocall`) were fixed separately in the same change: nothing in them is freed. + ## Intent and why @@ -122,7 +156,7 @@ cleanup for temporaries, a deferral inside a `try` region is refused in phase 1. - `WeakRef.deref()` / FinalizationRegistry see the object a little longer. JavaScript promises nothing about when that happens, so this is allowed. -## The scratch cases, classified +## The scratch cases, classified (before the build) Taken from `fable235/` and `t246/`. "own now" and "gc" are what the PR #1132 build printed on 2026-12-05. The last column was **classified by hand** from the rules above: nothing here has been diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index 82a5532cb..755a9a6ce 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -212,6 +212,14 @@ namespace own_inference llvm::SmallVector OwnershipInferencePass::slotEnds(mlir::Value slot) { llvm::SmallVector ends; + // a slot that only borrows (a walking `let`) frees nothing where it is assigned or given back: what its + // borrowers read lasts as long as what it borrows, which its own borrow checks with their uses + // (collectBorrowerUses follows a borrowing local declared from it) + if (auto varOp = slot.getDefiningOp(); varOp && (localBorrowingLets.contains(varOp) || borrowsOnly(varOp))) + { + return ends; + } + for (auto *user : slot.getUsers()) { if (mlir::isa(user)) @@ -759,10 +767,15 @@ namespace own_inference } llvm::SmallVector candidates; - getFunction()->walk([&](mlir_ts::VariableOp varOp) { + llvm::DenseSet candidateSet; + auto eligible = [&](mlir_ts::VariableOp varOp) { // (--own-fallback=count: a counted `let` keeps all of rc's ops, never a borrower's) - if (!localLetCandidates.contains(varOp) || !varOp.getInitializer() || !isOwningVariable(varOp) || - varOp.getCaptured().value_or(false) || countedValues.contains(varOp.getResult())) + return varOp.getInitializer() && isOwningVariable(varOp) && !varOp.getCaptured().value_or(false) && + !countedValues.contains(varOp.getResult()); + }; + + getFunction()->walk([&](mlir_ts::VariableOp varOp) { + if (!localLetCandidates.contains(varOp) || !eligible(varOp)) { return; } @@ -790,7 +803,7 @@ namespace own_inference return true; } - if (!readsOwningLocals(value, varOp)) + if (!readsOwningLocals(value, varOp) && !readsBorrowingLocal(value, varOp, candidateSet)) { return false; } @@ -818,27 +831,111 @@ namespace own_inference } } - if (local && assigned) + if (local && assigned && candidateSet.insert(varOp).second) { candidates.push_back(varOp); } }); + // A local given what a borrowing local reads (`while (p) { const e = p; p = e.next; }`, where `p` is no + // narrowed const but a slot; `let z = nn(c); z = z!.next` of a walking `c`), and, if assigned, only borrows + // after: it borrows what that one borrows, as a copy of a borrower owns nothing. Only of a `let` that is a + // candidate or only borrows: a copy of an owning local still moves it (`let b = q`) + auto onlyBorrowsAfter = [&](mlir_ts::VariableOp varOp) { + return llvm::all_of(varOp.getResult().getUsers(), [&](mlir::Operation *user) { + if (!isAssignmentOf(user, varOp)) + { + return true; + } + + auto value = mlir::cast(user).getValue(); + return letBorrows(value) || readsOwningLocals(value, varOp) || readsBorrowingLocal(value, varOp, candidateSet); + }); + }; + for (auto grew = true; grew;) + { + grew = false; + getFunction()->walk([&](mlir_ts::VariableOp varOp) { + if (candidateSet.contains(varOp) || !eligible(varOp) || + !readsBorrowingLocal(varOp.getInitializer(), varOp, candidateSet) || !onlyBorrowsAfter(varOp)) + { + return; + } + + candidateSet.insert(varOp); + candidates.push_back(varOp); + grew = true; + }); + } + // ...and nothing read out of it is kept: stored, returned, captured (else it stays an owner, - // and its values move into it as before) + // and its values move into it as before). Decided together: a borrower's copy is one only if it + // is kept nowhere, and the borrower only if its copy is one - so all start as borrowers, and any + // that keeps is taken out until none does for (auto varOp : candidates) { localBorrowingLets.insert(varOp); - auto keeps = quietly([&] { - llvm::SmallVector uses; - llvm::SmallVector bookkeeping; - mlir::Operation *declaration = varOp; - return collectBorrowerUses(varOp, declaration, uses, bookkeeping) != nullptr; - }); - if (keeps) + } + + for (auto changed = true; changed;) + { + changed = false; + for (auto varOp : candidates) { - localBorrowingLets.erase(varOp); - } } + if (!localBorrowingLets.contains(varOp)) + { + continue; + } + + auto keeps = quietly([&] { + llvm::SmallVector uses; + llvm::SmallVector bookkeeping; + mlir::Operation *declaration = varOp; + return collectBorrowerUses(varOp, declaration, uses, bookkeeping) != nullptr; + }); + // (a copy of a local that turned out no borrower is no borrower either) + auto copyLost = !localLetCandidates.contains(varOp) && + !readsBorrowingLocal(varOp.getInitializer(), varOp, candidateSet); + if (keeps || copyLost) + { + localBorrowingLets.erase(varOp); + candidateSet.erase(varOp); + changed = true; + } + } + } + } + + bool OwnershipInferencePass::readsBorrowingLocal(mlir::Value value, mlir_ts::VariableOp self, + const llvm::DenseSet &candidateSet) + { + // through views, and through a call whose result borrows its one argument (`nn(c)`) + auto root = rootOf(value); + for (auto depth = 0; depth < 8; ++depth) + { + auto *call = borrowingCall(root); + if (!call) + { + break; + } + + auto indices = resultBorrowsAll(call); + if (indices.size() != 1) + { + break; + } + + root = rootOf(callArgs(call)[indices.front()]); + } + + auto loadOp = root.getDefiningOp(); + auto slot = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::VariableOp(); + if (!slot || slot == self || !isOwningVariable(slot) || slot.getCaptured().value_or(false)) + { + return false; + } + + return localBorrowingLets.contains(slot) || candidateSet.contains(slot) || borrowsOnly(slot); } mlir_ts::VariableOp OwnershipInferencePass::localBorrowerOf(mlir::Operation *acquisition, mlir::Operation *&from) @@ -894,6 +991,14 @@ namespace own_inference llvm::SmallVector kills(givenKills.begin(), givenKills.end()); llvm::SmallVector assignments; auto onlyBorrows = borrowsOnly(borrower); + auto neverAssigned = llvm::none_of(borrower.getResult().getUsers(), [&](mlir::Operation *user) { return isAssignmentOf(user, borrower); }); + // (a copy of a walking local, never assigned: its declaration in a loop gives it the value again, as an + // assignment does) + if (neverAssigned && localBorrowingLets.contains(borrower) && !onlyBorrows) + { + kills.push_back(borrower); + } + if (onlyBorrows) { // its declaration gives it its initializer again, as an assignment gives it a value: what @@ -983,12 +1088,31 @@ namespace own_inference uses.push_back({user, {kills.begin(), kills.end()}}); // rc's release of the temporary a call returns that lends the read back (`const e = nn(c)`, `nn(c).next`) // keeps nothing of it: the call's own check walks it and erases it with the call's bookkeeping - // (checkPlaceRead) - here it is no keep of what the `let` holds (TSLANG 235). Only for a `let` given only - // borrows and assigned (a walk: borrowsOnly): a local that borrows a place once keeps the call's release as a - // keep, and is refused as before (own_err_result_borrows_argument) + // (checkPlaceRead) - here it is no keep of what the `let` holds (TSLANG 235). For a `let` given only + // borrows and assigned (a walk: borrowsOnly), and for one never assigned, which is a `const` that has a + // slot (`let c = this.head; while (..) { const e = nn(c); .. }`): its uses through the call's result + // are its uses, and a use after what it borrows may be freed takes a reference of its own + // (own_counted_result_borrows_argument, TSLANG 219) llvm::SmallVector lentBack; - auto keeping = onlyBorrows ? Keeping{&lentBack, false} : Keeping{nullptr, false}; - if (auto *kept = walkBorrowed(readOp.getResult(), kills, uses, nullptr, keeping)) + auto keeping = onlyBorrows || neverAssigned ? Keeping{&lentBack, false} : Keeping{nullptr, false}; + // (a local that borrows what this one does, declared from the read: its uses are this one's - + // readsBorrowingLocal) + auto nested = [&](mlir::Operation *nestedUser, llvm::ArrayRef nestedKills) { + auto varOp = mlir::dyn_cast(nestedUser); + if (!varOp || varOp == borrower || !localBorrowingLets.contains(varOp) || collectDepth > 8) + { + return false; + } + + // (not this one's kills: the copy reads what it was given after this one is assigned again, and + // that still lasts only as long as its owner) + ++collectDepth; + mlir::Operation *declaration = varOp; + auto *nestedKept = collectBorrowerUses(varOp, llvm::ArrayRef(), uses, bookkeeping, declaration); + --collectDepth; + return nestedKept == nullptr; + }; + if (auto *kept = walkBorrowed(readOp.getResult(), kills, uses, nested, keeping)) { return kept; } diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index cd8d52d28..7f063df5f 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -385,6 +385,8 @@ namespace own_inference dryRunCapture.clear(); countedErrors.clear(); letsUsedAfterCalls.clear(); + deferredReleases.clear(); + usedDeferrals.clear(); mergeShareRetains.clear(); uninitializedLets.clear(); adapterCaptures.clear(); @@ -942,6 +944,11 @@ namespace own_inference toErase.remove_if([&](mlir::Operation *op) { return touchesCounted(op); }); } + if (!dryRun) + { + applyDeferredReleases(toErase); + } + for (auto *op : toErase) { op->erase(); @@ -951,6 +958,132 @@ namespace own_inference return true; } + // A release of a field's old value made by this function's own assignment (`a.next = null`, rc's ReleaseSlot right + // before the store) that a local borrow outlives (`let q = a; q = q.next; a.next = null; q.i`): it may be deferred + // when it runs at most once (no loop round it), the function has one exit and no `try` (a throw past the exit's + // release would leak the value, never free it early - refused all the same, for now) + bool OwnershipInferencePass::deferrableRelease(mlir::Operation *end) + { + auto releaseSlotOp = mlir::dyn_cast_or_null(end); + auto storeOp = releaseSlotOp ? mlir::dyn_cast_or_null(end->getNextNode()) : mlir_ts::StoreOp(); + if (!storeOp || storeOp.getReference() != releaseSlotOp.getSlot() || + !releaseSlotOp.getSlot().getDefiningOp()) + { + return false; + } + + auto &body = getFunction().getFunctionBody(); + if (body.findAncestorOpInRegion(*end) != end) + { + return false; + } + + // the new value is a fresh one (`null`, a literal, `new C()`), or a local only ever given one: a value read + // out of memory may be part of the old value (`this.head = h.next`), which the exit's release would free with + // it and which own moves out of the old value - a later read of `h.next` would see null + std::function fresh = [&](mlir::Value value, int depth) { + while (auto castOp = value.getDefiningOp()) + { + value = castOp.getIn(); + } + + value = rootOf(value); + auto *def = value.getDefiningOp(); + if (!def || depth > 4 || mlir::isa(def) || mlir::isa(def)) + { + return false; + } + + auto loadOp = mlir::dyn_cast(def); + if (!loadOp) + { + return true; + } + + auto varOp = loadOp.getReference().getDefiningOp(); + if (!varOp || varOp.getCaptured().value_or(false) || (varOp.getInitializer() && !fresh(varOp.getInitializer(), depth + 1))) + { + return false; + } + + return llvm::all_of(varOp->getUsers(), [&](mlir::Operation *user) { + auto store = mlir::dyn_cast(user); + return mlir::isa(user) || (store && store.getReference() == varOp.getResult() && + fresh(store.getValue(), depth + 1)); + }); + }; + if (!fresh(storeOp.getValue(), 0)) + { + return false; + } + + // once: its block is on no cycle + auto *start = end->getBlock(); + llvm::SmallVector work(start->getSuccessors().begin(), start->getSuccessors().end()); + llvm::SmallPtrSet seen; + while (!work.empty()) + { + auto *block = work.pop_back_val(); + if (block == start) + { + return false; + } + + if (seen.insert(block).second) + { + work.append(block->getSuccessors().begin(), block->getSuccessors().end()); + } + } + + auto exits = 0; + auto tries = false; + getFunction().walk([&](mlir::Operation *op) { + exits += mlir::isa(op) ? 1 : 0; + tries = tries || mlir::isa(op); + }); + return exits > 0 && !tries; + } + + // The deferred releases (usedDeferrals): the old value is read into a temporary right before the store that + // replaces it, in place of rc's release, and the temporary is released at the function's exit - after every use + // a borrow of it may make here. It holds one value: the release runs once (deferrableRelease). + void OwnershipInferencePass::applyDeferredReleases(llvm::SetVector &toErase) + { + if (usedDeferrals.empty()) + { + return; + } + + auto &entry = getFunction().getFunctionBody().front(); + llvm::SmallVector exits; + getFunction().walk([&](mlir_ts::ReturnInternalOp returnOp) { exits.push_back(returnOp); }); + for (auto *end : usedDeferrals) + { + auto releaseSlotOp = mlir::cast(end); + auto field = releaseSlotOp.getSlot(); + auto refType = mlir::cast(field.getType()); + auto location = end->getLoc(); + + mlir::OpBuilder builder(&getContext()); + builder.setInsertionPointToStart(&entry); + auto empty = builder.create(location, refType.getElementType()); + auto temporary = builder.create(location, refType, empty, builder.getBoolAttr(false), + mlir::IntegerAttr()); + temporary->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); + + builder.setInsertionPoint(end); + auto old = builder.create(location, refType.getElementType(), field); + builder.create(location, old, temporary); + toErase.insert(end); + + for (auto exit : exits) + { + builder.setInsertionPoint(exit); + builder.create(location, temporary); + } + } + } + void OwnershipInferencePass::resetFunctionState() { auto f = getFunction(); diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index d26d88784..8f4eae9cd 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -445,6 +445,13 @@ class OwnershipInferencePass // reference of its own - a copy of a string or an `any`, else a count of the object (USER RULING 11-27, TSLANG // 219): countLetsUsedAfterCalls llvm::SetVector letsUsedAfterCalls; + // A release of a field's old value by this function's own assignment (`a.next = null`) that a borrow outlives: + // whether the real run may defer it (deferrableRelease, asked once each), and those it deferred - the old value + // is kept in a temporary and released at the function's exit (applyDeferredReleases) + llvm::DenseMap deferredReleases; + llvm::SetVector usedDeferrals; + bool deferrableRelease(mlir::Operation *end); + void applyDeferredReleases(llvm::SetVector &toErase); // A closure read out of a place and captured by an adapter this compiler made (the dry run's): counted, the // adapter's box holding an extra owner of it (TSLANG 220, capturedByAdapter) llvm::SetVector adapterCaptures; @@ -561,6 +568,9 @@ class OwnershipInferencePass bool borrowedByLocalLets(mlir::Value value, llvm::SetVector &toErase); // Does `value` read owning locals other than `self` - one, or a merge of several (and of null)? bool readsOwningLocals(mlir::Value value, mlir_ts::VariableOp self); + // a read of a local that only borrows (a walking `let`, or a candidate for one), through views and lending calls + bool readsBorrowingLocal(mlir::Value value, mlir_ts::VariableOp self, const llvm::DenseSet &candidateSet); + int collectDepth = 0; // The `let` of localBorrowingLets that an acquisition gives `value` to - its declaration's // `ts.RetainSlot`, or rc's retain right before an assignment - and in `from`, that declaration or // assignment; else null. @@ -782,7 +792,7 @@ class OwnershipInferencePass // Where an owning local stops holding its value: each release of its slot and each store // into it. - static llvm::SmallVector slotEnds(mlir::Value slot); + llvm::SmallVector slotEnds(mlir::Value slot); // A borrow (spec 2.2, verdict 2): `borrower` takes no reference and gives none back, so its // retain and every release of its slot go, and the owner keeps its own. Sound while no use of diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 6f3ec2c94..3d760c1fb 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -713,8 +713,10 @@ namespace own_inference slotValue = slotLoad.getReference(); } + // (a local never assigned that borrows what a walking one does, `const e = p`, the same: it is given + // its initializer only - readsBorrowingLocal) auto borrowingLet = slotValue ? slotValue.getDefiningOp() : mlir_ts::VariableOp(); - if (borrowingLet && borrowsOnly(borrowingLet)) + if (borrowingLet && (borrowsOnly(borrowingLet) || localBorrowingLets.contains(borrowingLet))) { chain.anyPlace = true; bases.push_back(rootOf(borrowingLet.getInitializer())); @@ -2047,6 +2049,24 @@ namespace own_inference { if ((use.op != drop || !use.callee) && heldAt(use, drop) && reachableAfter(drop, use.op, use.kills)) { + // a release of a field's old value by this function's own assignment (`a.next = null`): the real + // run defers it to the function's exit where it may be (deferrableRelease), after every use a + // borrow makes here; the dry run still fails on it, so a repair (a count, TSLANG 219) comes first + if (!dryRun) + { + auto [known, inserted] = deferredReleases.try_emplace(drop, false); + if (inserted) + { + known->second = deferrableRelease(drop); + } + + if (known->second) + { + usedDeferrals.insert(drop); + return false; + } + } + // a string given to the very call that may release it, when the call keeps it, or // is a callback - a function value, which nothing can say `@nodrops` of: the call // gets a copy diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 9fc47d1a9..0e8d8a632 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -3243,6 +3243,7 @@ namespace own_signature // read of the local itself. Not through a handle, whose payload others hold too. auto value = storeOp.getValue(); auto throughField = false; + auto copies = 0; for (;;) { auto loadOp = rootOf(value).getDefiningOp(); @@ -3256,6 +3257,19 @@ namespace own_signature break; } + // ...or of a copy of it, never assigned (`while (p) { const e = p; p = e.next; }`, where the loop's + // condition did not narrow `p` into a const): the copy holds what the local holds + if (auto copy = loadOp.getReference().getDefiningOp(); + copy && copy != varOp && ++copies <= 4 && copy.getInitializer() && !copy.getCaptured().value_or(false) && + llvm::none_of(copy.getResult().getUsers(), [&](mlir::Operation *copyUser) { + auto copyStore = mlir::dyn_cast(copyUser); + return copyStore && copyStore.getReference() == copy.getResult(); + })) + { + value = copy.getInitializer(); + continue; + } + auto field = loadOp.getReference().getDefiningOp(); if (!field || !mlir::isa(field.getObjectRef().getType())) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index a4b5f7827..982fe62e8 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -2818,8 +2818,8 @@ foreach(issue236_n 236 237 238 239 240 240_temps 240_fuzz) endforeach() # TSLANG 245: a ternary of two borrowing calls' results borrows each; TSLANG 246: a closure in a loop borrows a const # holding a call's result (238's loop form); TSLANG 235 under own: list walks from a const head and through a -# call lending its argument back; every model runs them -foreach(issue245_n 245 246_named_call 235_own) +# call lending its argument back; a release deferred to the function's exit; every model runs them +foreach(issue245_n 245 246_named_call 235_own 235_own_gaps 235_own_deferred) foreach(issue245_mm gc rc none own) tslang_add_test(NAME test-jit-00tslang_issue_${issue245_n}-${issue245_mm} COMMAND test-runner -jit -mm=${issue245_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue245_n}.ts") tslang_add_test(NAME test-compile-00tslang_issue_${issue245_n}-${issue245_mm} COMMAND test-runner -mm=${issue245_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_${issue245_n}.ts") @@ -7953,7 +7953,6 @@ set(own_error_cases "own_err_param_moved_twice_one_call|:5:12: error: 'p' is used here after its value was moved" "own_err_object_literal_counted_read|:9:11: error: a value that borrows 'G[.]items[[][]]' is used here after it may be released or overwritten" "own_err_counted_read_used_in_try|:11:14: error: 'e' borrows 'k[.]arr[[][]]' but is used here after it may be released or overwritten" - "own_err_result_borrows_argument|:5:88: error: 'pts' borrows 'tube.pts' and cannot be stored, returned or captured" "own_err_borrow_and_move|:8:5: error: '[^']*' is moved here while '[^']*' borrows it" "own_err_borrow_bound_method|:25:11: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" "own_err_borrow_catch_local|:28:13: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" @@ -7961,8 +7960,12 @@ set(own_error_cases "own_err_borrow_derived_ref|:28:5: error: '[^']*' borrows '[^']*' but is used here after '[^']*' is released or overwritten" "own_err_const_alias_move|:12:5: error: '[^']*' borrows '[^']*' and cannot be assigned" "own_err_const_alias_field|:15:5: error: '[^']*' is moved here while '[^']*' borrows it" - "own_err_field_alias|:9:11: error: a value that borrows 'n[.]v' is used here after it may be released or overwritten" "own_err_walk_const_head_cut|:9:60: error: 'q' borrows 'q.next' but is used here after it may be released or overwritten" + "own_err_walk_copy_cut|:7:27: error: 'p' borrows 'e.next' but is used here after it may be released or overwritten" + "own_err_walk_copy_stored|:8:30: error: 'p' borrows 'e.next' and cannot be stored, returned or captured" + "own_err_walk_alias_cut|:7:69: error: 'q' borrows 'q.next' but is used here after it may be released or overwritten" + "own_err_walk_lent_copy_cleared|:8:102: error: 'c' borrows 'this[.]head[.]next' but is used here after it may be released or overwritten" + "own_err_deferred_release_in_loop|:4:173: error: 'q' borrows 'q[.]next' but is used here after it may be released or overwritten" "own_err_walk_const_head_cleared|:11:17: error: 'q' borrows 'q.next' but is used here after it may be released or overwritten" "own_err_walk_const_head_moved|:9:5: error: 'q' is used here after its value was moved" "own_err_closure_calls_closure_returned|:12:5: error: 'part' is captured by a closure that escapes, and is still used here" @@ -7989,13 +7992,10 @@ set(own_error_cases "own_err_push_let|:7:9: error: '[^']*' is used here after its value was moved" "own_err_push_loop|:6:33: error: '[^']*' is moved inside a loop but was made outside it" "own_err_field_loop|:10:9: error: '[^']*' is moved inside a loop but was made outside it" - "own_err_union_moved|:10:11: error: a value that borrows 'h[.]c' is used here after it may be released or overwritten" - "own_err_merge_read_overwritten|:28:5: error: a value that borrows 'n[.]c' is used here after it may be released or overwritten" "own_err_alias_read_popped|:28:9: error: a value that borrows an element is used here after it may be released or overwritten" "own_err_container_read_stored|:27:5: error: a value that borrows 'h[.]c' cannot be stored, returned or captured" "own_err_field_let_assigned|:12:5: error: 'a' borrows 'h[.]a' and cannot be assigned. -mm=own cannot prove that yet" "own_err_borrowed_result_stored|a value that borrows the result of 'firstOf' cannot be stored, returned or captured" - "own_err_borrowed_result_outlives|:19:11: error: '[^']*' borrows the result of 'firstOf' but is used here after it may be released or overwritten" "own_err_borrowed_result_let_outlives|borrows the result of 'H.first' but is used here after it may be released or overwritten" "own_err_borrowed_result_escapes|could return a borrow or keep a parameter, but it is used other than by a call" "own_err_borrowed_result_family|an override in its class family disagrees" @@ -8102,7 +8102,6 @@ set(own_error_cases "own_err_lends_and_borrows|'firstOf' cannot say both '@lends' and '@borrows'" "own_err_lends_two_params|'@lends' of 'pick' names 'a', 'b', but its body returns a borrow of 'a'" "own_err_lends_index_64|'@lends' of 'K[.]pick' names 'p63', but a method's '@lends' can name only its first 64 arguments, the receiver among them" - "own_err_lends_outlives|:20:11: error: '[^']*' borrows the result of 'firstOf' but is used here after it may be released or overwritten" "own_err_generator_method_this|'this' 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: a value is used here after the value it borrows is released or overwritten" "own_err_shared_moved_in|:10:11: error: '[^']*' is used here after its value was moved" @@ -8123,7 +8122,6 @@ set(own_error_cases "own_err_shared_place_tuple|:31:39: error: a value that borrows 'p[.]child' cannot be stored, returned or captured" "own_err_shared_literal_borrowed|the initializer of global 'b' takes a second reference" "own_err_iface_field_result|borrows the result of 'dirOf' but is used here after it may be released or overwritten" - "own_err_read_after_move_overwritten|:10:11: error: a value that borrows 'h[.]c' is used here after it may be released or overwritten" "own_err_read_after_move_view|:12:11: error: a value that borrows 'h[.]c' is used here after it may be released or overwritten" "own_err_read_after_move_call|:11:11: error: a value that borrows 'h[.]c' is used here after it may be released or overwritten" "own_err_read_after_move_loop|:25:14: error: '[^']*' is used here after its value was moved" @@ -8148,7 +8146,6 @@ set(own_error_cases "own_err_borrowing_record_field_written|:15:9: error: 'r' borrows 'this[.]pos' and cannot be stored, returned or captured" "own_err_borrowing_record_cell|:25:16: error: '[^']*' borrows a captured variable but is used here after it may be released or overwritten" "own_err_borrowing_record_kept_param|:30:12: error: '[^']*' borrows '[^']*' but is used here after it may be released or overwritten" - "own_err_borrowing_record_place_overwritten|:28:11: error: a value that borrows 'c[.]pos' is used here after it may be released or overwritten" "own_err_borrowing_record_open|:17:31: error: a value that borrows 'p' cannot be stored, returned or captured" "own_err_borrowing_record_borrowed_again|:29:11: error: '[^']*' borrows the result of 'A[.]hit' but is used here after it may be released or overwritten" "own_err_destructure_element_reassigned|:10:11: error: 'a' borrows 'pair..' but is used here after it may be released or overwritten" @@ -8204,9 +8201,7 @@ set(own_error_cases "own_err_fill_after_call|:21:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" "own_err_fill_in_loop|:23:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" "own_err_fill_other_field|:20:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" - "own_err_fill_after_fill_call|:19:20: error: '[^']*' borrows the result of 'Dev.fill' but is used here after it may be released or overwritten" "own_err_field_moved_call_between|:12:9: error: a value that borrows 'this[.]level' cannot be stored, returned or captured" - "own_err_list_lookahead_cut|:17:20: error: 'k' borrows 'c[.]next' but is used here after it may be released or overwritten" "own_err_list_walk_up|:21:24: error: 'm' borrows 'c[.]next' but is used here after it may be released or overwritten" "own_err_list_pop_used_after|:14:16: error: 'h' borrows 'this[.]head' but is used here after it may be released or overwritten" "own_err_list_next_kept_twice|:14:9: error: a value that borrows 'this[.]head[.]next' cannot be stored, returned or captured" @@ -8246,7 +8241,6 @@ set(own_error_cases "own_err_weakref_returned|:4:55: error: '[^']*' borrows the object a WeakRef refers to and cannot be stored, returned or captured" "own_err_weakref_captured|:5:92: error: '[^']*' is used here after its value was moved" "own_err_weakref_after_call|:5:137: error: a value that borrows the object a WeakRef refers to is used here after it may be released or overwritten" - "own_err_weakref_after_release|:4:137: error: a value that borrows the object a WeakRef refers to is used here after it may be released or overwritten" "own_err_weakref_thread|:14:15: error: -mm=own cannot make a WeakRef to a 'Node' in a program that shares what may hold one with another thread" "own_err_literal_let_used_after|:5:11: error: '[^']*' is used here after its value was moved" "own_err_literal_let_twice|:4:12: error: '[^']*' is used here after its value was moved" @@ -8260,18 +8254,16 @@ set(own_error_cases "own_err_weakref_local_reassigned|:5:108: error: '[^']*' borrows the object a WeakRef refers to but is used here after it may be released or overwritten" "own_err_list_refill_from_param|:13:9: error: a value that borrows 'n[.]next' cannot be stored, returned or captured" "own_err_list_unlink_walk|:16:9: error: 'n' borrows 'n[.]next' but is used here after it may be released or overwritten" - "own_err_list_cut_through_alias|:13:15: error: 'c' borrows 'l[.]head' and cannot be stored, returned or captured" + "own_err_list_cut_through_alias|:16:21: error: 'c' borrows 'c[.]next' but is used here after it may be released or overwritten" "own_err_list_push_ctor_throws|:11:35: error: a value that borrows 'this[.]head' cannot be stored, returned or captured" "own_err_tree_field_given_twice|:13:11: error: a value that borrows 't[.]l' cannot be stored, returned or captured" "own_err_list_push_through_this|:11:23: error: a value that borrows 'this[.]h' cannot be stored, returned or captured" "own_err_param_walk_mixed|:18:82: error: '[^']*' is used here after its value was moved" "own_err_override_lends|:13:5: error: method 'read' returns a borrow .* but the method of 'Base' it overrides does not" "own_err_moved_field_overwritten|:15:25: error: a value that borrows 'this[.]layout' is used here after it may be released or overwritten" - "own_err_moved_param_field_dropped|:13:15: error: a value that borrows 'h[.]c' is used here after it may be released or overwritten" "own_err_pushed_then_popped|:14:16: error: a value that borrows 'this[.]texs..' is used here after it may be released or overwritten" "own_err_kept_by_constructor_reset|:16:11: error: a value that borrows 'app[.]s' is used here after it may be released or overwritten" "own_err_merge_moved_twice|:19:9: error: a value that borrows 'this[.]a' cannot be stored, returned or captured" - "own_err_borrowing_array_field_reset|:13:16: error: a value that borrows 'this[.]a' is used here after it may be released or overwritten" "own_err_parameter_let_stored|:10:5: error: a value takes a second reference. -mm=own cannot prove a move or a borrow here yet" "own_err_merged_locals_overwritten|:11:16: error: '[^']*' borrows '[^']*' but is used here after '[^']*' is released or overwritten" "own_err_merged_locals_moved|:12:5: error: '[^']*' is moved here while '[^']*' borrows it" @@ -8280,7 +8272,6 @@ set(own_error_cases "own_err_local_stored_element_reset|:22:12: error: a value that borrows 'h[.]items..' is used here after it may be released or overwritten" "own_err_pushed_object_field_popped|:24:16: error: a value that borrows 'h[.]frames..' is used here after it may be released or overwritten" "own_err_split_let_stored|:14:9: error: 'dir' borrows 'this[.]dir' and cannot be stored, returned or captured" - "own_err_split_let_field_overwritten|:14:16: error: 'dir' borrows 'this[.]dir' but is used here after it may be released or overwritten" "own_err_pushed_or_null_popped|:17:23: error: a value that borrows 'this[.]views..' is used here after it may be released or overwritten" "own_err_kept_local_array_popped|:16:22: error: a value that borrows 'this[.]nodes..' is used here after it may be released or overwritten" "own_err_kept_field_rebound|:29:5: error: '[^']*' is used here after its value was moved" @@ -8289,7 +8280,6 @@ set(own_error_cases "own_err_pushed_let_popped|:17:9: error: a value that borrows 'this[.]pipes..' is used here after it may be released or overwritten" "own_err_moved_on_some_paths_used|:21:15: error: '[^']*' is used here after its value was moved" "own_err_escaped_this_field_read|:24:28: error: '[^']*' is used here after its value was moved" - "own_err_borrowed_result_holder_stored|:26:16: error: a value that borrows 'this[.]chain' is used here after it may be released or overwritten" "own_err_function_expression_name|:11:13: error: 'this' is a parameter, returned here, but -mm=own cannot tell the callers of this function expression that the result borrows it" "own_err_named_walk_let|:11:40: error: 'node' borrows 'node[.]next' but is used here after it may be released or overwritten" "own_err_closure_reassigned_captured_call|:10:17: error: 'this' borrows a field and cannot be stored, returned or captured" @@ -8324,6 +8314,7 @@ endforeach() # free what it borrows, takes a reference of its own. Each runs, printing what it prints under rc (a block freed too # early reads the churn's values); those calling a declared function that nothing defines are compiled only. set(own_counted_cases + "own_counted_result_borrows_argument|^2" "own_counted_exported_virtual_call|^red area=4" "own_counted_call_in_try_drops|^1" "own_counted_cell_assigned_in_closure|^1" @@ -8414,6 +8405,25 @@ set(own_counted_cases "own_counted_callback_escapes|^1 1[\r\n]*$" "own_counted_declared_drops|^3[\r\n]*$" ) +# ...and what own accepts since deferred releases (TSLANG 247): a field assigned in the function while a local +# still uses its old value; the old value is freed at the function's exit. Each reaches the assignment, allocates +# after it and reads afterwards, printing what gc prints. +list(APPEND own_counted_cases + "own_deferred_field_alias|^9 503500[\r\n]*$" + "own_deferred_union_moved|^7 7000[\r\n]*$" + "own_deferred_merge_read_overwritten|^1 3 -1 1 4000[\r\n]*$" + "own_deferred_borrowed_result_outlives|^49 5004000[\r\n]*$" + "own_deferred_lends_outlives|^19 19000[\r\n]*$" + "own_deferred_read_after_move_overwritten|^100 3 51500[\r\n]*$" + "own_deferred_borrowing_record_place_overwritten|^49 49000[\r\n]*$" + "own_deferred_fill_after_fill_call|^12 0 12000[\r\n]*$" + "own_deferred_list_lookahead_cut|^3 -2 2 3000[\r\n]*$" + "own_deferred_weakref_after_release|^1 1000[\r\n]*$" + "own_deferred_moved_param_field_dropped|^5 5000[\r\n]*$" + "own_deferred_borrowing_array_field_reset|^37 37000[\r\n]*$" + "own_deferred_split_let_field_overwritten|^1 10 6500[\r\n]*$" + "own_deferred_borrowed_result_holder_stored|^3 3 3000[\r\n]*$" + "own_deferred_walk_lent_copy_cleared|^3 true 3000[\r\n]*$") foreach(own_counted_case ${own_counted_cases}) string(FIND "${own_counted_case}" "|" own_counted_sep) string(SUBSTRING "${own_counted_case}" 0 ${own_counted_sep} own_counted_name) diff --git a/tslang/test/tester/own/own_err_result_borrows_argument.ts b/tslang/test/tester/own/own_counted_result_borrows_argument.ts similarity index 69% rename from tslang/test/tester/own/own_err_result_borrows_argument.ts rename to tslang/test/tester/own/own_counted_result_borrows_argument.ts index 9396c5b11..e3b89a33f 100644 --- a/tslang/test/tester/own/own_err_result_borrows_argument.ts +++ b/tslang/test/tester/own/own_counted_result_borrows_argument.ts @@ -1,5 +1,5 @@ -// -mm=own, TSLANG 239: a call's result borrows the arguments it says; `keep` returns its argument, so -// `k` borrows `pts`, which cannot be stored. +// -mm=own, TSLANG 239: a call's result borrows the arguments it says; `keep` returns its argument, so `k` borrows +// `pts`, which `tube.pts = []` frees before `k.x`: `pts` takes a reference of its own (TSLANG 219's rule), and prints 2. @final class P { constructor(public x: number) {} keep(v: P): P { return v; } } class Tube { pts: P[] = []; } function f(tube: Tube): number { const pts = tube.pts; const t = new P(0.0); const k = t.keep(pts[0]); tube.pts = []; return k.x; } diff --git a/tslang/test/tester/own/own_deferred_borrowed_result_holder_stored.ts b/tslang/test/tester/own/own_deferred_borrowed_result_holder_stored.ts new file mode 100644 index 000000000..e1f96993a --- /dev/null +++ b/tslang/test/tester/own/own_deferred_borrowed_result_holder_stored.ts @@ -0,0 +1,41 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_borrowed_result_holder_stored: +// `texture` borrows the result of `Chain.texture`, and the store into `this.chain` releases the Chain holding it. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +@final +class Tex { + constructor(public id: int) {} +} +@final +class Chain { + private textures: Tex[] = [new Tex(1), new Tex(2)]; + @lends("this") + texture(i: int): Tex { + return this.textures[i]; + } +} +@final +class App { + private chain = new Chain(); + frame(): int { + const texture = this.chain.texture(1); + this.chain = new Chain(); + churn(); + return texture.id + this.chain.texture(0).id; + } +} +function main() { + let t: int = 0; + for (let i: int = 0; i < 1000; i++) t += new App().frame(); + const a = new App(); + print(a.frame(), a.frame(), t); +} diff --git a/tslang/test/tester/own/own_deferred_borrowed_result_outlives.ts b/tslang/test/tester/own/own_deferred_borrowed_result_outlives.ts new file mode 100644 index 000000000..0ebde72d5 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_borrowed_result_outlives.ts @@ -0,0 +1,35 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_borrowed_result_outlives: +// `c` borrows what `firstOf(h)` returned, a field under `h`, which is overwritten before `c.x` is read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class C { + constructor(public x: number) {} +} +class H { + c: C = new C(0); +} +function firstOf(h: H) { + return h.c; +} +function f(k: number): number { + const h = new H(); + h.c = new C(k); + const c = firstOf(h); + h.c = new C(9); + churn(); + return c.x * 10 + h.c.x; +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += f(i); + print(f(4), t); +} diff --git a/tslang/test/tester/own/own_deferred_borrowing_array_field_reset.ts b/tslang/test/tester/own/own_deferred_borrowing_array_field_reset.ts new file mode 100644 index 000000000..80d02e380 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_borrowing_array_field_reset.ts @@ -0,0 +1,32 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_borrowing_array_field_reset: +// TSLANG_ISSUES 55: an array literal of fields, a field written before a read out of the array. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +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(); + this.a.id = 7; + churn(); + return xs[0].id * 10 + this.a.id; + } +} +function main() { + let t: int = 0; + for (let i: int = 0; i < 1000; i++) t += new K().run(); + print(new K().run(), t); +} diff --git a/tslang/test/tester/own/own_deferred_borrowing_record_place_overwritten.ts b/tslang/test/tester/own/own_deferred_borrowing_record_place_overwritten.ts new file mode 100644 index 000000000..cf2d643e3 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_borrowing_record_place_overwritten.ts @@ -0,0 +1,33 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_borrowing_record_place_overwritten: +// the literal borrows the field `c.pos`, which is given a new value before the literal is read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class V { + constructor(public x: number) {} +} +interface Ray { start: V; dir: V; } +function len(r: Ray) { return r.start.x + r.dir.x; } +class Cam { + pos: V = new V(3); +} +function f(): number { + const c = new Cam(); + const r: Ray = { start: c.pos, dir: new V(1) }; + c.pos = new V(9); + churn(); + return len(r) * 10 + c.pos.x; +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += f(); + print(f(), t); +} diff --git a/tslang/test/tester/own/own_deferred_field_alias.ts b/tslang/test/tester/own/own_deferred_field_alias.ts new file mode 100644 index 000000000..b18d8a900 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_field_alias.ts @@ -0,0 +1,27 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_field_alias: +// `a`'s array moved into `n.v`, and `n.v` overwritten before `a` is read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class N { v: number[] = []; } +function f(k: number): number { + const a: number[] = [1, k]; + const n = new N(); + n.v = a; + n.v = [2]; + churn(); + return a.length + a[1] + n.v[0]; +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += f(i); + print(f(5), t); +} diff --git a/tslang/test/tester/own/own_deferred_fill_after_fill_call.ts b/tslang/test/tester/own/own_deferred_fill_after_fill_call.ts new file mode 100644 index 000000000..813fc4504 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_fill_after_fill_call.ts @@ -0,0 +1,39 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_fill_after_fill_call: +// TSLANG_ISSUES 47: `fill` fills `cached` and returns it; `bad` then stores a new value over it and reads +// what `fill` returned. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class Q { + constructor(public h: number) {} +} +class Dev { + cached: Q | undefined; + fill(): Q { + if (!this.cached) this.cached = new Q(1); + return this.cached; + } + bad(): number { + if (!this.cached) { + const x = this.fill(); + this.cached = new Q(2); + churn(); + return x.h * 10 + this.cached.h; + } + return 0; + } +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += new Dev().bad(); + const d = new Dev(); + print(d.bad(), d.bad(), t); +} diff --git a/tslang/test/tester/own/own_deferred_lends_outlives.ts b/tslang/test/tester/own/own_deferred_lends_outlives.ts new file mode 100644 index 000000000..1f6a8f58c --- /dev/null +++ b/tslang/test/tester/own/own_deferred_lends_outlives.ts @@ -0,0 +1,35 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_lends_outlives: +// `n` is lent by `firstOf(l)` (`@lends`), and `l.first` is overwritten before `n.v` is read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +export class Node { + constructor(public v: number) {} +} +export class List { + first: Node = new Node(1); +} +@lends("l") +export function firstOf(l: List): Node { + return l.first; +} +function f(): number { + const l = new List(); + const n = firstOf(l); + l.first = new Node(9); + churn(); + return n.v * 10 + l.first.v; +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += f(); + print(f(), t); +} diff --git a/tslang/test/tester/own/own_deferred_list_lookahead_cut.ts b/tslang/test/tester/own/own_deferred_list_lookahead_cut.ts new file mode 100644 index 000000000..8f3f38db9 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_list_lookahead_cut.ts @@ -0,0 +1,46 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_list_lookahead_cut: +// `k` names the node `c.next = null` cuts off a walking local's node. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class Node { + next: Node | null = null; + constructor(public v: number) {} +} +class List { + head: Node | null = null; + f() { + let c = this.head; + if (!c) return -1; + c = c.next; + if (!c) return -1; + const k = c.next; + c.next = null; + churn(); + return k ? k.v : -2; + } +} +function build(): List { + const l = new List(); + l.head = new Node(1); + l.head.next = new Node(2); + l.head.next.next = new Node(3); + l.head.next.next.next = new Node(4); + return l; +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += build().f(); + const l = build(); + const a = l.f(); + const b = l.f(); + print(a, b, l.head!.next!.v, t); +} diff --git a/tslang/test/tester/own/own_deferred_merge_read_overwritten.ts b/tslang/test/tester/own/own_deferred_merge_read_overwritten.ts new file mode 100644 index 000000000..7347b1109 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_merge_read_overwritten.ts @@ -0,0 +1,35 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_merge_read_overwritten: +// `c` is `n.c` or `m.c` through a merge, and `n.c` is overwritten before the read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class C { + v: number[] = []; + constructor(public x: number) {} +} +class N { + c: C | null = null; +} +function f(withN: boolean, withM: boolean): number { + const n = new N(); + const m = new N(); + if (withN) n.c = new C(1); + if (withM) m.c = new C(3); + const c = n.c ?? m.c; + n.c = new C(2); + churn(); + return c ? c.x : -1; +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += f(true, false) + f(false, true) + f(false, false) + f(true, true); + print(f(true, false), f(false, true), f(false, false), f(true, true), t); +} diff --git a/tslang/test/tester/own/own_deferred_moved_param_field_dropped.ts b/tslang/test/tester/own/own_deferred_moved_param_field_dropped.ts new file mode 100644 index 000000000..1868b2c66 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_moved_param_field_dropped.ts @@ -0,0 +1,32 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_moved_param_field_dropped: +// TSLANG_ISSUES 50: a value moved into a field of a parameter, the parameter given into a field that is then +// cleared; the value is read after. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class C { x: int = 5; } +class H { c: C | null = null; } +class K { + h: H | null = null; + run(h: H): int { + const c = new C(); + h.c = c; + this.h = h; + this.h = null; + churn(); + return c.x; + } +} +function main() { + let t: int = 0; + for (let i: int = 0; i < 1000; i++) t += new K().run(new H()); + print(new K().run(new H()), t); +} diff --git a/tslang/test/tester/own/own_deferred_read_after_move_overwritten.ts b/tslang/test/tester/own/own_deferred_read_after_move_overwritten.ts new file mode 100644 index 000000000..34b360374 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_read_after_move_overwritten.ts @@ -0,0 +1,29 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_read_after_move_overwritten: +// `c` moved into `h.c`, which is overwritten on one path before `c` is read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class C { x: number = 5; } +class H { c: C | null = null; } +function f(k: number): number { + const h = new H(); + const c = new C(); + c.x = k; + h.c = c; + if (c.x > 1) { h.c = null; } + churn(); + return c.x + (h.c ? 100 : 0); +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += f(i & 3); + print(f(0), f(3), t); +} diff --git a/tslang/test/tester/own/own_deferred_split_let_field_overwritten.ts b/tslang/test/tester/own/own_deferred_split_let_field_overwritten.ts new file mode 100644 index 000000000..74e7b4d3a --- /dev/null +++ b/tslang/test/tester/own/own_deferred_split_let_field_overwritten.ts @@ -0,0 +1,34 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_split_let_field_overwritten: +// TSLANG_ISSUES 66: a `let` borrowing a field, given a fresh value on some paths only, the field overwritten. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +function rot(v: number[], a: number) { + return [v[0] * a, v[1], v[2]]; +} +class Cam { + dir: number[] = [1.0, 0.0, 1.0]; + turn(c: boolean) { + let dir = this.dir; + if (c) { + dir = rot(dir, 2.0); + } + this.dir = [5.0, 0.0, 0.0]; + churn(); + return dir[0]; + } +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) { const c = new Cam(); t += c.turn((i & 1) == 0) + c.turn(false); } + const c = new Cam(); + print(c.turn(false), c.turn(true), t); +} diff --git a/tslang/test/tester/own/own_deferred_union_moved.ts b/tslang/test/tester/own/own_deferred_union_moved.ts new file mode 100644 index 000000000..c85a02b11 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_union_moved.ts @@ -0,0 +1,28 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_union_moved: +// `c` moved into the nullable field, which is set to null before `c` is read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class C { x: number = 5; v: number[] = [1, 2]; } +class H { c: C | null = null; } +function f(): number { + const h = new H(); + const c = new C(); + h.c = c; + h.c = null; + churn(); + return c.x + c.v[1]; +} +function main() { + let t: number = 0; + for (let i = 0; i < 1000; i++) t += f(); + print(f(), t); +} diff --git a/tslang/test/tester/own/own_deferred_walk_lent_copy_cleared.ts b/tslang/test/tester/own/own_deferred_walk_lent_copy_cleared.ts new file mode 100644 index 000000000..8ccbcad24 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_walk_lent_copy_cleared.ts @@ -0,0 +1,25 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_walk_lent_copy_cleared: +// a `let` given a lending call of a walking local (`let z = nn(c)`), the list's head cleared under it. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class L { i: int; next: L | null = null; constructor(i: int) { this.i = i; } } +function nn(n: L | null): L { return n!; } +class H { + head: L | null = null; + walk(): int { let c = this.head; c = c!.next; const e = nn(c); let z: L | null = e; this.head = null; churn(); z = z!.next; return z ? z.i : -1; } +} +function main() { + let t: int = 0; + for (let i: int = 0; i < 1000; i++) { const h = new H(); h.head = new L(1); h.head!.next = new L(2); h.head!.next!.next = new L(3); t += h.walk(); } + const h = new H(); h.head = new L(1); h.head!.next = new L(2); h.head!.next!.next = new L(3); + print(h.walk(), h.head === null, t); +} diff --git a/tslang/test/tester/own/own_deferred_weakref_after_release.ts b/tslang/test/tester/own/own_deferred_weakref_after_release.ts new file mode 100644 index 000000000..590cf3d92 --- /dev/null +++ b/tslang/test/tester/own/own_deferred_weakref_after_release.ts @@ -0,0 +1,17 @@ +// -mm=own: accepted since deferred releases (TSLANG 247): the assignment's release of the field's old value, +// which a local still uses, is kept in a temporary and freed at the function's exit. Was own_err_weakref_after_release: +// a WeakRef's object, read through `deref()`, whose owner field is cleared before the read. + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t: number[] = [777, 778]; + s += t.length; + } + return s; +} + +class Node { v = 1; } +class Holder { w: WeakRef | null = null; n: Node | null = null; kept: Node | null = null; } +function f(): number { const h = new Holder(); const n = new Node(); h.w = new WeakRef(n); h.n = n; const p = h.w.deref(); h.n = null; churn(); return p ? p.v : 0; } +function main() { let t: number = 0; for (let i = 0; i < 1000; i++) t += f(); print(f(), t); } diff --git a/tslang/test/tester/own/own_err_borrowed_result_holder_stored.ts b/tslang/test/tester/own/own_err_borrowed_result_holder_stored.ts deleted file mode 100644 index 9f2d3c9df..000000000 --- a/tslang/test/tester/own/own_err_borrowed_result_holder_stored.ts +++ /dev/null @@ -1,32 +0,0 @@ -// -mm=own rejects: `texture` borrows the result of `Chain.texture`, a place not known, and the store -// into `this.chain` releases a Chain, whose type holds textures: it may free the one borrowed -// (TSLANG 84 refines by type only where the released type cannot hold the borrowed one). -@final -class Tex { - constructor(public id: int) {} -} - -@final -class Chain { - private textures: Tex[] = [new Tex(1), new Tex(2)]; - - @lends("this") - texture(i: int): Tex { - return this.textures[i]; - } -} - -@final -class App { - private chain = new Chain(); - - frame(): int { - const texture = this.chain.texture(1); - this.chain = new Chain(); - return texture.id; - } -} - -function main() { - print(new App().frame()); -} diff --git a/tslang/test/tester/own/own_err_borrowed_result_outlives.ts b/tslang/test/tester/own/own_err_borrowed_result_outlives.ts deleted file mode 100644 index 234f2690a..000000000 --- a/tslang/test/tester/own/own_err_borrowed_result_outlives.ts +++ /dev/null @@ -1,20 +0,0 @@ -// -mm=own, phase 4 rejects: `c` borrows what `firstOf(h)` returned, a field under `h`; the -// overwrite of `h.c` destroys it before `c.x` reads it. -class C { - constructor(public x: number) {} -} - -class H { - c: C = new C(0); -} - -function firstOf(h: H) { - return h.c; -} - -function main() { - const h = new H(); - const c = firstOf(h); - h.c = new C(9); - print(c.x); -} 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 deleted file mode 100644 index 3c33bce5c..000000000 --- a/tslang/test/tester/own/own_err_borrowing_array_field_reset.ts +++ /dev/null @@ -1,17 +0,0 @@ -// 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_borrowing_record_place_overwritten.ts b/tslang/test/tester/own/own_err_borrowing_record_place_overwritten.ts deleted file mode 100644 index 836880029..000000000 --- a/tslang/test/tester/own/own_err_borrowing_record_place_overwritten.ts +++ /dev/null @@ -1,29 +0,0 @@ -// -mm=own rejects: the literal borrows the field `c.pos` (spec 32), which is given a new value - its -// old one freed - before the literal is read. -class V { - constructor(public x: number) {} -} - -function churn() { - const keep: V[] = []; - for (let i = 0; i < 200; i++) { - keep.push(new V(77777)); - } - return keep.length; -} - -interface Ray { start: V; dir: V; } - -function len(r: Ray) { return r.start.x + r.dir.x; } - -class Cam { - pos: V = new V(3); -} - -function main() { - const c = new Cam(); - const r: Ray = { start: c.pos, dir: new V(1) }; - c.pos = new V(9); - churn(); - print(len(r)); -} diff --git a/tslang/test/tester/own/own_err_deferred_release_in_loop.ts b/tslang/test/tester/own/own_err_deferred_release_in_loop.ts new file mode 100644 index 000000000..140c3d865 --- /dev/null +++ b/tslang/test/tester/own/own_err_deferred_release_in_loop.ts @@ -0,0 +1,4 @@ +// The release `a.next = null` makes runs on every turn of the loop: one temporary cannot hold every old value until +// the function's exit, so it is not deferred and stays refused. +class L { i: int; next: L | null = null; constructor(i: int) { this.i = i; } } +function main() { let s: int = 0; for (let j: int = 0; j < 3; j++) { const a = new L(0); a.next = new L(1 + j); let q: L | null = a; q = q.next; a.next = null; if (q) s += q.i; } print(s); } diff --git a/tslang/test/tester/own/own_err_field_alias.ts b/tslang/test/tester/own/own_err_field_alias.ts deleted file mode 100644 index 31bfc76cd..000000000 --- a/tslang/test/tester/own/own_err_field_alias.ts +++ /dev/null @@ -1,11 +0,0 @@ -// -mm=own rejects: `a`'s array moved into `n.v`, and `n.v` is overwritten before `a` is read: the -// overwrite frees the array `a` still names (spec 29). -class N { v: number[] = []; } -function main() { - const a: number[] = [1]; - const n = new N(); - n.v = a; - n.v = [2]; - print(a.length); - print("done."); -} diff --git a/tslang/test/tester/own/own_err_fill_after_fill_call.ts b/tslang/test/tester/own/own_err_fill_after_fill_call.ts deleted file mode 100644 index 3e29714a8..000000000 --- a/tslang/test/tester/own/own_err_fill_after_fill_call.ts +++ /dev/null @@ -1,29 +0,0 @@ -// TSLANG_ISSUES 47: `fill` only fills `cached`, so its own calls free nothing - but called between -// `bad`'s test and its store, it may have filled the field, and the store then frees what `fill` -// returned. A call in between is judged by facts that count every fill as a drop. -class Q { - constructor(public h: number) {} -} - -class Dev { - cached: Q | undefined; - fill(): Q { - if (!this.cached) this.cached = new Q(1); - return this.cached; - } - - bad(): number { - if (!this.cached) { - const x = this.fill(); - this.cached = new Q(2); - return x.h; - } - - return 0; - } -} - -function main() { - const d = new Dev(); - print(d.bad()); -} diff --git a/tslang/test/tester/own/own_err_lends_outlives.ts b/tslang/test/tester/own/own_err_lends_outlives.ts deleted file mode 100644 index 961173921..000000000 --- a/tslang/test/tester/own/own_err_lends_outlives.ts +++ /dev/null @@ -1,21 +0,0 @@ -// -mm=own rejects: `n` is lent by `firstOf(l)`, a field under `l`; the overwrite of `l.first` -// destroys it before `n.v` reads it. `@lends` is what tells the caller so. -export class Node { - constructor(public v: number) {} -} - -export class List { - first: Node = new Node(1); -} - -@lends("l") -export function firstOf(l: List): Node { - return l.first; -} - -function main() { - const l = new List(); - const n = firstOf(l); - l.first = new Node(9); - print(n.v); -} diff --git a/tslang/test/tester/own/own_err_list_lookahead_cut.ts b/tslang/test/tester/own/own_err_list_lookahead_cut.ts deleted file mode 100644 index 78f464860..000000000 --- a/tslang/test/tester/own/own_err_list_lookahead_cut.ts +++ /dev/null @@ -1,21 +0,0 @@ -// A field of the node a walking local holds may be overwritten (the node itself stays) - but not -// while something read out of that field is still used: `k` names the node `c.next = null` frees. -class Node { - next: Node | null = null; - constructor(public v: number) {} -} - -class List { - head: Node | null = null; - f() { - let c = this.head; - if (!c) return -1; - c = c.next; - if (!c) return -1; - const k = c.next; - c.next = null; - return k ? k.v : -2; - } -} - -function main() { const l = new List(); l.head = new Node(1); print(l.f()); } diff --git a/tslang/test/tester/own/own_err_merge_read_overwritten.ts b/tslang/test/tester/own/own_err_merge_read_overwritten.ts deleted file mode 100644 index f763bfabe..000000000 --- a/tslang/test/tester/own/own_err_merge_read_overwritten.ts +++ /dev/null @@ -1,31 +0,0 @@ -// -mm=own, phase 3 rejects: `c` is `n.c` or `m.c` through a merge, and `n.c` is overwritten before -// the read. -class C { - v: number[] = []; - constructor(public x: number) {} -} - -function churn() { - const junk: C[] = []; - for (let i = 0; i < 64; i++) { - const c = new C(999); - c.v.push(99); - junk.push(c); - } -} - -class N { - c: C | null = null; -} - -function main() { - const n = new N(); - const m = new N(); - n.c = new C(1); - const c = n.c ?? m.c; - n.c = new C(2); - churn(); - if (c) { - print(c.x); - } -} diff --git a/tslang/test/tester/own/own_err_moved_param_field_dropped.ts b/tslang/test/tester/own/own_err_moved_param_field_dropped.ts deleted file mode 100644 index 7a4fa5e8e..000000000 --- a/tslang/test/tester/own/own_err_moved_param_field_dropped.ts +++ /dev/null @@ -1,16 +0,0 @@ -// TSLANG_ISSUES 50: a value moved into a field of a parameter is a borrow of that field after the -// move; the parameter given away into a field that is then cleared frees it, and the value with -// it, so the use after is refused (v0.0-pre-alpha127 took it and printed 0). -class C { x: int = 5; } -class H { c: C | null = null; } -class K { - h: H | null = null; - run(h: H) { - const c = new C(); - h.c = c; - this.h = h; - this.h = null; - print(c.x); - } -} -function main() { new K().run(new H()); } diff --git a/tslang/test/tester/own/own_err_read_after_move_overwritten.ts b/tslang/test/tester/own/own_err_read_after_move_overwritten.ts deleted file mode 100644 index 467f12c39..000000000 --- a/tslang/test/tester/own/own_err_read_after_move_overwritten.ts +++ /dev/null @@ -1,11 +0,0 @@ -// -mm=own rejects: `c` moved into `h.c`, which is overwritten on one path before `c` is read (spec -// 29). -class C { x: number = 5; } -class H { c: C | null = null; } -function main() { - const h = new H(); - const c = new C(); - h.c = c; - if (c.x > 1) { h.c = null; } - print(c.x); -} diff --git a/tslang/test/tester/own/own_err_split_let_field_overwritten.ts b/tslang/test/tester/own/own_err_split_let_field_overwritten.ts deleted file mode 100644 index 95f8732e2..000000000 --- a/tslang/test/tester/own/own_err_split_let_field_overwritten.ts +++ /dev/null @@ -1,21 +0,0 @@ -// TSLANG_ISSUES 66: a `let` borrowing a field, given a fresh value on some paths only, is still the -// field's on the others: the field overwritten frees it. -function rot(v: number[], a: number) { - return [v[0] * a, v[1], v[2]]; -} -class Cam { - dir: number[] = [1.0, 0.0, 1.0]; - turn(c: boolean) { - let dir = this.dir; - if (c) { - dir = rot(dir, 2.0); - } - this.dir = [5.0, 0.0, 0.0]; - return dir[0]; - } -} -function main() { - const c = new Cam(); - print(c.turn(false)); - print("done."); -} diff --git a/tslang/test/tester/own/own_err_union_moved.ts b/tslang/test/tester/own/own_err_union_moved.ts deleted file mode 100644 index c42e652cf..000000000 --- a/tslang/test/tester/own/own_err_union_moved.ts +++ /dev/null @@ -1,12 +0,0 @@ -// -mm=own rejects: `c` is moved into the nullable field through the widening view, and the field -// is set to null - freeing `c` - before `c` is read (spec 29). -class C { x: number = 5; } -class H { c: C | null = null; } -function main() { - const h = new H(); - const c = new C(); - h.c = c; - h.c = null; - print(c.x); - print("done."); -} diff --git a/tslang/test/tester/own/own_err_walk_alias_cut.ts b/tslang/test/tester/own/own_err_walk_alias_cut.ts new file mode 100644 index 000000000..845c9fc7f --- /dev/null +++ b/tslang/test/tester/own/own_err_walk_alias_cut.ts @@ -0,0 +1,9 @@ +// -mm=own: two locals on one node (`const p = q; q = q.next`); cutting through one while the other reads is refused. +class L { i: int; next: L | null = null; constructor(i: int) { this.i = i; } } +function main() { + const a = new L(0); a.next = new L(1); a.next.next = new L(2); + let s: int = 0; + let q: L | null = a; + while (q) { const p = q; q = q.next; p.next = null; if (q) s += q.i; } + print(s); +} diff --git a/tslang/test/tester/own/own_err_walk_copy_cut.ts b/tslang/test/tester/own/own_err_walk_copy_cut.ts new file mode 100644 index 000000000..2b6598488 --- /dev/null +++ b/tslang/test/tester/own/own_err_walk_copy_cut.ts @@ -0,0 +1,9 @@ +// -mm=own: a copy of a walking local (`const e = p`) borrows what the walk does; cutting the list it reads is refused. +class L { i: int; next: L | null = null; constructor(i: int) { this.i = i; } } +function main() { + const a = new L(0); a.next = new L(1); a.next.next = new L(2); + let s: int = 0; + let p: L | null = a; + while (p) { const e = p; p = e.next; if (e.i == 1) a.next = null; s += e.i; } + print(s); +} diff --git a/tslang/test/tester/own/own_err_walk_copy_stored.ts b/tslang/test/tester/own/own_err_walk_copy_stored.ts new file mode 100644 index 000000000..3ad6c174a --- /dev/null +++ b/tslang/test/tester/own/own_err_walk_copy_stored.ts @@ -0,0 +1,10 @@ +// -mm=own: a copy of a walking local (`const e = p`) borrows the list; storing it into a field is refused. +class L { i: int; next: L | null = null; constructor(i: int) { this.i = i; } } +class H { t: L | null = null; } +function main() { + const a = new L(0); a.next = new L(1); + const h = new H(); + let p: L | null = a; + while (p) { const e = p; p = e.next; h.t = e; } + print(h.t!.i); +} diff --git a/tslang/test/tester/own/own_err_walk_lent_copy_cleared.ts b/tslang/test/tester/own/own_err_walk_lent_copy_cleared.ts new file mode 100644 index 000000000..aaf798830 --- /dev/null +++ b/tslang/test/tester/own/own_err_walk_lent_copy_cleared.ts @@ -0,0 +1,10 @@ +// -mm=own: a `let` given a lending call of a walking local (`let z = nn(c)`) borrows the field; clearing it in a call (`this.clear()`) is refused: +// a release in another function is not deferred. +class L { i: int; next: L | null = null; constructor(i: int) { this.i = i; } } +function nn(n: L | null): L { return n!; } +class H { + head: L | null = null; + clear() { this.head = null; } + walk() { let c = this.head; c = c!.next; const e = nn(c); let z: L | null = e; this.clear(); z = z!.next; print(z === null); } +} +function main() { const h = new H(); h.head = new L(1); h.head!.next = new L(2); h.walk(); } diff --git a/tslang/test/tester/own/own_err_weakref_after_release.ts b/tslang/test/tester/own/own_err_weakref_after_release.ts deleted file mode 100644 index 92c6bb1a9..000000000 --- a/tslang/test/tester/own/own_err_weakref_after_release.ts +++ /dev/null @@ -1,4 +0,0 @@ -// The owner's release of a Node ends a borrow of the object a WeakRef refers to. -class Node { v = 1; } -class Holder { w: WeakRef | null = null; n: Node | null = null; kept: Node | null = null; } -function main() { const h = new Holder(); const n = new Node(); h.w = new WeakRef(n); h.n = n; const p = h.w.deref(); h.n = null; print(p ? p.v : 0); } diff --git a/tslang/test/tester/tests/00tslang_issue_235_own_deferred.ts b/tslang/test/tester/tests/00tslang_issue_235_own_deferred.ts new file mode 100644 index 000000000..6a67e84a3 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_235_own_deferred.ts @@ -0,0 +1,79 @@ +// -mm=own deferred releases: a field assigned in this function (`a.next = null`) while a local borrow of its old +// value is still used (`let q = a; q = q.next; a.next = null; q.i`). The old value is kept in a function-local +// temporary and freed at the function's exit, after the borrow's last use; a cut on one branch only frees what the +// temporary holds, nothing where the cut did not run. Each runs as under gc and rc; the allocations after each cut +// would reuse a block freed too early. +class L { + i: int; + next: L | null = null; + constructor(i: int) { this.i = i; } +} + +let G = 1; + +function churn(): int { + let s: int = 0; + for (let k: int = 0; k < 64; k++) { + const t = new L(100 + k); + s += t.i & 1; + } + + return s; +} + +function cutAfterStep(): int { + const a = new L(0); + a.next = new L(G); + a.next.next = new L(G + 1); + let q: L | null = a; + q = q.next; + a.next = null; + churn(); + return q ? q.i : 0; +} + +function cutAfterTwoSteps(): int { + const a = new L(0); + a.next = new L(G); + a.next.next = new L(G + 1); + let q: L | null = a; + q = q.next; + q = q!.next; + a.next = null; + churn(); + return q ? q.i : 0; +} + +function cutOnBranch(c: boolean): int { + const a = new L(0); + a.next = new L(G + 2); + let q: L | null = a; + q = q.next; + if (c) { + a.next = null; + } + + churn(); + return q ? q.i : 0; +} + +function cutThenReplace(): int { + const a = new L(0); + a.next = new L(G); + const n = a.next; + a.next = new L(G + 4); + churn(); + return n.i + (a.next ? a.next.i : 0); +} + +function main() { + let total: int = 0; + for (let k: int = 0; k < 1000; k++) { + total += cutAfterStep() + cutAfterTwoSteps() + cutOnBranch((k & 1) == 0) + cutThenReplace(); + } + + print(cutAfterStep(), cutAfterTwoSteps(), cutOnBranch(true), cutOnBranch(false), cutThenReplace(), total); + assert(cutAfterStep() == 1 && cutAfterTwoSteps() == 2 && cutOnBranch(true) == 3 && cutThenReplace() == 6); + assert(total == 12000); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_235_own_gaps.ts b/tslang/test/tester/tests/00tslang_issue_235_own_gaps.ts new file mode 100644 index 000000000..6b45ef45c --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_235_own_gaps.ts @@ -0,0 +1,104 @@ +// TSLANG 235 under -mm=own, the borrow-inference gaps: walks own refused though nothing is freed. +// - a `let` never assigned that borrows a field, given to a call lending it back inside a loop (`let c = this.head; +// while (..) { const e = nn(c); .. }`): a `const` with a slot; +// - a copy of a walking local that the loop condition did not narrow (`while (p) { const e = p; p = e.next; }`, +// `const e = p!` under `n > 0 || p !== null`): it borrows what the walk borrows; +// - a `let` given a lending call's result of a walking local, and stepped (`let z = nn(c); z = z!.next`). +// Each runs as under gc and rc; nodes are made at run time. +class L { + i: int; + next: L | null = null; + constructor(i: int) { this.i = i; } +} + +function nn(n: L | null): L { return n!; } + +class H { + head: L | null = null; + + sumHead(times: int): int { + let c = this.head; + let s: int = 0; + while (times > 0) { + const e = nn(c); + s += e.i; + times--; + } + return s; + } + + secondIsLast(): boolean { + let c = this.head; + c = c!.next; + const e = nn(c); + let z: L | null = e; + z = z!.next; + return z === null; + } +} + +function walkTruthy(a: L): int { + let s: int = 0; + let p: L | null = a; + while (p) { + const e = p; + p = e.next; + s += e.i; + } + return s; +} + +function walkCounted(a: L): int { + let s: int = 0; + let p: L | null = a; + let n: int = 1; + while (n > 0 || p !== null) { + const e = p!; + p = e.next; + n--; + s += e.i; + } + return s; +} + +function walkNested(a: L): int { + let p: L | null = a; + let steps: int = 0; + while (p !== null) { + let n: int = 1; + while (n > 0 || p !== null) { + const e = p!; + p = e.next; + n--; + if (p === null) { + break; + } + } + steps++; + if (steps > 10) { + break; + } + } + return steps; +} + +let G: int = 1; + +function main() { + const h = new H(); + h.head = new L(G); + h.head!.next = new L(G + 1); + + const a = new L(G - 1); + a.next = new L(G); + a.next!.next = new L(G + 1); + + const r1 = h.sumHead(3); + const r2 = h.secondIsLast(); + const r3 = walkTruthy(a); + const r4 = walkCounted(a); + const r5 = walkNested(a); + print(r1, r2, r3, r4, r5); + assert(r1 == 3 && r2 && r3 == 3 && r4 == 3 && r5 == 1); + print("done."); +} From ab2b5e2c1bb5588d616c4291df2100889e182049 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 5 Dec 2026 20:16:02 +0000 Subject: [PATCH 2/2] CI (Linux): build tslang with -j 4 and 8 GB more swap - -j 8 ran the 16 GB runner out of memory and it lost contact; rm -rf for the build folder cleanup Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cmake-test-release-linux.yml | 14 ++++++++++++-- .github/workflows/create-release.yml | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cmake-test-release-linux.yml b/.github/workflows/cmake-test-release-linux.yml index 16ac5c308..00d166e19 100644 --- a/.github/workflows/cmake-test-release-linux.yml +++ b/.github/workflows/cmake-test-release-linux.yml @@ -49,7 +49,7 @@ jobs: # from GitHub each run is quick; GC is rebuilt every run anyway. - name: Delete __Build TS folders continue-on-error: true - run: rm -R ./__build/tslang/ninja/release + run: rm -rf ./__build/tslang/ninja/release shell: sh - name: Create __Build Folders @@ -139,11 +139,21 @@ jobs: shell: sh run: cmake ../../../../tslang -G "Ninja" -DCMAKE_BUILD_TYPE=${{ env.BUILD_TYPE }} -Wno-dev + # The hosted runner has 4 cores and 16 GB: 8 compiles of the MLIR sources at once (2-3 GB each) ran it out of + # memory, and it dropped off ("The hosted runner lost communication with the server"). One job per core, as + # create-release.yml builds, and 8 GB more swap for the peaks. + - name: Add swap + continue-on-error: true + shell: sh + run: | + sudo fallocate -l 8G /swapfile_build && sudo chmod 600 /swapfile_build && sudo mkswap /swapfile_build && sudo swapon /swapfile_build + free -h + - name: Build continue-on-error: false working-directory: ${{github.workspace}}/__build/tslang/ninja/release shell: sh - run: cmake --build . --config ${{ env.BUILD_TYPE }} -j 8 + run: cmake --build . --config ${{ env.BUILD_TYPE }} -j 4 # The JIT tests are the ones named test-jit-*; every other test is the exe leg's. - name: Test (Ubuntu 22.04, ${{ matrix.programs }} programs, ${{ matrix.kind }}) diff --git a/.github/workflows/create-release.yml b/.github/workflows/create-release.yml index 0d313702f..e03b1b88b 100644 --- a/.github/workflows/create-release.yml +++ b/.github/workflows/create-release.yml @@ -339,7 +339,7 @@ jobs: - name: Delete __Build TS folders continue-on-error: true - run: rm -R ./__build/tslang/ninja/release + run: rm -rf ./__build/tslang/ninja/release shell: sh - name: Create __Build Folders