Loop rewrite: every array method, in any combination, split into loops at the methods without one #162
Loading…
Reference in a new issue
No description provided.
Delete branch "evobug/inline-array-fusion"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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.filter,map,flatMap,flat(d)(literald≤ 4), andslice(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 afilter/flatMap/flat, then a counter of what got through.forEach,reduce(also without an initial value: the sameTypeErroron an empty array, and the first element is peeled whenreduceis alone),some,every,find,findIndex,findLast/findLastIndex(a backwards loop of their own),includes(SameValueZero),indexOf,lastIndexOf,at(k ≥ 0).toSorted,join,concat,reverse,with, aslicewith 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(",").mapandslicekeep them (a preallocated buffer), the skipping methods skip them, andfind/includes/at/findLastseeundefined. A step that comes after amapsees a hole without themapcallback having run.var) is evaluated once before the loop and called with the method's arguments, with atypeofcheck like the method makes.thisArgbecomes.call(thisArg, ...). A later step that reads thearrayparameter, 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.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 (&&,?:,whileconditions) the chain becomes an arrow called in place. Measured: called in place is as fast as the hoisted form.@inlinenow applies to every chain in the marked statement. It is found by the statement's span, because aconst's value can be visited where it is read.Bench (
packages/std/bench/fusion.bench.ts,npm run bench:fusion, also part ofbench:checkand its baseline): the callback versions live in a// @safe-ts legacyfile (listed underlegacyFiles), and the same code with@inlinein a normal file, both run through the transform loader. Times are ns per element, at 10 / 1,000 / 100,000 elements: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, plusforEach,map(also by name),flatMap,flatandfindLast*on their own. A lonefilter,find,some,every,reduceorincludesstays a call. Where the bench said no, the design changed:joinalways runs on the buffer. Building the string in the loop was 1.1–1.5x faster but allocated 2x as much.toSortedis not turned intosorton a buffer the chain owns. V8 sorts a copy either way, andtoSortedwas as fast or faster in both the bench and a separate microbench.push-grown buffer is what mademap→toSorted→maplose 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.tscovers placements (whileand&&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.typecheck:emit).transform.rstests and the loops fixture updated.cargo nextest run --workspace416/416,npm run test:std463/463,npm run typecheckandnpm run test:docspass.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):
items.filter(done).forEach(remove), whereremovesplicesitems. 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.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.ymllocally):mut_two_namesratchet counts with it.test:rewritesin 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)withxs: 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-call3 → 1,text inline optional-callgone, plus one new line with its reason (new inline hoist-const 1: the harness moves the chain out of the@inlinestatement).bench:check: the fusion ratios on 10 elements get a 4x tolerance.findLaston 10 elements landed exactly on its 2x limit on a retry here.ec5e4680:cargo nextest run --workspace, fulltest:rewrites,test:std(471 with #163),typecheck,test:soundness,test:vite,test:docs,bench:check.🤖 Generated with Claude Code
44eb05fde49f5721c4f9