0316. Zero-allocation view and iterator fusion in Core IR
- Status: Accepted
- Date: 2026-11-28
- Plan: M27.2
Context
Tenon's text splitting methods
(str/bytes .lines(),
.split(sep), .words(), and
str.chars()) and vector block methods
(.filter, .map, .fold) are
semantically eager value-returning operations
(vec<T>). Prior to this decision:
lower/stmt.rs(for_text) streamed only directfor x in s.{lines,split,words}()heads usingIntrinsic::PartStep/Intrinsic::RawStep;for c in s.chars()still allocated a fullvec<str>of every Unicode scalar.- Any chained pipeline such as
s.lines().filter { ... }.map { ... }.fold(init) { ... },for x in s.split(",").filter { ... },v.filter { ... }.map { ... }, ors.split(",").len()materialized every intermediatevecin the arena before the next stage ran. - Escaping
trt_text_partscalls (runtime/trt_seq.h) performed two full passes over the input (a counting pass followed by a filling pass), and single-bytesplitcalled the generaltrt_str_findinstead of directmemchr.
Decision
Fuse view-producing and block-transforming pipelines directly
during Core IR lowering
(crates/tenon-compiler/src/lower/), and upgrade
runtime/trt_seq.h to single-pass materialization with
a direct single-byte memchr path:
- Cursor support for
chars(): AddRawPart::Charstoir::RawPart, emitted astrt_part_at(..., kind = 4)(mode = 0Unicode scalars inruntime/trt_seq.h) and mirrored ininterp/value.rs::raw_step.for c in s.chars()and chains rooted at.chars()stream without allocating avec<str>. - Producer -> Stage -> Sink lowering
fusion:*
- Producers:
str/bytes.lines(),.split(sep),.words(),str.chars()(cursor loop viaPartStep/RawStep), and anyvec<T>expression (index loop0..n). - Intermediate stages (0 or more):
.filter { x -> cond }and.map { x -> expr }. - Non-materializing sinks (zero
vecallocation):for x in <chain> { body }<chain>.fold(init) { acc, x -> body }<chain>.len()(counts surviving items in ani64accumulator while still executing all stage blocks in order)<chain>.is_empty()(for pure producer without stage blocks, checks whether the first cursor step is invalid; with stage blocks, executes all stages to preserve traps and outervarwrites)
- Materializing sinks (zero intermediate
vecs, single outputvec):<chain>.filter { ... }or<chain>.map { ... }when the outer value is used as avec: emits oneStmtKind::Looppushing surviving/mapped elements into the single destinationvecvia tipIntrinsic::Push.
- Producers:
- Single-pass
trt_text_partsand 1-bytememchrinruntime/trt_seq.h:- Replace the 2-pass count-then-fill loop in
trt_text_partswith a single-passtrt_allocbuffer that grows in place at the arena top (doubling capacity on demand with zero copies and returning(trt_vec){data, count, 0}). - Add a direct
memchrfast path intrt_parts_nextforsep.len == 1.
- Replace the 2-pass count-then-fill loop in
- Semantics and parity invariants:
- Strict L-to-R evaluation: Producer receiver,
separator (for
split), andfoldinitializer are evaluated once and frozen into temporaries before the fused loop starts, so outervarmutations in stage blocks never alter the source or separator. - UTF-8, NUL, and empty-separator edge cases:
Identical to the unfused intrinsics (
str.split("")yields leading"", each scalar, trailing"";bytes.split(b"")yields the whole slice;lines()splits on LF and strips a single trailing LF; NUL bytes are preserved via boundedmemchr). - Arena scratch resets: Because fusion emits
ordinary structured Core IR (
StmtKind::Loop),regions/place.rsautomatically attaches a per-iteration scratchScopeDecland promotes only escaping values (foldaccumulator or pushed elements). - Interpreter parity: Both backends execute the identical fused Core IR.
- Strict L-to-R evaluation: Producer receiver,
separator (for
Alternatives considered
- Lazy iterator types in the surface language:
Adds new user-facing types, trait/interface complexity, and
LANGUAGE.mdtoken cost; unnecessary when Core IR fusion eliminates intermediate allocations transparently. - Post-lowering IR loop-fusion pass:
Reconstructing producer/stage/sink structure from already-lowered
loops and
Push/Indexstatements is fragile and risks breakingregionslinearity on branch-heavy functions. Lowering-time fusion is O(AST size), deterministic, and directly produces clean structured IR.
Consequences
- Chained text/vector pipelines allocate zero intermediate
vecs (zerovecs total forfor,fold,.len(),.is_empty()), and escapingsplit/lines/chars/wordsexecute in a single pass. - No surface syntax, type system, or
LANGUAGE.mdchanges are required. - Both C and
tenon interpshare identical semantics and trap locations.