Skip to content

feature/js-plains - #974

Closed
MattCozendey wants to merge 4 commits into
bendlang:mainfrom
MattCozendey:feature/js-plains
Closed

MattCozendey wants to merge 4 commits into
bendlang:mainfrom
MattCozendey:feature/js-plains

Conversation

@MattCozendey

@MattCozendey MattCozendey commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

The JS lane stops paying for calls: selector intrinsics + plain defs off the trampoline

Three changes to bend2/comp.ts; the first two are invisible to the C
emitter, the device and the checker, and the third gives the C lane the same
templates (no base.bend, bend.ts or Lean surface is touched).

1. Selector intrinsics (b4ebc8b)

JS-only OPERATIONS entries for bool_and, bool_not, bool_pick,
u32_min, u32_max, f32_min, f32_max, nat_min, nat_max.

Before, U32.min(a, b) emitted a trampolined call into $U32$min$, which
trampolined again into $Bool$pick$ — three frames and two $JMP
allocations for one compare. Now the ternary emits in place.

Each template mirrors its base.bend body exactly:

  • pick c a b = c ? a : b, min = a < b ? a : b, max = a < b ? b : a
  • F32 NaN answers keep following is_lt, as Bool.pick of F32.is_lt does
  • Nat.min/max's Succ-peeling recursion (O(min(a,b)) BigInt steps) becomes
    one BigInt compare
  • bool_pick stays JS-only because its A is polymorphic; on native lanes
    no single word shape fits

2. Plain defs are called directly (8ff7eab)

A def is plain when its emitted JS can never return a $JMP: no tail
self-call and no closure applied in tail position. Every other return comes
back through the machine stack, whose depth the def call DAG bounds — Bend
has no mutual recursion and no forward calls.

js_call now calls a plain callee directly (tail or not), so the JIT can
inline it. A self tail call keeps run_jump; a tail call into a trampolined
callee absorbs its $JMPs with run_loop in place, costing one bounded
frame. plain_of reads the property off the body with term_any's tail
flag; a closure body counts as tail, which only errs toward keeping the
trampoline.

3. The C lane gets the same templates (036e0b4)

