Skip to content

fix(compiler): convert intrinsic argument layouts - #1038

Merged
nicolas-abril merged 3 commits into
bendlang:mainfrom
vicmcorrea:dev/intrinsic-argument-layouts
Sep 25, 2026
Merged

nicolas-abril merged 3 commits into
bendlang:mainfrom
vicmcorrea:dev/intrinsic-argument-layouts

Conversation

@vicmcorrea

Copy link
Copy Markdown
Contributor

Why

the native build in #1026 prints f False g False h True, while the interpreter and JS print f True g True h True. The generic pick returns a boxed Bool, which the native intrinsic uses without converting it to the expected 0 or 1.

i'm evaluating Bend alongside our TypeScript monorepo and checked this report while comparing native and JS behavior.

Fixes #1026.

Scope

Convert intrinsic arguments to their parameter layouts before taking ownership and extracting their words. This uses the existing sig_def and val_to helpers and adds one net compiler line.

The new regression covers Bool.or and Bool.xor, both argument positions, and true/false results from a computed selection. Existing tests stay intact.

Blast radius

The conversion is in the C emitter, after the specialized array path. Intrinsic result handling is unchanged.

Verification

On macOS arm64, Bun 1.3.11 and clang 23.1.1:

  • The new regression fails natively on ac0ddb7b; with the fix, checking, interpreter, emitted JS and native execution pass.
  • The original Native compiler: Bool.or(x, pick(Bool, cond, a, b)) returns the wrong value #1026 repro now prints f True g True h True natively.
  • Eleven existing native fixtures pass, covering arithmetic, tuple results, arrays, borrowing and flat sharing.
  • bun gates/repo.ts: 46/46. git diff --check passes.

Cluster, GPU and benchmark gates were not run.

@nicolas-abril nicolas-abril self-assigned this Sep 25, 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 for the fix, and for the clear write-up. I validated it merged into current main (it merges without conflicts):

  • The #1026 repro prints f False g False h True natively on main and f True g True h True with this PR. tests/reg/intrinsic_arg_layout fails natively on main and passes on all three lanes here.
  • I emitted C for every runnable test plus the runtime benches (1085 programs) with and without the PR. Apart from the new test, the output is byte-identical, so nothing else changes and the benches aren't affected.
  • sig_def(fl, k).lays lines up with m.args (live_dom is quant_live, and lay_wide keeps the list's length), and val_to does nothing when the layouts already match. bun gates/repo.ts passes 46/46.

Two small things before merging:

  1. Naming (inline below): chaining the two maps drops the extra vs, which is otherwise shadowed a few lines later by const vs: string[] in the Array.isArray(it.C) branch. Same size, same C.
  2. Test header: every other file in tests/reg starts with a # regression witness: ... comment saying what broke and how. Could you add one, e.g. that a generic pick returns a boxed Bool that the native intrinsic read raw, so Bool.or/Bool.xor saw the wrong word?

Side note, not blocking: the conversion sits after the array fast path, so arr_op still reads its index and depth words raw. An index from pick(U32, ...) works today (I checked Array.get/Array.set on every lane), but a boxed argument of another type there could hit the same class of bug.

Comment thread bend2/comp.ts Outdated
Comment on lines +2246 to +2247
const vs = args.map((v, i) => val_to(fl, v, sig_def(fl, k).lays[i]));
const ws = vs.map((v) => (val_own(fl, v), val_word(v)));

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.

Chaining the maps avoids the extra vs (shadowed by the vs: string[] below); it emits identical C:

Suggested change
const vs = args.map((v, i) => val_to(fl, v, sig_def(fl, k).lays[i]));
const ws = vs.map((v) => (val_own(fl, v), val_word(v)));
const ws = args.map((v, i) => val_to(fl, v, sig_def(fl, k).lays[i]))
.map((v) => (val_own(fl, v), val_word(v)));

jnadeau207-collab added a commit to jnadeau207-collab/bend that referenced this pull request Sep 25, 2026
…) defs for every op and a native on every lane

type U64 is Data: U64{lo: U32, hi: U32}. A runtime cell holds 48-bit
immediates and reads bit 63 (RFC_BIT) and the all-ones word (TERM_HOLE)
as tags, so a U64 never sits in one cell: its halves travel as two U32
words, flat in registers and two fields in a node, and base/u64_transport
moves 2^63, 2^64-1 and tag-shaped words through a record, a pair, a Maybe,
a recursion, a fork, an Array get and swap, a closure, a generic pick and
a ! call, bit-exact on every lane.

