Skip to content

The JS lane loops tail cycles and calls every def directly (on top of #1043) - #1061

Merged
nicolas-abril merged 14 commits into
bendlang:mainfrom
nicolas-abril:js-tail-loops
Sep 25, 2026
Merged

nicolas-abril merged 14 commits into
bendlang:mainfrom
nicolas-abril:js-tail-loops

Conversation

@nicolas-abril

@nicolas-abril nicolas-abril commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

Builds on #1043 by @MattCozendey, which carries #1040 and #974. It contains #1043's six commits unchanged, plus commits on top that keep its tail loops and remove most of the machinery around them. It supersedes #1040.

What changes relative to #1043

  • No new fields on Src or File. A def's tail loop comes from loop_of(cb, k), a Tarjan search over tail callees (self calls included), memoized in a LOOPS cache that is declared and cleared with the other per-book caches. carb_book no longer records tails, and plain_of, Src.plain, Src.loop and File.loop are gone.
    • fl.seg.def names the def being emitted, as it does in C. A tail call into that def's loop continues it; a closure's segment has no def, so its tail calls never do.
    • A self loop is just a loop of one, so js_def's second walk looking for self tail calls is gone.
  • One loop shape. A looping def is its own function, let $pc = <its case>; for (;;) switch ($pc), so there are no entry functions and no self-loop special case. Each member of a mutual cycle gets its own copy of the loop; cycles have at most three members.
  • No plainness. Every tail call into a def is a direct JS call.
    • This is safe because tail cycles run as loops: a direct tail call can only get back to its caller through a closure, and a closure's run_tail still bounces on the trampoline.
    • run_jump and the plainness fixpoint are gone. A non-tail call still goes through run_loop.
  • Only Nat.min and Nat.max stay as intrinsics, on both lanes, as one tpl_ops row. Base defines them in unary (1n+Nat.min(ap, bp)), so as written they recurse min(a, b) deep and overflow the stack on large Nats.
    • The other selectors are now cheap direct calls, and their C side measured nothing, because clang already inlines the Base definitions. They're removed along with tests/base/selector_intrinsics.bend.
    • tests/run/unsafe_law_tail_cycle.bend repeated unsafe_tail_cycle.bend, so it's removed too.

Against current main (rebased on db84f207), comp.ts changes by +62 −11 lines and +627 ttok (62,808 → 63,435, under the 64,000 cap); #1043 added +127 −15 against its base.

Measurements

JS lane, M-series Mac, hyperfine, 15 runs, in ms:

workload #1043 (bun) this (bun) #1043 (node) this (node)
three-def tail cycle, different arities, 10M steps 175 176 86 86
two-def mutual tail recursion, 30M steps 282 282 131 131
a wrapper tail-calling a self loop, 3M calls 137 148 75 77
fib 32 through a helper 152 157 66 68
a closure bounce, 3M steps 263 118 144 93
list build and sum, 3M 148 149 112 112
bench/runtime/hashmap 5303 5296

fib is about 3% slower because its non-tail calls keep run_loop, and wrapper about 7% slower under bun because each short self loop now sets up $pc and a switch (node: within about 3%). bounce is 1.5–2.2× faster because a tail call into a def that bounces a closure no longer goes through the trampoline.

Verification

  • Every runnable test, demo and runtime bench, built to JS and run under bun: the same output as The JS lane loops tail calls, mutual cycles included, and calls plain defs directly #1043, apart from the two removed tests.
  • Emitted C is byte-identical to main's, except tests/base/nat_ops and tests/base/num_kit, which call Nat.min/Nat.max; both pass on C.
  • Stress programs at 10⁶ steps (continuation-passing, a def/closure ping-pong, List.foldl, a recursive IO loop) run on the JS lane.
  • gates/repo.ts: 46/46. tsc: the 4 existing errors, none in comp.ts.
  • Merges cleanly into current main.

Not done: the cluster, perf and GPU gates. SSH to the nodes is refused from this machine.

🤖 Generated with Claude Code

@MattCozendey

Copy link
Copy Markdown
Contributor

I closed mine in favour of this. Looks better :)

