Loop rewrite: every array method, in any combination, split into loops at the methods without one #162

Merged
sionzee merged 14 commits from evobug/inline-array-fusion into main 2026-11-24 14:44:12 +01:00
Owner

The loop rewrite (crates/safe_ts_core/src/loops.rs) handles every array method and every combination of them. A chain is a list of steps, split into loops at the methods that have no loop of their own.

  • Passing elements on: filter, map, flatMap, flat(d) (literal d ≤ 4), and slice(a, b) with non-negative literal bounds (these become the loop's bounds and stop early). Each step's index is the position in the array it would have seen: the loop index until a filter/flatMap/flat, then a counter of what got through.
  • Ending the loop: forEach, reduce (also without an initial value: the same TypeError on an empty array, and the first element is peeled when reduce is alone), some, every, find, findIndex, findLast/findLastIndex (a backwards loop of their own), includes (SameValueZero), indexOf, lastIndexOf, at(k ≥ 0).
  • Any other method (toSorted, join, concat, reverse, with, a slice with a negative bound, ...): the loop before it fills a buffer, the method runs on that buffer as written (its arguments stay in place), and a new loop starts over its result. A method in last position is folded into the statement: return __lr1.join(",").
  • Holes: map and slice keep them (a preallocated buffer), the skipping methods skip them, and find/includes/at/findLast see undefined. A step that comes after a map sees a hole without the map callback having run.
  • Callbacks: an arrow written in place is inlined as before. Anything else (a callback by name, a member, a function expression, an arrow with defaults or var) is evaluated once before the loop and called with the method's arguments, with a typeof check like the method makes. thisArg becomes .call(thisArg, ...). A later step that reads the array parameter, or a function by name whose parameter count the file doesn't show, starts a new loop over the buffer, which is the array the step asks for. A later step that mentions the receiver does the same.
  • Expression positions: when the chain is the first thing its statement evaluates (send(xs.map(f)), if, return [..], for (const x of ...), export const, an arrow's expression body), the loop goes before the statement and what came before the chain moves after the loop. Elsewhere (&&, ?:, while conditions) the chain becomes an arrow called in place. Measured: called in place is as fast as the hoisted form.
  • @inline now applies to every chain in the marked statement. It is found by the statement's span, because a const's value can be visited where it is read.

Bench (packages/std/bench/fusion.bench.ts, npm run bench:fusion, also part of bench:check and its baseline): the callback versions live in a // @safe-ts legacy file (listed under legacyFiles), and the same code with @inline in a normal file, both run through the transform loader. Times are ns per element, at 10 / 1,000 / 100,000 elements:

case callbacks loops allocation (B/el)
filter→map(i)→forEach 16.2 / 11.6 / 31.2 3.6 / 1.8 / 3.8 24–38 → 0
flatMap→filter→reduce 72 / 70 / 70 4.0 / 2.2 / 2.0 142–164 → 0
filter→map→includes 8.9 / 8.6 / 23.6 3.4 / 1.5 / 1.5 24–28 → 0
filter→map→findLast 12.6 / 10.0 / 22.0 14.3 / 5.8 / 7.5 24–34 → 18
map→slice→join 26.4 / 3.4 / 14.7 21.0 / 0.87 / 0.01 8–38 → 0–26
map→toSorted→map 29 / 67 / 133 30 / 72 / 106 same
map→reduce (no init) 5.7 / 5.6 / 26.0 3.8 / 1.8 / 2.3 8–13 → 0
chain, before the statement 7.8 / 8.6 / 32.5 3.3 / 1.3 / 1.4 24–28 → 0
chain, called in place 8.5 / 8.7 / 26.6 4.2 / 1.3 / 1.3 24–28 → 0–10
callbacks by name 26.7 / 24.8 / 31.2 4.1 / 2.0 / 1.9 24–28 → 0
the request's example 75 / 110 / 213 56 / 105 / 170 113–212 → 107–182
lone flatMap / findLast 4.3–4.8x / 7.9–8.6x faster
lone find / reduce (no init) / filter→toSorted 0.8–1.1x

What happens on plain arrays without @inline (same rules as before: the receiver is known to be an array, and callbacks before another step are pure): every chain of two or more steps, plus forEach, map (also by name), flatMap, flat and findLast* on their own. A lone filter, find, some, every, reduce or includes stays a call. Where the bench said no, the design changed:

  • join always runs on the buffer. Building the string in the loop was 1.1–1.5x faster but allocated 2x as much.
  • toSorted is not turned into sort on a buffer the chain owns. V8 sorts a copy either way, and toSorted was as fast or faster in both the bench and a separate microbench.
  • A buffer whose length is known is preallocated. A push-grown buffer is what made map→toSorted→map lose before.

Tests:

  • packages/std/test/fusion/: 420 generated chains of 2–4 steps (gen.ts --write). Each one is compared with the legacy twin on dense, sparse (holes in the middle and at the end), empty, holes-only, one-element and NaN/-0 inputs: same value (isDeepStrictEqual, so holes and -0 count), same calls in the last step, same error. The test also asserts every one of them was rewritten.
  • behaviour.test.ts covers placements (while and && called in place, hoisted, for...of, arrow body), automatic rewrites on plain arrays, thisArg, flat(2), the request's example, and the one visible difference: a callback that throws.
  • The transformed TS of those files type-checks (typecheck:emit).
  • Rust: new transform.rs tests and the loops fixture updated.
  • Results: cargo nextest run --workspace 416/416, npm run test:std 463/463, npm run typecheck and npm run test:docs pass.

Docs: docs/guide/loops.md (new "How a chain becomes loops" section, the measured table, "When the code stays a callback", the throw and early-exit difference), docs/rules/inline.md, the CHANGELOG, the README, performance-myths, notes.

Known gaps (not changed here):

  • An impure last step can still change what earlier pure steps read: items.filter(done).forEach(remove), where remove splices items. This was already so before this PR. Inline callbacks that name the receiver now start a new loop, but a function called from the last step isn't seen.
  • The Node loader's disk cache doesn't key on legacyFiles: after listing a file there, a stale rewritten result is served until the cache is cleared (SAFE_TS_CACHE=0).

Update after CI (the first run failed, and CI logs aren't readable from here, so I reproduced every step of test.yml/bench.yml locally):

  • Rebased onto main (#149, #151 and #156 had landed). That brought main's mut_two_names ratchet counts with it.
  • test:rewrites in full mode now passes. A ?. after a step (xs.map(f)?.forEach(g)), on a method (xs.map?.(f)), or on a receiver declared an array (xs?.map(f) with xs: T[]) changes nothing and is rewritten. A ?. in a receiver that may be absent (c?.xs.map(f)) is refused: the loop would run where the chain is skipped. Ratchet: new inline optional-call 3 → 1, text inline optional-call gone, plus one new line with its reason (new inline hoist-const 1: the harness moves the chain out of the @inline statement).
  • bench:check: the fusion ratios on 10 elements get a 4x tolerance. findLast on 10 elements landed exactly on its 2x limit on a retry here.
  • All of these pass locally on head ec5e4680: cargo nextest run --workspace, full test:rewrites, test:std (471 with #163), typecheck, test:soundness, test:vite, test:docs, bench:check.

🤖 Generated with Claude Code

The loop rewrite (`crates/safe_ts_core/src/loops.rs`) handles every array method and every combination of them. A chain is a list of steps, split into loops at the methods that have no loop of their own. - **Passing elements on**: `filter`, `map`, `flatMap`, `flat(d)` (literal `d` ≤ 4), and `slice(a, b)` with non-negative literal bounds (these become the loop's bounds and stop early). Each step's index is the position in the array it would have seen: the loop index until a `filter`/`flatMap`/`flat`, then a counter of what got through. - **Ending the loop**: `forEach`, `reduce` (also without an initial value: the same `TypeError` on an empty array, and the first element is peeled when `reduce` is alone), `some`, `every`, `find`, `findIndex`, `findLast`/`findLastIndex` (a backwards loop of their own), `includes` (SameValueZero), `indexOf`, `lastIndexOf`, `at(k ≥ 0)`. - **Any other method** (`toSorted`, `join`, `concat`, `reverse`, `with`, a `slice` with a negative bound, ...): the loop before it fills a buffer, the method runs on that buffer as written (its arguments stay in place), and a new loop starts over its result. A method in last position is folded into the statement: `return __lr1.join(",")`. - **Holes**: `map` and `slice` keep them (a preallocated buffer), the skipping methods skip them, and `find`/`includes`/`at`/`findLast` see `undefined`. A step that comes after a `map` sees a hole without the `map` callback having run. - **Callbacks**: an arrow written in place is inlined as before. Anything else (a callback by name, a member, a function expression, an arrow with defaults or `var`) is evaluated once before the loop and called with the method's arguments, with a `typeof` check like the method makes. `thisArg` becomes `.call(thisArg, ...)`. A later step that reads the `array` parameter, or a function by name whose parameter count the file doesn't show, starts a new loop over the buffer, which is the array the step asks for. A later step that mentions the receiver does the same. - **Expression positions**: when the chain is the first thing its statement evaluates (`send(xs.map(f))`, `if`, `return [..]`, `for (const x of ...)`, `export const`, an arrow's expression body), the loop goes before the statement and what came before the chain moves after the loop. Elsewhere (`&&`, `?:`, `while` conditions) the chain becomes an arrow called in place. Measured: called in place is as fast as the hoisted form. - `@inline` now applies to every chain in the marked statement. It is found by the statement's span, because a `const`'s value can be visited where it is read. **Bench** (`packages/std/bench/fusion.bench.ts`, `npm run bench:fusion`, also part of `bench:check` and its baseline): the callback versions live in a `// @safe-ts legacy` file (listed under `legacyFiles`), and the same code with `@inline` in a normal file, both run through the transform loader. Times are ns per element, at 10 / 1,000 / 100,000 elements: | case | callbacks | loops | allocation (B/el) | |---|---|---|---| | filter→map(i)→forEach | 16.2 / 11.6 / 31.2 | 3.6 / 1.8 / 3.8 | 24–38 → 0 | | flatMap→filter→reduce | 72 / 70 / 70 | 4.0 / 2.2 / 2.0 | 142–164 → 0 | | filter→map→includes | 8.9 / 8.6 / 23.6 | 3.4 / 1.5 / 1.5 | 24–28 → 0 | | filter→map→findLast | 12.6 / 10.0 / 22.0 | 14.3 / 5.8 / 7.5 | 24–34 → 18 | | map→slice→join | 26.4 / 3.4 / 14.7 | 21.0 / 0.87 / 0.01 | 8–38 → 0–26 | | map→toSorted→map | 29 / 67 / 133 | 30 / 72 / 106 | same | | map→reduce (no init) | 5.7 / 5.6 / 26.0 | 3.8 / 1.8 / 2.3 | 8–13 → 0 | | chain, before the statement | 7.8 / 8.6 / 32.5 | 3.3 / 1.3 / 1.4 | 24–28 → 0 | | chain, called in place | 8.5 / 8.7 / 26.6 | 4.2 / 1.3 / 1.3 | 24–28 → 0–10 | | callbacks by name | 26.7 / 24.8 / 31.2 | 4.1 / 2.0 / 1.9 | 24–28 → 0 | | the request's example | 75 / 110 / 213 | 56 / 105 / 170 | 113–212 → 107–182 | | lone flatMap / findLast | 4.3–4.8x / 7.9–8.6x faster | | | | lone find / reduce (no init) / filter→toSorted | 0.8–1.1x | | | **What happens on plain arrays without `@inline`** (same rules as before: the receiver is known to be an array, and callbacks before another step are pure): every chain of two or more steps, plus `forEach`, `map` (also by name), `flatMap`, `flat` and `findLast*` on their own. A lone `filter`, `find`, `some`, `every`, `reduce` or `includes` stays a call. Where the bench said no, the design changed: - `join` always runs on the buffer. Building the string in the loop was 1.1–1.5x faster but allocated 2x as much. - `toSorted` is **not** turned into `sort` on a buffer the chain owns. V8 sorts a copy either way, and `toSorted` was as fast or faster in both the bench and a separate microbench. - A buffer whose length is known is preallocated. A `push`-grown buffer is what made `map→toSorted→map` lose before. **Tests**: - `packages/std/test/fusion/`: 420 generated chains of 2–4 steps (`gen.ts --write`). Each one is compared with the legacy twin on dense, sparse (holes in the middle and at the end), empty, holes-only, one-element and NaN/-0 inputs: same value (`isDeepStrictEqual`, so holes and -0 count), same calls in the last step, same error. The test also asserts every one of them was rewritten. - `behaviour.test.ts` covers placements (`while` and `&&` called in place, hoisted, `for...of`, arrow body), automatic rewrites on plain arrays, `thisArg`, `flat(2)`, the request's example, and the one visible difference: a callback that throws. - The transformed TS of those files type-checks (`typecheck:emit`). - Rust: new `transform.rs` tests and the loops fixture updated. - Results: `cargo nextest run --workspace` 416/416, `npm run test:std` 463/463, `npm run typecheck` and `npm run test:docs` pass. **Docs**: `docs/guide/loops.md` (new "How a chain becomes loops" section, the measured table, "When the code stays a callback", the throw and early-exit difference), `docs/rules/inline.md`, the CHANGELOG, the README, performance-myths, notes. **Known gaps** (not changed here): - An impure *last* step can still change what earlier pure steps read: `items.filter(done).forEach(remove)`, where `remove` splices `items`. This was already so before this PR. Inline callbacks that name the receiver now start a new loop, but a function called from the last step isn't seen. - The Node loader's disk cache doesn't key on `legacyFiles`: after listing a file there, a stale rewritten result is served until the cache is cleared (`SAFE_TS_CACHE=0`). **Update after CI** (the first run failed, and CI logs aren't readable from here, so I reproduced every step of `test.yml`/`bench.yml` locally): - Rebased onto main (#149, #151 and #156 had landed). That brought main's `mut_two_names` ratchet counts with it. - `test:rewrites` in full mode now passes. A `?.` after a step (`xs.map(f)?.forEach(g)`), on a method (`xs.map?.(f)`), or on a receiver declared an array (`xs?.map(f)` with `xs: T[]`) changes nothing and is rewritten. A `?.` in a receiver that may be absent (`c?.xs.map(f)`) is refused: the loop would run where the chain is skipped. Ratchet: `new inline optional-call` 3 → 1, `text inline optional-call` gone, plus one new line with its reason (`new inline hoist-const 1`: the harness moves the chain out of the `@inline` statement). - `bench:check`: the fusion ratios on 10 elements get a 4x tolerance. `findLast` on 10 elements landed exactly on its 2x limit on a retry here. - All of these pass locally on head `ec5e4680`: `cargo nextest run --workspace`, full `test:rewrites`, `test:std` (471 with #163), `typecheck`, `test:soundness`, `test:vite`, `test:docs`, `bench:check`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Loop rewrite: every array method, in any combination, split into loops at the methods without one
Some checks failed
Benchmarks / bench (pull_request) Failing after 8m22s
Tests / test (pull_request) Failing after 22m15s
44eb05fde4
A chain is now a list of steps over the receiver: `filter`, `map`, `flatMap`, `flat(d)` and
`slice(a, b)` stream into the next step; `forEach`, `reduce` (also without an initial value),
`some`, `every`, `find`, `findIndex`, `findLast`, `findLastIndex`, `includes`, `indexOf`,
`lastIndexOf` and `at(k)` end the loop; any other method (`toSorted`, `join`, `concat`, ...)
runs as written on the array the loop before it built, and a new loop starts over its result.
Holes are kept, skipped or read as `undefined` the way each method does; an index after a
`filter` counts what it kept. Callbacks by name (evaluated once, called with the method's
arguments), `thisArg`, a step that reads the `array` parameter (a new loop over the array it
asks for), and chains inside larger expressions (loop before the statement when the chain is
evaluated first in it, else an arrow called in place) are rewritten too.

On plain arrays this happens where packages/std/bench/fusion.bench.ts measured a win (every
chain of two or more steps; `forEach`, `map`, `flatMap`, `flat`, `findLast*` alone); `@inline`
gets all of it. packages/std/test/fusion/ compares 420 generated chains with the methods on
dense, sparse, empty and NaN/-0 arrays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee force-pushed evobug/inline-array-fusion from 44eb05fde4
Some checks failed
Benchmarks / bench (pull_request) Failing after 8m22s
Tests / test (pull_request) Failing after 22m15s
to 9f5721c4f9
Some checks failed
Tests / test (pull_request) Failing after 5s
Benchmarks / bench (pull_request) Successful in 5m20s
2026-11-24 13:21:33 +01:00
Compare
Loop rewrite: a ?. on a receiver declared an array changes nothing either
All checks were successful
Benchmarks / bench (pull_request) Successful in 6m7s
Tests / test (pull_request) Successful in 27m47s
ec5e46806e
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge main into evobug/inline-array-fusion
Some checks failed
Tests / test (pull_request) Has been cancelled
Benchmarks / bench (pull_request) Has been cancelled
c18ecdb027
sionzee deleted branch evobug/inline-array-fusion 2026-11-24 14:44:12 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!162
No description provided.