# ADR 0039: Tail recursion modulo cons **Status:** Proposed (2026-10-13, issue #154); needs engineering review (#44). Implements what [ADR 0003](0003-effect-lowering.md), Revision 1, promised (it was documented, not implemented). ## Context `list.map`'s recursive call is not a tail call: its result goes into the `Cons` built after it returns. So `map`, `filter`, `append`, `zip` and `zip_with` used one stack frame per element. On native actors' 64 MiB stacks that is a few hundred thousand elements; in the interpreter, frames on the heap. ADR 0003 said these run in constant stack; issue #154 found they didn't. ## Decision A Core pass, `louise_core::trmc`, at the end of lowering, so both back ends get it (Leijen and Lorenzen, "Tail Recursion Modulo Context", POPL 2023). ### Which functions A **site** is a call of the function to itself whose result goes into one field of a *spine*: one or more constructors or tuples, each in a field of the next, returned (or `exit`ed, ADR 0037), with nothing between the call and the return. A function with a site gets a sibling. Left alone: - mutual recursion; - `n + f(x)` and other operations (not a constructor); - a result read anywhere but its hole; - a function whose sites put the result in different fields (the runtime follows one field to copy a context, below); - anything with an effect between the call and the return. ### The transformation `f(params)` gets `f$trmc(params, k)`, `k` being a **context**: the part of the result built so far, with a hole. - A value `f` would return goes through `ctx_apply(k, value)`. - A site builds its cells first, with unit in the hole, extends `k` with them (outermost first), and tail-calls `f$trmc`. - A plain tail call to `f` passes `k` along. - `f` becomes `f$trmc(params, ())`. Core gets two values, `CtxExtend { ctx, cell, hole }` and `CtxApply { ctx, value }`; both consume their arguments. The cells are ordinary constructions, so Perceus counts them and reuses matched cells for them: `map` over a unique list writes its result into the input's cells. `LOUISE_NO_TRMC` turns the pass off. ### Contexts natively (runtime ABI 7) A context is unit when empty, or a 3-field block: the root (owned), `tl_int` of the last cell's address and `tl_int` of its hole field. Each cell owns the next through its hole. The int fields are immediates, so dropping, unwinding or copying a context needs nothing special. - `tl_ctx_extend` and `tl_ctx_apply` are inline: a unique context changes in place, one store and two field updates. - **Shared contexts:** a multi-shot resumption (ADR 0017) keeps a copy of the frame, so the context is counted twice. The slow paths (`louise_rt/src/ctx.rs`) copy the path from the root to the last cell, following the hole field, before changing it; the other holder keeps the original. That is why a function's cells must all have the same hole field. ### Contexts in the interpreter A persistent linked list of (cell, hole) from the last cell back, extended in O(1). Applying it rebuilds the cells from the last one. A resumption taken twice shares what came before and builds its own rest, as natively. ## Consequences - `map`, `filter`, `append`, `zip`, `zip_with`, `option.values`, `result.values` and functions of that shape run in constant stack. `tests/run/trmc.lse` runs them over 30,000 elements with a 256 KiB stack and a 10,000-frame interpreter, and overflows with `LOUISE_NO_TRMC`. - A context costs one block per call chain (not per element). - **Performance:** see the table below. - **Not covered:** varying hole fields (the hole index could go into each cell's header flags), mutual recursion, and contexts through other operations (Koka's general "modulo context"). ### Benchmarks `scripts/bench.sh`, best of 21, one thread, ms; PR #149's branch → this one. | bench | before | after | | |---|---|---|---| | lists | 343 | 166 | −51% | | html | 431 | 403 | −6% | | effects | 51 | 49 | −3% | | messages | 95 | 97 | +2% | | others | | | within ±1% | `lists` is twice as fast: `map` over a unique list now writes into its own cells, in a loop, instead of recursing and allocating new ones. Nothing is slower beyond noise. ## Alternatives considered - **Leave the recursion, document the limit:** the issue's other option. But the library's basic functions would still overflow on long inputs, and ADR 0003 promised it. - **Rewrite `map` and friends with an accumulator and `reverse`:** two passes and twice the allocation, and only for std. - **A context per cell (the hole index in each cell):** lifts the one-field rule, but needs a header bit layout change; left for later. - **Checking each cell's count while following the path, as Koka does:** needed where cells can be shared some other way. Here a context's cells are reachable only through it, so the context's own count decides. **Implementation note — 2026-10-14 (ADR 0043, issue #196).** **Status:** Proposed, as the ADR. TRMC moved out of lowering into `louise_core::opt`, after the simplifier: the optimiser's passes (specialisation and fusion, issues #197–#198) recognise the pristine recursion, and a function they leave alone is transformed exactly as before. `LOUISE_NO_TRMC` is unchanged; `louise core --no-opt` shows Core without it. **Implementation note — 2026-10-27 (issue #331).** A cell is built with unit in its hole, so a cell whose other fields are constant (`Succ(…)`, `[0, ..…]`, `Link(7, …)`) looked like a constant tree to the C back end, which emitted it as a shared, read-only static block (`static_construct`, from 2c2381f "constant constructor trees are static, immortal blocks"); `tl_ctx_extend` and `tl_ctx_apply` then wrote into it and the program segfaulted, natively only. A cell reused from a matched input (`map` and friends) was never static, which is why `tests/run/trmc.lse` passed. The emitter now collects each function's context cells (`ctx_cells`) and never hoists them. `tests/run/trmc_constant_cells.lse` covers the shapes.