@nicolas-abril nicolas-abril self-assigned this Sep 25, 2026
MattCozendey and others added 14 commits September 25, 2026 19:18
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]>
…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]>
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]>
A tail-call cycle between defs (Tarjan over the Src tails carb_book
records) runs as one loop: `$f$loop($pc, $0, ...)` switches on `$pc`, a
tail call into the cycle sets `$i` and `$pc` and continues, and each
member keeps an entry that enters the loop at its own case. A self loop
is the cycle of one, without the switch. Each case binds its parameters
afresh, so a closure keeps its own turn's values, and a closure body
never continues the enclosing loop.

plain_of reads a cycle as one def: it is plain when every def the cycle
tail-calls outside itself is, so callers call it directly. An intrinsic
callee is no longer recorded as a tail callee, so a def ending in one
(U32.add, Nat.min, ...) is plain rather than trampolined.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
…demand, declared among the caches and cleared by carb_book, so js_lib runs no pass for it

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…s, no self-loop special case, and a cycle's loop is emitted once per member

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ef is on the stack or cached, so the ids map goes

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…moizes through memo like the other caches

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…s_def: js_loop looks up its own loop and brackets nothing, and js_func reads the loop in place

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…op inside it

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril
nicolas-abril merged commit 0608588 into bendlang:main Sep 25, 2026
VictorTaelin added a commit that referenced this pull request Sep 26, 2026
… descent is linear

bend2/bend.ts (43,884 -> 42,275 ttok):
- The parser reads every infix operator from one INFIX table (longest
  spelling wins), not a list, three special branches and an if-chain.
- The parser's binder stack and frame count live on Parse: Scope, Entry
  and Loc go; parse_book resets them once per declaration.
- A reply is its term: the Reply type goes (Body = Match | Local | LTerm).
- parse_term sets the span of a node that lacks one, so the branches that
  set the same span go, and parse_grow goes.
- {a == b : T}, {a != b : T} and {a : T} share one tail; parse_book and
  parse_def read a word once; parse_lookup, parse_term_do_call go.
- term_higher, term_lower and term_snf return a leaf as it is; the dead Sub
  cases of term_lower and term_snf go; Sub.v is a Patt.
- term_wnf's MAT frame applies its lambda-match in one place.
- term_compare: one case for Qnt, Efq and Rfl.
- uses_close closes a binder (quant_used, uses_get, uses_del go);
  ctrs_find goes; book_fam reads tele_unbind; def_inst checks its ~
  arguments with tele_check; book_valid checks a def in place.
- The book adds an open law to hols: the open field goes.
- err_show prints a context type with expr_show; char_is_name extends
  char_is_head.
- #983: term_descend skips the field that already missed, so a descent
  on a Nat literal is linear, not 2^n (tests/halt/literal_descent_linear).
- Header comments that were false now match the code.

bend2/comp.ts (63,523 -> 62,584 ttok), effs/chan.c, effs/tcp_poll.c,
effs/file_read.c, effs/window_frame.c:
- One type walk, ty_holds, finds closures and recursive datatypes:
  lay_cyclic and its cache go.
- An IO fiber is its IoWork: the IoAct wrapper and io_wait_time go.
- The pool counts with the a32 atomics: its _Atomic globals go.
- A Halt or a deadlock ends the program where the IO loop meets it; the
  CLI fails through err_fail (cli_fail goes); same texts, same codes.
- A term's spine holds its call: the Call type and call_kind go.
- One effect_srcs reads each foreign source once for both lanes.
- One mat_rows gives both lanes a match's rows; Seg.host goes.
- term_keep takes its count; the kernel votes in its group's block;
  GA32, ALC_WORDS and fid_seqk go.
- The compiler's types go from 31 to 16. One File record holds a
  compile, and a nested scope is a copy of it (Carb, Src, Dst and Show
  go); a def's raised arity and body live in its Fun, and the book is
  never copied (Def, TLD and Sig go); a flat layout's arms map a
  constructor to its fields' layouts (Arm and Field go); Nat and word
  match rows are one Row (Chain and Leaf go); HAdt, HLet, UMap and Probe
  are written as Of<K>.
- The C runtime's type names go from 26 to 14: it speaks u64, u32 and
  pointers (Loc, Cls, Fid, Err, Ring, Nat, U32, Stk, Corpus go), one
  atomic family serves host, Metal and CUDA (g32 and Cur go), the five
  u8 id tables are two byte-row tables FID_T and CID_T, and an IO queue
  is a circular list held by its last IoWork (IoQue goes).
- The JS lane runs 2.3x faster than #1061's (benches: bun 2.7x, node
  2.9x; other programs: bun 2.5x, node 1.5x) and recurses at least as
  deep: a Nat is a JS number, exact below the 2^48 cap C shares. #1061's
  tail-cycle loops stay the one call design (loop_of; a one-def cycle
  needs no $pc), and a call passes through run_loop only when its callee
  may return a closure's bounce: a marker per call resolves once every
  def is out, so a def that never bounces is called directly (bun: fib
  0.40 s against 0.65 s with run_loop on every call; node: gameoflife
  0.26 s against 0.76 s). A Nat from the host enters through nat_host: an
  integer up to 2^53 is exact, any other value fails like C's Nat check
  (tests/io/nat_host_bounds, nat_host_neg, nat_host_chan); an array
  converts in place, as before; a match field an arm never reads is not
  bound.
- Dead internal guards go; term_any walks a tree without a visited set.
- On main since b531388: #1068's wide nodes (WIDE 247, a node past it
  keeps 240 plus its size class in CID_T), #1038's intrinsic argument
  layouts, #988's --bend-help and #1061's Nat.min/max rows, in this
  model; {a != b : T} underlines its != as #1063 does.

WONTFIX.txt, guide/GUIDE.md: stale lines match the CLI and the runtime.

The emitted C differs only in the runtime text above (a program's
segments are the same, but a foreign request's local names). The emitted
JS behaves as main's for every test, demo and generated program, except a
bad Nat from the host (negative, past 2^53, not an integer), which now
fails as the C lane does instead of printing garbage. 8,286 programs and
mutants against 11c65a2: the same check, interpreter, JS (bun and node)
and C output (1,414 binaries), except those host-Nat cases and
literal_descent_linear, which main does not finish. C lane on the M4
minis (16 benches, min of 5): SEQ 0.999, PAR 0.999, GPU 1.000; emit
0.98. Linux x86 (clang-19, RTX 4090): every test, bench and CUDA test
prints as on main.

bend.ts and comp.ts follow STYLE.md: no prose comment sits in the middle
of a section (a fact the code does not show moves, in one short sentence,
into its section's doc block; comp.ts goes from 150 comment blocks to 47);
trailing comments line up; a checker function sits in Check (tele_check,
term_descend, uses_close) and f32_show in Show; each comp.ts section is a
type or a verb and holds its subject's functions (Live is Dom, Anf is ANF,
the type Gen is Tpl, emit_nats and emit_lits are mat_nats and mat_lits);
every case of a switch is a block; the title comes first; TAB_BAD,
RUNTIME_ADTS, OWNED, IDS and TAKEN move into Constants; no comp.ts line
passes 80 chars. The code tokens are unchanged: the emitted C and JS
differ only in runtime comments and whitespace.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
phenomenon0 pushed a commit to phenomenon0/bend that referenced this pull request Sep 27, 2026
Canon fixed U02 (backlog 512, bendlang#977), U04 (Nat.min/max through the tail
cycle loop, bendlang#1061) and U22 (the boxed Bool reaching Bool.or, bendlang#1038); U08
and U21 answer in C now, U20 in interp and JS. Still REPRO: U01, U03/U03t,
U06, U10, U11, U14 spawn_sleep, U16-U19, U20 (C), U21 (interp, JS), and
F01-F11 -- F01, no wall clock: IO.now is still monotonic.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01S4szbK155RvUkyET5spFdw
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.

2 participants