Every op is a def over Word(64n) (U64.word joins the halves, U64.of splits
them back): add, sub, mul, div (by 0 is 0), mod (by 0 the dividend), not,
and, or, xor, shl, shr, shln and shrn (past 63 is 0), inc, cmp and the six
predicates, is_zero, min, max, clz, mul_hi (the high word of the 128-bit
product), from_nat, to_nat, to_u32, U32.to_u64, Bool.to_u64, show and read,
and U64.add_comm proves commutativity from Word.add_comm as U32.add_comm
does. Word gains the generic shln, shrn, cat, take, drop, divmod, div, mod,
is_zero and clz those defs need. C and CUDA run each op as a native on one
u64 (mul_hi as __int128, __umul64hi under NVRTC, mulhi on Metal's ulong),
JS on a BigInt; U64.to_nat fail-stops past 2^48-1 as Nat.add does.

A literal is NUMBER "u64" (the grammar table's new row): U64{lo, hi} of two
U32 Lits, so the checker reduces U64 arithmetic on literals and a match
reads a wide literal pattern; past 2^64-1, a fraction or an n suffix is a
parse error. term_show and both printers spell a U64 as that literal.

The compiler: a native reads each argument in the layout it takes (a boxed
U64 from a generic def unboxes first; the same fix as bendlang#1038), a two-word
argument enters a template as one u64 and a two-word result leaves as its
halves (intr_c), and a spin is keyed by its erased arguments' layouts, so
Bool.pick at U64 passes the halves flat instead of boxing them.

Tests: base/u64_ops (every op at 0, 1, 2^32-1, 2^32, 2^63 and 2^64-1
against exact integers), base/u64_transport, printer/u64_print,
parse/u64_literal_overflow, proof/u64_literal_unfolds (wrapping, mul_hi of
2^64-1 squared, a literal pattern and add_comm, by the checker),
check/u64_literal_own_u64 and run/u64_nat_overflow; u64_transport also
runs on CUDA. Test gate 1465 / 1465, repo gate 46 / 46.

bend.ts is 44058 ttok (the literal, its show and the table row; the kernel
is otherwise untouched), so gates/repo.ts allows 44500; comp.ts 63863,
base.bend 28374. A run that imports Base checks 275 more lines: bend
hello.bend 65.0 to 68.4 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
jnadeau207-collab added a commit to jnadeau207-collab/bend that referenced this pull request Sep 25, 2026
…) defs for every op and a native on every lane

type U64 is Data: U64{lo: U32, hi: U32}. A runtime cell holds 48-bit
immediates and reads bit 63 (RFC_BIT) and the all-ones word (TERM_HOLE)
as tags, so a U64 never sits in one cell: its halves travel as two U32
words, flat in registers and two fields in a node, and base/u64_transport
moves 2^63, 2^64-1 and tag-shaped words through a record, a pair, a Maybe,
a recursion, a fork, an Array get and swap, a closure, a generic pick and
a ! call, bit-exact on every lane.

Every op is a def over Word(64n) (U64.word joins the halves, U64.of splits
them back): add, sub, mul, div (by 0 is 0), mod (by 0 the dividend), not,
and, or, xor, shl, shr, shln and shrn (past 63 is 0), inc, cmp and the six
predicates, is_zero, min, max, clz, mul_hi (the high word of the 128-bit
product), from_nat, to_nat, to_u32, U32.to_u64, Bool.to_u64, show and read,
and U64.add_comm proves commutativity from Word.add_comm as U32.add_comm
does. Word gains the generic shln, shrn, cat, take, drop, divmod, div, mod,
is_zero and clz those defs need. C and CUDA run each op as a native on one
u64 (mul_hi as __int128, __umul64hi under NVRTC, mulhi on Metal's ulong),
JS on a BigInt; U64.to_nat fail-stops past 2^48-1 as Nat.add does.

A literal is NUMBER "u64" (the grammar table's new row): U64{lo, hi} of two
U32 Lits, so the checker reduces U64 arithmetic on literals and a match
reads a wide literal pattern; past 2^64-1, a fraction or an n suffix is a
parse error. term_show and both printers spell a U64 as that literal.

The compiler: a native reads each argument in the layout it takes (a boxed
U64 from a generic def unboxes first; the same fix as bendlang#1038), a two-word
argument enters a template as one u64 and a two-word result leaves as its
halves (intr_c), and a spin is keyed by its erased arguments' layouts, so
Bool.pick at U64 passes the halves flat instead of boxing them.

Tests: base/u64_ops (every op at 0, 1, 2^32-1, 2^32, 2^63 and 2^64-1
against exact integers), base/u64_transport, printer/u64_print,
parse/u64_literal_overflow, proof/u64_literal_unfolds (wrapping, mul_hi of
2^64-1 squared, a literal pattern and add_comm, by the checker),
check/u64_literal_own_u64 and run/u64_nat_overflow; u64_transport also
runs on CUDA. Test gate 1468 / 1469 (io_process_run fails the same way
on upstream here), repo gate 46 / 46.

bend.ts is 44058 ttok (the literal, its show and the table row; the kernel
is otherwise untouched), so gates/repo.ts allows 44500; comp.ts 63916,
base.bend 28616. A run that imports Base checks 275 more lines: bend
hello.bend 77.9 to 81.0 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vicmcorrea

Copy link
Copy Markdown
Contributor Author

np, I updated both in 5ddeac4, lmk if i missed anything

jnadeau207-collab added a commit to jnadeau207-collab/bend that referenced this pull request Sep 25, 2026
…) defs for every op and a native on every lane

type U64 is Data: U64{lo: U32, hi: U32}. A runtime cell holds 48-bit
immediates and reads bit 63 (RFC_BIT) and the all-ones word (TERM_HOLE)
as tags, so a U64 never sits in one cell: its halves travel as two U32
words, flat in registers and two fields in a node, and base/u64_transport
moves 2^63, 2^64-1 and tag-shaped words through a record, a pair, a Maybe,
a recursion, a fork, an Array get and swap, a closure, a generic pick and
a ! call, bit-exact on every lane.

Every op is a def over Word(64n) (U64.word joins the halves, U64.of splits
them back): add, sub, mul, div (by 0 is 0), mod (by 0 the dividend), not,
and, or, xor, shl, shr, shln and shrn (past 63 is 0), inc, cmp and the six
predicates, is_zero, min, max, clz, mul_hi (the high word of the 128-bit
product), from_nat, to_nat, to_u32, U32.to_u64, Bool.to_u64, show and read,
and U64.add_comm proves commutativity from Word.add_comm as U32.add_comm
does. Word gains the generic shln, shrn, cat, take, drop, divmod, div, mod,
is_zero and clz those defs need. C and CUDA run each op as a native on one
u64 (mul_hi as __int128, __umul64hi under NVRTC, mulhi on Metal's ulong),
JS on a BigInt; U64.to_nat fail-stops past 2^48-1 as Nat.add does.

A literal is NUMBER "u64" (the grammar table's new row): U64{lo, hi} of two
U32 Lits, so the checker reduces U64 arithmetic on literals and a match
reads a wide literal pattern; past 2^64-1, a fraction or an n suffix is a
parse error. term_show and both printers spell a U64 as that literal.

The compiler: a native reads each argument in the layout it takes (a boxed
U64 from a generic def unboxes first; the same fix as bendlang#1038), a two-word
argument enters a template as one u64 and a two-word result leaves as its
halves (intr_c), and a spin is keyed by its erased arguments' layouts, so
Bool.pick at U64 passes the halves flat instead of boxing them.

Tests: base/u64_ops (every op at 0, 1, 2^32-1, 2^32, 2^63 and 2^64-1
against exact integers), base/u64_transport, printer/u64_print,
parse/u64_literal_overflow, proof/u64_literal_unfolds (wrapping, mul_hi of
2^64-1 squared, a literal pattern and add_comm, by the checker),
check/u64_literal_own_u64 and run/u64_nat_overflow; u64_transport also
runs on CUDA. Test gate 1468 / 1469 (io_process_run fails the same way
on upstream here), repo gate 46 / 46.

bend.ts is 44058 ttok (the literal, its show and the table row; the kernel
is otherwise untouched), so gates/repo.ts allows 44500; comp.ts 63916,
base.bend 28616. A run that imports Base checks 275 more lines: bend
hello.bend 77.9 to 81.0 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Thank you, this is merged. Both review points are in exactly as asked, and I re-validated it on top of the current main (7cb184a, merges cleanly): the #1026 repro prints f True g True h True natively (main still prints f False g False h True), tests/reg/intrinsic_arg_layout passes on the interpreter, JS and native lanes, and the C emitted for all 1,492 programs under tests/ and bench/ is byte-identical to main's apart from the new test. gates/repo.ts is 46/46; comp.ts grows by 24 ttok. A small, well-targeted fix with a clear write-up.

Note: this reply 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.

@nicolas-abril
nicolas-abril merged commit ab71b1b 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.

Native compiler: Bool.or(x, pick(Bool, cond, a, b)) returns the wrong value

2 participants