# RustGlue replacement: compiler changes and asks Nov 22, 2026 ยท @Karl ## Summary The branch replaces `src/glue/src/RustGlue.roc` with a Rust API whose types carry Roc's ownership rules. Most of it is the glue generator itself, but it rests on a few compiler-side changes and specifically asks for seven changes to the glue-platform contract. The branch is `r``u``s``t``-``g``l``u``e``-``r``e``w``o``r``k`, five commits on tag `0.1.0_RC1` (`15177e91f6`): | Commit | Kind | What it changes | | --- | --- | --- | | `3a5df8e603` | CI | tidy matches its `design.md` vocabulary rule by whole path component | | `fbda9e6d51` | Docs | rationale comments for tag-union discriminant placement and for an erased call's `ops` argument | | `41437ccd5d` | Test | pins atomic refcounts for root parameters and hosted-call results in `arc.zig` | | `4f67e4ebf0` | Feature + fix | exposes the erased-call argument layout to glue scripts; derives list allocation headers from the element layout | | `02006483ab` | Spec | the RustGlue replacement, its tests, the glue README, and a `design.md` amendment to the Host Symbol ABI section | - **The erased-call argument layout** as glue-platform data (`AbiErasedCall`). Typed Rust callables cannot be generated without it. - **The list-header fix** in `glue.zig`. It is a memory-safety bug today, independent of Rust. - **The two ARC tests.** Rust glue declares Roc values `Send` and `Sync`, and these tests are what keep that sound. - **The `design.md` amendment (R5).** Rust glue stops shipping a host-built `RocHost` vtable and uses a private symbol-backed adapter instead. Additional proposed changes, not implemented here: source alias names for structural types (R1), a warning channel for glue scripts (R2), the erased-call convention and other ABI facts as data rather than text (R3, R4), a platform-contract fingerprint (R6), and stable names for shapes shared across worlds (R7, found during the ports). ## The problem with today's generated Rust Today's RustGlue emits C with method syntax: every ABI type is `#[repr(C)] + Clone + Copy`, ownership is manual (`unsafe { arg0.decref(host) }`), and the Rust type system checks none of it. `src/glue/README.md`'s risk register already names non-`Copy` ownership APIs as the control for shallow copies of ownership-bearing values; the emitter derives `Copy` on all of them. The failures this caused in real platforms: - **Releases the driver never reaches.** `decref_stmt_for_repr_rust` writes correct release code, but only for types that are members of a named generated type. A hosted function returning `List(Str)` gets no helper and no diagnostic. In Kite this leaked about 2,200 allocations per view (about 1 GB RSS over 30,000 frames) while five correctness gates stayed green, because none asserted that anything is freed. Unnamed records and unnamed multi-variant unions hit the same gap. - **Two allocation paths.** `RocHost` is a vtable compiled Roc never constructs; compiled code calls the `roc_alloc` linker symbols. Hosts export the symbols and also wire a parallel vtable, and `make_roc_host` defaults that vtable to a different allocator than the host's own. In Kite this made a tracking allocator report a leak that did not exist. - **Erased-call arity drift.** The erased-callable ABI went from four parameters to six. Nothing locks the Rust signature against builtins, and no CI case invokes a callable from a Rust host: `callable_fn_ptr` appears in none of the ten Rust test hosts. It cost two long hunts, one in Kite and one in tower-platform. - **Guessed argument layouts.** Hosts hand-declare the packed argument struct for each stored callable. A sub-word argument in a non-final slot crashed one of them. - **Tag unions that cannot match the layout.** Roc places the discriminant after an unrounded payload area. A Rust `union` rounds its size up to its alignment, so `{u64}` plus `{u32, u32, u32}` gives Roc a discriminant at offset 12 and a Rust union of 16 bytes, on x86-64. Today that is a build failure on a legal platform type, caught only by the layout assertion. - **Identifiers that do not compile.** Tag-derived names skip the keyword escape, and the keyword list misses `async`, `await`, `dyn`, `try` and eight more. A tag named `Try` emits `pub try:`. Kite renamed a Roc variant from `For` to `ForEach` to get around it. - **Names the source already has.** A structural alias such as `ArgPod : { kind : U8, a : I32, b : I32 }` reaches the host as `AnonStruct17fa5d8cd542867`; Kite had 63 such references across about ten crates. ## Compiler-side changes, and what is lost without each Every compiler-side change plumbs data the compiler already computes or pins a rule that already holds; none adds new computation. The feature commit was built and tested on its own: the glue suite passes there with the old spec still in place. The three commits before it are a tidy fix, comments, and a test. ### 1. Expose the erased-call argument layout (`4f67e4ebf0`) **What.** A new `AbiLayoutDetails` variant, `AbiErasedCall`, carries each argument's offset and the packed buffer's size and alignment at both pointer widths. It is sourced from `erased_call_abi`, which gains `argShapeAt` and `planShapes` because one callable's arguments can be committed by different lowerings; `plan` delegates to `planAt`, so the packing rule stays in one place. It lives on the layout side, not on `FunctionSignature` (shared with provided procedures, which use no packed buffer) and not in `CallableSignature` (repr data, documented as carrying no layout facts). **Why.** A host invoking a stored callable fills a buffer whose layout only the compiler knows. The glue README says generators "must not reconstruct runtime layout" from incidental type structure, and rebuilding the packed struct from argument type ids is exactly that. **Lost if rejected.** Typed callables. Hosts go back to hand-declaring the packed struct per callable, where a wrong offset is a silent runtime crash, as already happened once. The ownership typing of a call also goes: `call(&self)` borrowing and `call_once(self)` transferring the one reference the callee may reuse are only expressible on a generated type. ### 2. Derive list allocation headers from the element layout (`4f67e4ebf0`) **What.** `buildRocList` always allocated with the refcounted-elements header. `allocateList` now takes the header shape from the element layout, so no caller can pass the wrong one. **Why.** The old behavior held only because every record list glue had marshalled so far contained a `Str`. A list of plain-data records needs the shorter header; with the longer one, compiled Roc frees the list from the wrong base. It reproduces as `RuntimeHostEnv: double-free or untracked free` on a glue spec that ignores its input, and is absent on the unmodified compiler only because no such list existed yet. **Lost if rejected.** Any glue platform type with a list of plain-data records, for any generator, becomes a double-free. `List(AbiErasedArg)` is the first such list, so item 1 cannot land without this. ### 3. Pin atomic refcounts at the boundary (`41437ccd5d`) **What.** Two tests in `src/lir/arc.zig`: root parameters and hosted-call results get `.atomic` refcount updates. Root returns and hosted-call arguments were already pinned. **Why.** Optimized builds count a value single-threaded when the host-visibility analysis proves no host thread can reach it. The replacement declares every Roc value `Send` and `Sync` on the strength of that analysis, and tower-platform already shares its handler table and model across worker threads. **Lost if rejected.** Nothing breaks today. But a future change to host-visibility seeds could make a boundary value single-threaded in optimized builds only, with no test failing. Rust would still accept sharing it across threads, so the result is a data race on the refcount: use-after-free or double-free, in release builds only. ### 4. Document discriminant placement and erased-call `ops` (`fbda9e6d51`) **What.** Comments only: on `TagUnionMeasure` and the `discriminant_offset` field, why the discriminant follows an unrounded payload area (it lands in padding the payload already carries, so `A(u32, u32, u32) | B(u64)` is 16 bytes where a tag-first layout is 24); and in `erased_callable.zig`, what a host must pass as `ops`. **Why.** The default `roc` command, embedded interpreter builds and the REPL run the app in the interpreter behind the same host objects. An interpreter-created callable forwards every allocation, `dbg`, `expect` failure and crash through the `RocOps` prefix it receives as `ops`, and a host cannot tell it from a compiled callable, which ignores `ops`. **Lost if rejected.** No behavior changes. What is lost is the reason, and with it the two mistakes it prevents: an emitter reaching for its language's native tagged union, and a host passing a placeholder `ops` that faults on the first allocation under `roc`. ### 5. Amend design.md's Host Symbol ABI section (R5, in `02006483ab`) **What.** `design.md` currently says generated Zig and Rust bindings provide a host-built `RocHost` helper, and the glue ABI lock checks its prefix. The amendment keeps that for Zig. For Rust, helpers call the runtime symbols directly, and the one `RocOps` prefix they need is a private static adapter (`raw::RocSymbolAdapter`) whose callbacks forward to those symbols. The ABI lock is retargeted at the adapter, so it still matches the interpreter's prefix exactly. Generated Rust also declares `roc_crashed` as returning `!`, which is ABI-identical to `void`. **Why.** A host-built vtable is a second allocation path that can disagree with the linked symbols, which is the phantom leak described above. `Drop::drop` takes no parameters, so drop glue could not reach a vtable anyway. An adapter whose callbacks are the symbols cannot disagree, and still gives interpreter-created callables a real host. **Lost if rejected.** Rust glue would have to keep a host-facing `RocHost`, which restores the two-path bug exactly on the path interpreter allocations take. Without `-> !`, a host's `roc_crashed` that returns is a runtime trap instead of a compile error. ### 6. tidy: match by whole path component (`3a5df8e603`) `endsWith("design.md")` also matched files such as `plans/x-redesign.md`, holding them to `design.md`'s vocabulary rule. Nothing safety-related depends on it. ## What the replacement guarantees, and what each guarantee rests on The replacement turns most of the failures above into compile errors. Several guarantees need nothing new from the compiler; the rest depend on the changes in the previous section, so rejecting a change removes the guarantees listed against it. | Guarantee | Failure it removes | Rests on | | --- | --- | --- | | Typed callables: `call(&self)` borrows, `call_once(self)` hands over the reusable reference; arguments packed at the compiler's offsets | Guessed argument structs, arity drift, a reference used after the callee consumed it | Change 1, plus a Rust compile lock of the erased-callable header against builtins | | `Send` and `Sync` on every Roc value type | Hand-written `unsafe impl Send/Sync` blocks (tower-platform 10 before, 3 after, all arena internals), and the data race if counts ever go single-threaded | Change 3 | | One allocation path: `RocRuntime`, an optional `roc_runtime!` macro, and a private adapter for `ops` | Phantom leaks from a second vtable; interpreter-created callables faulting on a placeholder `ops` | Changes 4 and 5 | | `roc_crashed` returns `!` | A host crash handler that returns | Change 5 | | Release through `Drop`, keyed to the compiler's existing `HostRcPlan` | Releases the driver never reached; every field, element, payload and argument position is covered by drop glue | Nothing new | | A value only Roc can release has no `Clone`, is `#[must_use]`, and duplicates only through `retain()` | A clone that looks free but creates an obligation nothing collects | Nothing new (`RcRocReleased`) | | Tag unions as a private byte area sized to the committed discriminant offset, read through `view()`, taken apart with `into_view(self)`, built with per-tag constructors | Layout mismatch on x86-64; the double release `take_payload_*_unchecked(&mut self)` causes once the shell has `Drop`; a new Roc variant silently falling through a `_` arm | Nothing new; change 4 records why | | One reserved-word escape for every identifier | Tags named `Try` or `For` failing to compile | Nothing new | | Each shape without its own Roc name is named by the first path that reaches it | `AnonStruct` names in host code | Nothing new; R1 would do better | | Infallible construction, diverging through `roc_crashed`; no `panic!` or `.expect()` in generated code | Unwinding across Roc frames | Nothing new | | `call_with`, `call_once_with` and `_with` entrypoints enter a host `RocContext` for the call | Per-thread host state (an arena) missing on a thread that runs Roc code | Nothing new | **The trade, stated plainly.** Under manual release, every host mistake was a leak and memory safety survived it. Under `Drop`, a value a host receives and hands back to Roc must be moved; getting that wrong is a use-after-free. The replacement keeps every raw handoff inside generated code, behind safe entrypoint wrappers, so ordinary host code hands a value back by moving it, `retain()` or `clone()`. Raw access remains only as explicit escape hatches (`RocListRaw`, `RocStr::from_raw_parts` for borrowed slices). In both ports every handback is a move, `retain()` or `clone()`. ## Requests to the compiler team These change the glue-platform contract, so they are asked for, not implemented. Only R5 is on the branch, to be ruled on in review. The others each have a stopgap in the replacement, listed so you can see what they would retire. | Ask | Why | Stopgap until then | | --- | --- | --- | | **R1.** Keep the source alias name for structural types, subordinate to `shape_id` | `glue.zig` drills through `.alias` at eight sites and discards `alias.name`, then mints `__AnonStruct_` (`:2345`) | Name each shape by the first path that reaches it | | **R2.** A warning channel for glue scripts | `make_glue : List(Types) -> Try(List(File), Str)` can fail a build but cannot warn | Warnings, such as two payload slots sharing one type, become comments in the generated file, seen only by someone reading it | | **R3.** The erased-callable calling convention as glue-platform data | Every spec restates `RocErasedCallableFn` as text, and it has already gone from four parameters to six | Restated text, plus a Rust compile lock against builtins so drift fails the build | | **R4.** The other ABI facts specs restate as text, as data: the small-string bit, the seamless-slice tag, the capture offset, the allocation header layout | Each restatement is a place a spec can silently disagree with the compiler | Restated text | | **R5.** Accept the private symbol-backed adapter in place of a host-built `RocHost` for Rust | See change 5 above | Implemented on the branch | | **R6.** A platform-contract fingerprint: a digest over boundary layouts with app-type payloads opaque, computed identically by glue and `roc build`, exported by compiled apps as a symbol host bindings can link against | A stale glue spec next to a newer compiler is a silent ABI mismatch that reads as a compiler bug. `host_boundary_digest` cannot serve: it descends into box payloads, so it is app-dependent (right for hot reload, wrong for glue), and only `roc run` paths compute it | The generated file's header carries a hash of the glue input, for visibility only; no link-time check | | **R7.** A stable name for a structural shape that appears under several paths | Path naming is source dependent. A package shared by several crates must spell glue's names for shared shapes, and those come from the first path in table order: `CliInReadToEndResult` is also fs-core's `Try(List(U8), IOErr)`. A crate that adds or drops a hosted module sorting earlier can rename a shape and break the package | The ported packages confine those spellings to one alias block, and today's separate crates agree | R7 surfaced during the consumer ports. It may fold into R1, for example by naming a `Try(...)` after its type rather than its first use. ## Readings of design.md a reviewer may question Apart from R5, the replacement follows `design.md`, but in four places it meets a requirement in a shape the text does not literally describe. Each reading is deliberate. - **Raw tag-payload move.** `design.md` says generated host glue exposes an unsafe raw payload move, and that an RAII host language puts it behind a non-copying owner whose failed tag-specific move returns the still-owned shell. The replacement emits only `view()` and `into_view(self)`. `into_view` is that owner, and more general than a per-tag move; the raw move stays inside generated code. Upstream's `take_payload_*_unchecked(&mut self)` was dropped because it double-releases once the shell has `Drop`. - **Per-thread call context.** `design.md` asks for closure-invocation helpers that set and restore per-thread host state, so the contract is enforced by signatures. The `_with` forms are those helpers: they take `&impl RocContext` and hold its guard for the call. The short forms pass a no-op context, because in three ported codebases all 74 call sites passed it and no host implemented a real one. - **`roc_crashed` typing.** `design.md` keeps the symbol `void` because C cannot spell `noreturn` on a function pointer. Rust can, and an `extern "C"` declaration returning `!` is ABI-identical, so the reason still holds. The amendment records the Rust spelling. - **Named releases.** `design.md` requires a named release for every type whose release is more than one decrement, and none for a type holding an opaque heap target. Under `Drop` every such type carries its release, there is no public `decref` primitive to mislabel, and `RcRocReleased` types get none. Reviewers will also find upstream's `RocRelease` witness types absent. They encode the compiler's `HostRcPlan`, which the replacement reads directly to decide which types get `Drop`, so there is nothing for them to carry. ## Evidence from porting three codebases The replacement was ported through three real consumers: Kite (a UI framework with native and DOM hosts), tower-platform (an HTTP platform with a per-request arena), and trantor (a platform composer with generated service shims), plus trantor's CLI and four packages. Every consumer gate passes after the port, except one that also fails on `main` with the same compiler. **Static counts** in hand-written host code, excluding generated glue and vendored code: | Measure | Kite before | Kite after | tower before | tower after | | --- | --- | --- | --- | --- | | `unsafe` uses | 826 | 392 | 249 | 148 | | `unsafe impl Send/Sync` | 4 | 2 | 10 | 3 | | `AnonStruct` names | 63 | 1 | 6 | 0 | | `RocHost` uses | 37 | 0 | 26 | 0 | | Manual `decref`/`incref` calls | 103 | 0 | 52 | 0 | | `mem::zeroed` | 4 | 3 | 0 | 0 | What remains is not glue. In Kite about 113 `unsafe` uses are C-ABI export attributes and definitions, about 95 are OS and foreign-library calls (signals, input devices, a C layout library), and the rest are runtime plumbing, test fakes, wasm singletons and GPU readback. tower's remainder is mostly its own arena allocator and SQLite cursor handles. The leftover `Send`/`Sync` impls wrap a GPU buffer and arena internals; the three `mem::zeroed` are libc `sigaction` structs. **Runtime probes** in Kite, before and after: - Live allocations over 2,000 views: 398 before, 398 after, so no leak was introduced. - Mounting a view: 4,606 allocations and 975,816 bytes before, 4,608 and 976,268 after. - Retained bytes: 80.0 per write, unchanged; 7,440 per view before, 7,868 after; 10,448 with a retained closure before, 10,876 after. The small rise is host-built values now allocated through `roc_alloc`, where the host's tracker sees them. **CI.** The full `zig build minici` passed on the branch (105 phases: 102 passed, 3 platform-gated skips). Since then only the call-form change and comment edits landed; the glue ABI check, the glue suite (57 passed, 2 skipped) and the source-check lane (14 of 14) pass on the tip. In the consumers: - **Kite****:** lint (now including `cargo fmt --check`), unit tests and example checks pass. The IM gate suite passes 168 of 169; the one failure, `im-keyunder`, also fails on `main`. - **tower-platform:** `just check` passes. - **trantor:** 136 unit tests and all 20 golden fixtures pass, as do trantor's CLI and its four packages. ## Scope, costs and open points **Out of scope.** CGlue and ZigGlue are untouched, including ZigGlue's version of the same release-reachability gap. No separate reports are filed for today's Rust defects, since the replacement fixes them by construction. **Cost to existing Rust hosts.** This is an API break. The ten in-repo Rust test hosts (about 3,500 lines) were rewritten. The three consumers above were ported on their own branches. One hazard needs attention in any port: `mem::zeroed()` construction is harmless under `Copy` and a memory-safety bug under `Drop`, so it has to be removed during the port rather than discovered later. **Considered and rejected.** `From>` conversions for two-tag unions such as `[Key(Id), Nothing]`. The shape "one empty tag, one payload tag" fits `[Pending, Done(x)]` and `[Err, Ok(x)]` as well, so a conversion would read a meaning into a shape. Hosts write the `match`. **Open.** - R7's naming question, and whether it belongs inside R1. - Whether the two call forms (`call` and `call_with`) satisfy `design.md`'s "enforced by signatures" intent, or whether you would rather require the context argument everywhere.