As @jeromelaurens pointed out, since 2.0.17 (#860, 4033e90) Nat.min/Nat.max
peel successors in lockstep, and the C lane ran that recursion as written:
one continuation frame per successor, O(min(a, b)), so
Nat.min(10^9, 2*10^9) dies with bend: memory fault (machine stack overflow?). Clang can't recover the compare because the recursion goes
through the runtime's work loop.

C templates now sit beside the JS ones for nat_min, nat_max, u32_min,
u32_max, f32_min, f32_max, bool_and and bool_not:

  • nat_min/max: ($0 < $1 ? $0 : $1), the same raw-word compare as
    nat_sub and nat_is_lt
  • u32_min/max: compare as U32.is_lt does ((u32) casts, like
    U32_BIN) and return the operand normalized to 32 bits
  • f32_min/max: compare as F32.is_lt does (f32_unbox) and return the
    original word, bit-identical to Bool.pick, so NaN and ±0 behave as in Base
  • bool_pick keeps no C template: its untaken side may own a box to drop,
    and a wider A isn't one word, so the C lane keeps its match

Only the Nat pair was a real cost; U32/F32 min/max are a Bool.pick
over is_lt in base.bend, already O(1) on C, and their templates are for
lane parity.

Measurements (WSL, bun, medians of three, identical outputs and RSS)

workload (10M iterations) before after speedup
Base selector ops (min/max/pick/is_even) 1.30 s 0.51 s ~2.5x
chain of three small user defs per step 1.26 s 0.49 s ~2.6x
single pure Nat tail loop (control) 0.98 s 0.94 s ~1.0x

The control row is expected: a def that never calls anything gains nothing;
its costs (per-iteration run_jump allocation, BigInt Nat arithmetic) are
follow-up work, not this PR.

C and JS lanes after change 3 (WSL, clang 18 -O3 and bun, medians of three, identical outputs)

Before is main; RSS is the median max RSS (/usr/bin/time).

workload (10M iterations) lane before after speedup
Nat.min(p, 100) + Nat.max(p, 50) per step C 1.39 s, 2.0 MB 6.0 ms, 2.4 MB ~230x
Nat.min(p, 100) + Nat.max(p, 50) per step JS 81.2 s, 56.4 MB 0.59 s, 39.0 MB ~138x
U32/F32 min/max, Bool.and/not per step C 8.6 ms, 2.5 MB 7.2 ms, 1.9 MB ~1.2x
U32/F32 min/max, Bool.and/not per step JS 2.13 s, 44.2 MB 0.61 s, 40.8 MB ~3.5x
the report: Nat.min(10^9, 2*10^9), one call C memory fault (2.0 GB) 1000000000, 1.9 MB fixed
the report: Nat.min(10^9, 2*10^9), one call JS memory fault 1000000000 fixed

The C selector row is mostly process startup: clang already compiled the
Bool.pick match to the same compare. The report row ran once per side.

Verification

  • A scratch program exercising every intrinsic through constant and
    variable arguments prints the same value interpreted and emitted.
  • 73 tests across tests/base, tests/eval and tests/io pass on both
    the run path and the emitted-JS path.
  • The C lane (WSL, clang 18): the report's program and every runnable
    tests/base test agree across check, C and JS; five tests my local
    harness couldn't build fail the same way on main.
  • The cluster gates did not run (no ssh access from this machine); the
    perf pins and the device lane still need the usual gate pass.

🤖 Generated with Claude Code

@jeromelaurens

Copy link
Copy Markdown

Since 2.0.17 (#860, 4033e90) Nat.min/Nat.max peel successors and neither lane has an intrinsic for them, so they cost O(min(a, b)). This PR fixes the JS lane; the native lane still crashes:

import Base

def main() -> IO(Unit):
  do IO<Unit>:
    IO.print(Nat.show(Nat.min(Nat.mul(1000000000n, 1n), Nat.mul(1000000000n, 2n))))

bend min.bend -o min && ./min prints bend: memory fault (machine stack overflow?) on 2.0.27 (10^8 works) and 1000000000 on 2.0.16. Would C templates for nat_min/nat_max (($0 < $1 ? $0 : $1), ($0 < $1 ? $1 : $0)) in this PR cover both lanes? Found in a payroll POC, where amounts in micro-euros exceed 10^9. — bend 2.0.27, Darwin arm64

@MattCozendey

Copy link
Copy Markdown
Contributor Author

You were right, thanks. Since #860 made Nat.min/Nat.max peel successors, the C lane had been running that recursion as written, one continuation frame per successor, and clang can't turn it back into a compare. I added the C templates you suggested (036e0b4), plus C templates for the other selectors this PR had made JS-only, so both lanes get the same treatment. bool_pick still has no C template: the branch it doesn't take may own a heap value the C lane has to drop, so it keeps its match. Your program now prints 1000000000 on both lanes.

WSL, clang 18 -O3 and bun, medians of three, identical outputs; before is main:

workload (10M iterations) lane before after speedup
your repro: Nat.min(10^9, 2*10^9), one call C memory fault (2.0 GB) 1000000000, 1.9 MB fixed
your repro: Nat.min(10^9, 2*10^9), one call JS memory fault 1000000000 fixed
Nat.min(p, 100) + Nat.max(p, 50) per step C 1.39 s, 2.0 MB 6.0 ms, 2.4 MB ~230x
Nat.min(p, 100) + Nat.max(p, 50) per step JS 81.2 s, 56.4 MB 0.59 s, 39.0 MB ~138x
U32/F32 min/max, Bool.and/not per step C 8.6 ms, 2.5 MB 7.2 ms, 1.9 MB ~1.2x
U32/F32 min/max, Bool.and/not per step JS 2.13 s, 44.2 MB 0.61 s, 40.8 MB ~3.5x

The details are in the updated PR description, under section 3 and the new measurements table.

@nicolas-abril nicolas-abril self-assigned this Sep 24, 2026

@nicolas-abril nicolas-abril left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a good change, and the measurements hold up here. We'd like to merge it once the one issue below is fixed and tests are added.

The intrinsics are correct. Every template matches its base.bend body, including F32's NaN and ±0 behaviour. On a cross-lane program covering NaN, ±0, the U32 extremes, every Bool combination, Bool.pick at String and Nat, and Nat near 10^12, this branch prints exactly what main prints on the interpreter, JS and C wherever main finishes. Where main overflows the stack, it prints the right values.

The issue: plain defs can recurse on the JS stack. The plain-def argument relies on "Bend has no mutual recursion and no forward calls". Since c64e021d, an @unsafe def can call a def written below it, and tests/run/unsafe_forward.bend has two that recurse into each other. Two defs that tail-call each other then both count as plain, so they call each other directly, one JS frame per hop. A tail call into a non-plain callee also became run_loop(call) in place of run_jump, which nests a frame per call and so also grows on a cycle.

import Base

@unsafe
def even(n: Nat) -> Bool:
  match n:
    case 0n:
      True{}
    case 1n+p:
      odd(p)

@unsafe
def odd(n: Nat) -> Bool:
  match n:
    case 0n:
      False{}
    case 1n+p:
      even(p)

def main() -> IO(Unit):
  do IO<Unit>:
    t : Nat <- IO.now()
    IO.print(Bool.show(even(Nat.add(1000000n, Nat.mul(Nat.mod(t, 1n), 1n)))))

main prints True on every lane. On this branch the JS lane and bend file.bend stop with memory fault (machine stack overflow?); the C lane still prints True. It passes at 20,000 and fails at 100,000.

A fix we tested. A def is plain only if it is foreign, or every tail call in it reaches a plain def. A def that is still being evaluated counts as not plain, so any call cycle is not plain. Every non-plain callee keeps main's behaviour, and fl.def is no longer needed:

// A def is plain when its JS returns no $JMP: a foreign def, or one whose
// tail calls all reach plain defs. A tail self call, a tail closure and a
// def on its own call cycle (unsafe defs call forward) ride the
// trampoline, so a direct call never recurses through the machine stack.
function plain_of(c: Carb, k: Bend.Name): boolean {
  const got = PLAINS.get(k);
  if (got !== undefined) {
    return got;
  }
  PLAINS.set(k, false);
  const tld = def_body(c, k);
  const out = tld?.$ === "Def" && (def_foreign(tld) || tld.h !== undefined
    && !term_any(c, tld.h as HTerm, (s, tail) => {
      const ck = tail ? call_kind(c, s) : null;
      return ck !== null && (ck.k === CLO_APPLY || !plain_of(c, ck.k));
    }));
  PLAINS.set(k, out);
  return out;
}
  return v !== "" ? "(" + v + ") => " + call
    : plain_of(fl, k) ? call
    : tail ? "run_jump(" + js_sat(k) + ", [" + exprs.join(", ") + "])"
    : "run_loop(" + call + ")";

With it, the program above prints True on every lane and unsafe_forward still passes. The gains are kept on the JS lane (medians of three, bun, 10M steps):

workload main this branch with the fix
chain of three small defs per step 0.71 s 0.30 s 0.30 s
U32 min/max, Bool.pick/and/not, Nat.min per step ~41 s 0.44 s 0.44 s
a wrapper that tail-calls a self-recursive loop 0.45 s 0.37 s 0.45 s

The last row is the only cost: the in-place run_loop is what makes that shape faster, and it is the part that is unsafe on a cycle. Recovering it would take a real call-cycle analysis, which we don't think is worth it.

A smaller simplification. The six min/max entries are one pattern with a different comparison, so a helper can write them once:

// min and max as Base writes them, a Bool.pick over is_lt: a tie or a NaN
// answers min's second argument and max's first.
function sel_ops(pre: string, C: string): Record<string, Intr> {
  return {
    [pre + "min"]: { C: `(${C} ? $0 : $1)`, JS: "($0 < $1 ? $0 : $1)" },
    [pre + "max"]: { C: `(${C} ? $1 : $0)`, JS: "($0 < $1 ? $1 : $0)" },
  };
}
  ...sel_ops("u32_", "U32_BIN($0, <, $1)"),
  ...sel_ops("f32_", "f32_unbox($0) < f32_unbox($1)"),
  ...sel_ops("nat_", "$0 < $1"),

For U32 this returns the original word, as Bool.pick in Base does, and it prints the same values on all three lanes.

Tests. The branch adds none. Please add:

  • tests/base/nat_min_max.bend from #1037, which we're closing in favour of this PR (Nat.min/max at 0, equal values, both orders and pairs near 2^40, through a template and a closure);
  • a cross-lane intrinsics test for F32 NaN and ±0, the U32 extremes and every Bool combination;
  • the mutual recursion above, so the JS lane keeps this depth.

Merged onto current main, the branch passes gates/repo.ts (46/46), and a local run of gates/test.ts gives 1439/1441, failing only the two display tests gfx_clicks and gfx_window. With the fix and the helper applied the result is the same. The cluster and GPU gates were not run.

A further suggestion, optional. The C lane compiles a def's self tail call as a loop (WL_AGAIN in its helper), but the JS lane emits return run_jump($f$, [...]) on every iteration. If js_def compiled a self tail call as a loop instead, a def could only return a $JMP through a closure in tail position or through a cycle of unsafe defs. plain_of would shrink to that check, nearly every def would be plain (loop defs included), and the per-iteration $JMP allocation behind your control row would go away. Hand-editing the emitted JS of a benchmark whose loop tail-calls a wrapper around a small self-recursive loop (3M steps) gave:

emitted JS time
as this branch emits it ~0.43 s
the inner loop compiled as a loop ~0.25 s
both loops compiled as loops ~0.17 s

One thing to watch: a loop must give each iteration fresh bindings for its parameters, or a lambda created in the body would see a later iteration's values.

Take this only if it pays for itself in size: the whole change should end up smaller than this branch's patch. Measured with ttok, as gates/repo.ts does, this branch adds 630 tokens to comp.ts (62215 to 62845), and the fix and helper above bring that to 522. If the loop emission plus the smaller plain_of fit under 630, it is worth doing here; otherwise, leave it for a follow-up.

Note: this review was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

@MattCozendey

Copy link
Copy Markdown
Contributor Author

Updated as requested!

MattCozendey and others added 4 commits September 24, 2026 14:07
JS-only OPERATIONS entries for bool_and, bool_not, bool_pick, u32_min,
u32_max, f32_min, f32_max, nat_min and nat_max: each mirrors its
base.bend body exactly (pick c a b = c ? a : b; min = a < b ? a : b;
max = a < b ? b : a, so F32's NaN answers follow is_lt, and Nat's
Succ-peeling recursion becomes one BigInt compare). Before, each call
cost a run_jump trampoline into the def and, for min/max, a second one
into Bool.pick; now the ternary emits in place. The C lane is untouched:
intr_of without js sees no JS-only entry, so fuse, spins and the borrow
inference read the same book as before.

Verified through WSL on the JS lane: a scratch program exercising every
entry through variable and constant arguments prints the same value
interpreted and emitted, and 14 tests (num_kit, nat_ops, list_ops,
list_fold, list_kit, string_ops, text_ops, float_roundtrip, u32_divmod,
rand, tuple_suite, bool_algebra, fold, readback_sugars) pass run and
emitted-JS alike. The cluster gates did not run (no ssh from this
machine).

Co-Authored-By: Claude Fable 5 <[email protected]>
A def is plain when its emitted JS returns no $JMP: a self call or a
closure applied in tail position rides the trampoline, so its callers
must run_loop; everything else returns through the machine stack, whose
depth the def DAG bounds, since defs never call forward. plain_of reads
that off the body with term_any's tail flag (a closure body counts as
tail, which only errs toward the trampoline). js_call then calls a
plain callee directly, tail or not, so the JIT can inline it; a self
tail call keeps run_jump, and a tail call to a trampolined callee
absorbs its $JMPs with run_loop in place, one bounded frame. The C
lane and the device read none of this.

Verified through WSL on the JS lane: 73 tests across base, eval and io
pass run and emitted-JS alike (three tests/run fails are the @unsafe
stderr note the local runner merges into stdout; they fail identically
on the parent commit), and a 10M-iteration loop over a three-def chain
runs 1.14-1.42 s before, 0.45-0.54 s after, same output and RSS. The
cluster gates did not run (no ssh from this machine).

Co-Authored-By: Claude Fable 5 <[email protected]>
- Cycle-aware plain-def detection and safe tail calls.
- Shared min/max selector helper.
- Four regression tests covering both recursion forms, large Nats, NaN, signed zero, U32 extremes, and Bool combinations.
@nicolas-abril

Copy link
Copy Markdown
Collaborator

@MattCozendey, following up on the review: we tried the loop suggestion and put the result in a draft, #1040. It contains your three commits unchanged, plus one commit on top:

  • A tail self call is a loop on the JS lane, as the C lane's flat helpers loop. Each turn gets fresh parameter bindings, so closures keep their own turn's values.
  • Plainness is read off the same walk as C's flatness. carb_book records each def's tail callees in its Src, and plain_of reads them with flat_of's cycle guard. The PLAINS map and plain_of's own walk go.
  • The mutual-recursion overflow from the review is fixed, and the case the review called the only cost, a tail call into a self-recursive loop, gets faster than on this branch rather than slower.

On the JS lane it runs about 2 to 2.7 times faster than this branch on every benchmark we tried, and it adds 579 tokens to comp.ts against 630 here. The numbers and the checks are in its description.

It's your PR, so tell us which way you'd like to go: pull the commit into this branch, or we continue on #1040 and close this one. Tests are still missing on both. The list from the review (#1037's nat_min_max.bend, a cross-lane intrinsics test and the mutual recursion) applies to whichever lands.

Note: this comment was written by an AI after it reported the issue to me and I made the decision. If anything here is wrong, reply and I will review it myself.

@MattCozendey

Copy link
Copy Markdown
Contributor Author

Thanks, Nicolas. #1040 is the better base. It is smaller, and it reuses the Src walk. We can close #974.

I opened #1043. It contains #1040 unchanged, plus 2 commits:

  1. Tests. It adds the 7 tests from the review: nat_min_max, selector_intrinsics, the two unsafe tail cycles, closure capture, a tail call through a closure, and mutual jumps across arities.
  2. Mutual tail recursion runs as a loop. A Tarjan pass finds cycles in the tails sets that carb_book already records. plain_of reads a cycle as one def, so callers still call it directly.
  3. Intrinsic tail calls stay plain. Intrinsic callees (U32.add, Nat.min, …) were recorded as tail callees, so a def that ended in one used the trampoline. A one-line change fixes this.

JS lane, compared to #1040. The outputs are identical, and the memory use is the same:

case #1040 #1043
3-def tail cycle 543 ms 71 ms
2-def mutual recursion 578 ms 182 ms
wrapper that calls a self-loop 48 ms 46 ms
other cases same same

The tests pass on the interpreter, JS and C. I did not run the cluster gates.

If #1043 is good for you, it can replace both #974 and #1040.

MattCozendey pushed a commit to MattCozendey/bend that referenced this pull request Sep 24, 2026
…d off the same Src walk as C's flat

On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn
const bindings, so a closure keeps its turn's values), as the C lane's flat
helpers loop with WL_AGAIN. carb_book's one walk records each def's tail
callees in its Src beside deps; plain_of reads them with the same
in-progress false guard as flat_of, so a def is plain when every def it
tail-calls is: a closure has no source and a call cycle (unsafe defs call
forward) is not plain. A plain callee is called directly, every other one
keeps main's run_jump in tail position and run_loop elsewhere, so a
10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map,
plain_of's own walk and js_call's foreign branch go; the min/max
selectors are one sel_ops row per type and bool_and joins tpl_ops.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
MattCozendey added a commit to MattCozendey/bend that referenced this pull request Sep 24, 2026
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors
across lanes, unsafe tail cycles (plain and law), mutual tail jumps
across arities, closures captured in a loop, and a tail call through
a closure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
MattCozendey pushed a commit to MattCozendey/bend that referenced this pull request Sep 24, 2026
…d off the same Src walk as C's flat

On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn
const bindings, so a closure keeps its turn's values), as the C lane's flat
helpers loop with WL_AGAIN. carb_book's one walk records each def's tail
callees in its Src beside deps; plain_of reads them with the same
in-progress false guard as flat_of, so a def is plain when every def it
tail-calls is: a closure has no source and a call cycle (unsafe defs call
forward) is not plain. A plain callee is called directly, every other one
keeps main's run_jump in tail position and run_loop elsewhere, so a
10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map,
plain_of's own walk and js_call's foreign branch go; the min/max
selectors are one sel_ops row per type and bool_and joins tpl_ops.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
MattCozendey added a commit to MattCozendey/bend that referenced this pull request Sep 24, 2026
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors
across lanes, unsafe tail cycles (plain and law), mutual tail jumps
across arities, closures captured in a loop, and a tail call through
a closure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@MattCozendey
MattCozendey deleted the feature/js-plains branch September 24, 2026 21:07
MattCozendey pushed a commit to MattCozendey/bend that referenced this pull request Sep 25, 2026
…d off the same Src walk as C's flat

On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn
const bindings, so a closure keeps its turn's values), as the C lane's flat
helpers loop with WL_AGAIN. carb_book's one walk records each def's tail
callees in its Src beside deps; plain_of reads them with the same
in-progress false guard as flat_of, so a def is plain when every def it
tail-calls is: a closure has no source and a call cycle (unsafe defs call
forward) is not plain. A plain callee is called directly, every other one
keeps main's run_jump in tail position and run_loop elsewhere, so a
10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map,
plain_of's own walk and js_call's foreign branch go; the min/max
selectors are one sel_ops row per type and bool_and joins tpl_ops.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
MattCozendey added a commit to MattCozendey/bend that referenced this pull request Sep 25, 2026
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors
across lanes, unsafe tail cycles (plain and law), mutual tail jumps
across arities, closures captured in a loop, and a tail call through
a closure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Sep 25, 2026
…d off the same Src walk as C's flat

On top of bendlang#974. A def's tail self call is a loop (for (;;) with per-turn
const bindings, so a closure keeps its turn's values), as the C lane's flat
helpers loop with WL_AGAIN. carb_book's one walk records each def's tail
callees in its Src beside deps; plain_of reads them with the same
in-progress false guard as flat_of, so a def is plain when every def it
tail-calls is: a closure has no source and a call cycle (unsafe defs call
forward) is not plain. A plain callee is called directly, every other one
keeps main's run_jump in tail position and run_loop elsewhere, so a
10^6-deep mutual tail recursion runs on the JS lane again. The PLAINS map,
plain_of's own walk and js_call's foreign branch go; the min/max
selectors are one sel_ops row per type and bool_and joins tpl_ops.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
nicolas-abril pushed a commit to nicolas-abril/bend that referenced this pull request Sep 25, 2026
From bendlang#974 (149bce0) and feature/js-cga: Nat/U32/F32/Bool selectors
across lanes, unsafe tail cycles (plain and law), mutual tail jumps
across arities, closures captured in a loop, and a tail call through
a closure.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Sep 25, 2026
…ess, no new Src or File fields, and only Nat.min and Nat.max become intrinsics

On top of bendlang#1043, which carries bendlang#1040 and bendlang#974. The same tail loops, with
less machinery:

- One Tarjan pass over each def's tail callees, self calls included
  (tail_loops), fills a JS-lane LOOPS map. Src and File are main's again:
  carb_book records no tails, and plain_of, Src's plain and loop and
  File's loop go. The loop being emitted is read off fl.seg.def, as C's
  emit_jump spots a self jump; a closure's segment has no def, so its
  tail calls never continue the loop. A self loop is the group of one,
  so js_def's second walk for it goes.
- Every tail call into a def is a direct JS call. Tail cycles loop, so a
  direct tail call can reach its caller again only through a closure,
  whose run_tail still bounces on the trampoline: run_jump and the
  plainness fixpoint go. A non-tail call keeps run_loop.
- Only nat_min and nat_max stay intrinsics, on both lanes: Base's are
  unary and recurse min(a, b) deep. The other selectors are cheap direct
  calls now, and their C side measured nothing (clang inlines them), so
  they go with tests/base/selector_intrinsics; tests/run/
  unsafe_law_tail_cycle repeated unsafe_tail_cycle.

JS lane under bun, bendlang#1043 -> this, ms: cycle3 175 -> 176, mutual2 282 ->
282, listacc 148 -> 149, wrapper 137 -> 140, fib 152 -> 157 (a non-tail
call keeps run_loop), bounce 263 -> 118 (a tail call into a def that
bounces a closure skips the trampoline); node shows the same.
bench/runtime/hashmap 5303 -> 5296.

Verified: every runnable test, demo and runtime bench through the JS lane
under bun prints what bendlang#1043 prints (the removed tests aside); emitted C
equals main's but for tests/base/nat_ops and num_kit (Nat.min and
Nat.max), which pass; 10^6-step CPS, def/closure ping-pong, List.foldl
and IO loops run; gates/repo.ts 46/46 (comp.ts 63446 ttok); tsc reports
its 4 existing errors, none in comp.ts. The cluster gates did not run.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
nicolas-abril added a commit that referenced this pull request Sep 25, 2026
A def on a tail cycle, or tail-calling itself, is one JS loop: loop_of
finds its cycle (Tarjan over tail callees, cached in LOOPS with the other
per-book caches), and js_def emits `let $pc = <its case>; for (;;)
switch ($pc)` with each turn's parameters bound afresh, so a closure keeps
its own. A tail call into the loop being emitted (fl.seg.def names it, as
in C) sets $i and $pc and continues. Every other tail call into a def is a
direct JS call: tail cycles loop, so it can reach its caller again only
through a closure, whose run_tail still bounces; run_jump goes. Nat.min
and Nat.max become one tpl_ops row on both lanes (Base's are unary and
recurse min(a, b) deep). Src and File are unchanged.

JS lane under bun against the trampoline: a three-def tail cycle 841 ->
176 ms, two-def mutual recursion 895 -> 282, a closure bounce 265 -> 118,
fib 316 -> 157. comp.ts +627 ttok. Tests: nat_min_max, js_group_args,
js_loop_capture, js_tail_closure, unsafe_tail_cycle. Builds on #974 and
#1043 by Mathews Fernando; supersedes #1040 and #1043. The cluster gates
did not run.

Co-authored-by: Mathews Fernando <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants