Stream: ideas

Topic: Reworking Rust Glue


view this post on Zulip Karl (Jul 31 2026 at 04:48):

The current Rust glue doesn't really take advantage of Rust's features and leaves the door open for errors that those features prevent. The GUI platform I'm working on (named roc-solid because it was going to be a Solid port; needs a rename) is up to ~30k lines of Rust and 3k LoC glue and tower-platform is 10.5k Rust and 3.7k glue so I feel they're large enough to exercise the glue reasonably well. I have had Claude do the wrong thing at several points along the way. Since I'm waiting on the weekly token reset tonight and design work is cheap I thought I'd take a swing at it tonight. This isn't particularly carefully considered and my total investment is a couple hours of thinking about it so I'm not particularly committed to anything.

Goals going in were to eliminate unsafe outside of generated code and to have the borrow checker earn its keep. I'm going to dump some LLM summaries and code examples and do some more formal process if there's interest. If not then I enjoyed thinking about it.

view this post on Zulip Karl (Jul 31 2026 at 04:49):

I didn't explicitly restrict things to just the glue layer so a couple compiler feature requests grew out of the session:

1. Retain the source alias name for structural types

glue.zig walks through .alias nodes to reach the backing record and discards alias.name on the way (:2455, :2837, :4216, :4268). Keep it and hand emitters the module-qualified name. One field on RecordRepr; no layout change; all three emitters benefit.

platform-im/Element.roc declares ArgPod : { kind : U8, a : I32, b : I32 }. The host writes abi::AnonStruct17fa5d8cd542867 { kind, a, b } in eight places — the name the author gave it is discarded between declaration and emission.

2. Expose the erased-callable argument-struct layout

Add the packed args AbiLayout (and the return layout) to FunctionRepr beside the existing type ids, so emitters can generate and assert the struct the ABI actually passes instead of reconstructing it.

Both platforms hand-declare #[repr(C)] struct Args { … } and pass &args as *const u8 into callable_fn_ptr. roc-solid's hazards note records (Str, Bool, model -> model) SIGBUSing on a sub-word parameter in a non-final slot — a hand-written struct can't be checked against anything, and neither host has any way to know it guessed wrong.

3. Export an ABI fingerprint symbol from compiled apps

Hash every layout fact the type table exposes and export a zero-sized symbol named for it; glue emits an opt-in roc_abi_assert!() referencing it, so a host built against stale bindings fails at link rather than at runtime.

roc-solid's standing hazards records "Element moves if Info grows — a glue regen and an ABI change," and its staleness check lives in the consumer's Justfile (stat the roc binary, shasum the platform sources). Nothing on the roc side lets a host detect that its bindings no longer match the app.

4. (Optional) A warning channel for glue scripts

make_glue : List(Types) -> Try(List(File), Str) lets a script fail the build but not warn, so there's no way to tell a platform author about a boundary shape that is legal but hazardous. Fallback needing no compiler change: emit the warning as a comment or #[deprecated] note in the generated source.

TextInput(Str, Str) — two payload slots the type system can't tell apart, so transposing them compiles silently in every host. Worth naming; not worth failing a build over.

5. (Small) Pin "host-visible allocations use atomic refcounts" as a test

arc.zig's visibility analysis picks single_thread only for allocations no host thread can touch (:4667). Generated glue is about to rely on that to declare Roc types Send/Sync by default. Add a test asserting boundary-reachable allocations always get .atomic.

tower-platform runs a multi-threaded tokio runtime and shares Roc handlers and the app model across workers behind seven hand-written unsafe impl Send/Sync. That's sound because of the visibility rule — but the rule is currently an implementation property, not a pinned contract, and glue is about to extend it to every host.

view this post on Zulip Karl (Jul 31 2026 at 04:50):

Overall Design

Memory & ownership

Runtime

Types & naming

Tag unions

Callables & construction

Errors

Boundary & build

Scope

Compiler-side work (alias retention, fingerprint, teardown reachability) for all three emitters; the Rust API redesign Rust-only.

Defects found, independent of the redesign

  1. Tag identifiers bypass keyword escaping; keyword list missing 12 reserved words — a Roc tag named Try fails to compile.
  2. rustfmt_skip is the pre-2018 spelling, inert.
  3. Union rounding vs disc_offset diverges on x86-64.
  4. make_roc_host defaults to a different allocator than the host's own symbols.
  5. Unnamed records and unnamed multi-variant unions emit "" with no compile_error!.

Accepted losses

Implicit Copy duplication (the mechanism itself); deliberate leaks need mem::forget; per-platform helper allocators in one process; a host that skips roc_abi_assert!() gets no check; path-derived names churn on platform reorganization — loudly.

Open

One item: whether Zig and C adopt equivalents of the view/constructor surface, or stop at the Phase 1 metadata fixes.

view this post on Zulip Karl (Jul 31 2026 at 04:51):

The 196 unsafe blocks break down as:

category count fate
decref / incref 86 gone — Drop / Clone
&* box deref 20 gone — RocBox<T> derefs safely
call_erased 14 gone — typed callable newtypes
abi::roc_* entrypoint calls 12 gone — safe wrappers
from_slice / allocate 6 gone — from_iter
from_raw_parts 7 mostly gone — see below
raw casts / ptr::read 8 mixed
remainder ~55 untouched — clay/wgpu FFI, nothing to do with Roc

(Categories overlap slightly; a block can match two patterns.) Let me show what the survivors actually are.

view this post on Zulip Karl (Jul 31 2026 at 04:53):

Text(Info, List(Tok), Str),
Node(Str, Info, List(Tok), List(Box(Element))),
Button(Info, List(Tok), U64, List(Box(Element))),
Input(Info, List(Tok), U64, Str),
Rich(Info, List(Tok), List(Run)),

_0 is Info in every variant except Node, where it's Str. Same union, same slot index, different meaning — and nothing in the host says so.

Today

fn label_of(el: &abi::Element) -> String {
    match el.tag {
        abi::ElementTag::Text => text_of(&el.payload_text()._2),
        abi::ElementTag::Node => {
            let n = el.payload_node();
            // SAFETY: Box(Element) crosses as a live, parent-owned pointer.
            n._3.as_slice().iter().map(|&c| label_of(unsafe { &*c })).collect()
        }
        abi::ElementTag::Button => {
            let b = el.payload_button();
            b._3.as_slice().iter().map(|&c| label_of(unsafe { &*c })).collect()
        }
        _ => String::new(),
    }
}

After — platform unchanged (positional payloads)

Glue emits this above the payload struct, which is the legibility fix for the Node trap:

/// Payload for `Element.Node`.
/// _0: Str, _1: Info, _2: List(Tok), _3: List(Box(Element))
pub struct ElementNodePayload { pub _0: RocStr, pub _1: UiInfo, … }

and the walk becomes:

fn label_of(el: &Element) -> String {
    match el.view() {
        ElementView::Text(t)   => text_of(&t._2),
        ElementView::Node(n)   => n._3.iter().map(|c| label_of(c)).collect(),
        ElementView::Button(b) => b._3.iter().map(|c| label_of(c)).collect(),
        ElementView::Input(_) | ElementView::Rich(_) | ElementView::Spacer(_) => String::new(),
    }
}

No unsafe — n._3.iter() yields &RocBox<Element> and derefs at the call. Note |c| label_of(c) rather than .map(label_of): deref coercion fires at a call site, not when passing a function item. The _ => becomes an explicit list, so a sixth variant stops the build. And t is now a borrow of the payload rather than the copy payload_text() returns today — which under Drop types is the difference between correct and a double release.

Still _0/_1/_2 — better than today (no unsafe, exhaustive, doc comment on the page) but not good.

After — with record payloads

One change in Element.roc:

Text({ info : Info, styles : List(Tok), text : Str }),
Node({ label : Str, info : Info, styles : List(Tok), kids : List(Box(Element)) }),
Button({ info : Info, styles : List(Tok), handler : U64, kids : List(Box(Element)) }),

and the view enum gets struct variants:

fn label_of(el: &Element) -> String {
    match el.view() {
        ElementView::Text { text, .. }   => text_of(text),
        ElementView::Node { kids, .. }   => kids.iter().map(|c| label_of(c)).collect(),
        ElementView::Button { kids, .. } => kids.iter().map(|c| label_of(c)).collect(),
        ElementView::Input { .. } | ElementView::Rich { .. } | ElementView::Spacer { .. } => String::new(),
    }
}

Node's odd slot order stops mattering entirely — you bind info by name and the position is irrelevant. The Roc side improves identically, since app code destructures by name too.

One thing to know about styles.as_slice().to_vec(): under non-Copy types that's T: Clone, so it increfs each element. Tok is plain data, so its generated Clone is a memcpy with no atomics — free. It would not be free for a list of Str.

view this post on Zulip Karl (Jul 31 2026 at 04:54):

The handler call

// before
#[repr(C)] struct Args { arg0: RocRequest }          // a guess at committed layout
unsafe { abi::incref_box(model.0, 1) };
let args = Args { arg0: RocRequest { ctx, headers: roc_kv_list(&parts.headers), … } };
let mut ret = core::mem::MaybeUninit::<RocResponse>::uninit();
unsafe {
    let payload = abi::roc_erased_callable_payload_ptr(handler.0);
    let capture = abi::roc_erased_callable_capture_ptr(handler.0);
    ((*payload).callable_fn_ptr)(host as *const _ as *mut _,
        ret.as_mut_ptr() as *mut u8, &args as *const Args as *const u8, capture);
    let mut response = ret.assume_init();

    // Take the list out and neutralize the response's copy FIRST: `response.decref`
    // below recursively decrefs the body field, and `RocListWith` is `Copy`, so
    // without this an arena body would be a harmless double no-op but a >4 MiB
    // cap-fallback (global) body would be genuinely freed out from under the owner.
    let body_list = response.body;
    response.body = abi::RocListWith::empty();
    …
    response.decref(host);
}

// after
let response = handler.call(RocRequest { ctx, model: model.clone(), headers: …, … });
let body_list = response.body;      // partial move — the neutralization line is unwriteable
…
// remaining fields drop at scope end

That comment describes a double-free that only manifests above 4 MiB — a hazard that passes every small-payload test, which is the same shape as roc-solid's "a payload under 24 bytes cannot exhibit this." Under move semantics it isn't a hazard that's been fixed; it's a state that can't be expressed. Taking response.body out is a partial move, and Rust drops the remaining fields itself.

view this post on Zulip Karl (Jul 31 2026 at 04:54):

That should be enough to get the idea across.

view this post on Zulip Luke Boswell (Jul 31 2026 at 05:08):

I haven't read everything above ... but the general idea was certainly to make the generated code as idiomatic and nice to use as possible.

view this post on Zulip Luke Boswell (Jul 31 2026 at 05:09):

The reason we went with three languages to start with is because a) we needed those, but b) it would be easy to overfit the API for one language ... so having multiple helps us keep the API generic and suitable for multiple target languages

view this post on Zulip Karl (Jul 31 2026 at 05:10):

This is mostly a feature request and not a concrete proposal. I wanted to bring up the topic as soon as I felt like I could do it reasonably because glue changes are disruptive.

view this post on Zulip Luke Boswell (Jul 31 2026 at 05:31):

Karl said:

named roc-solid because it was going to be a Solid port; needs a rename

This has to be the coolest name for a project... :rock: the only thing cooler might be solid-roc. Here's a very Australian song to help convince you...

https://youtu.be/tSNxFGW09Mo?si=PtRfEo74SpZS-V8R

view this post on Zulip Luke Boswell (Nov 22 2026 at 00:58):

@Karl if you could share your RustGlue.roc -- it sounds much nicer than what we have in the repo.

I am thinking we should leave a note in the repo that the glue scripts there aren't meant to be "official" or the only ones people use. My understanding or intent was that these would serve as a starting point to help bootstrap platform authors.

I'd love to collect relevant glue scripts people are using and include them on roc-awesome so they are easier to find. I think @pixelsprout has been workin on an Odin one... and I think there are others out there too.

view this post on Zulip pixelsprout (Nov 22 2026 at 01:00):

Here is the Odin glue repo - https://github.com/Pixelsprout/roc-odin-glue

view this post on Zulip Karl (Nov 22 2026 at 03:49):

This design wasn't pure glue and did require some upstream compiler changes to fully function. The nice part is that the compiler moved in the direction this proposal wanted so a decent fraction of the changes are now just exposing information to the glue. Other changes mean some design rework for the glue so I'll get things update and get back to you tomorrow.

view this post on Zulip Luke Boswell (Nov 22 2026 at 03:53):

:thumbs_up: no rush or anything.

view this post on Zulip Karl (Nov 22 2026 at 21:47):

Rust Glue writeup
compiler code
converted branch of my server platform to show what the diff looks like.

view this post on Zulip Luke Boswell (Nov 22 2026 at 21:51):

This is using a patched compiler?

view this post on Zulip Karl (Nov 22 2026 at 21:53):

Yes, the details of what the patches do are in the writeup.

view this post on Zulip Luke Boswell (Nov 22 2026 at 21:55):

I cant access the writeup link, I think zulip downloads it but I cant find it :sweat_smile:

view this post on Zulip Karl (Nov 22 2026 at 21:57):

RustGlue replacement: compiler changes and asks

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 rust-glue-rework, 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

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:

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.

view this post on Zulip Karl (Nov 22 2026 at 21:59):

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<hash> 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_<hash> (: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.

Reviewers will also find upstream's RocRelease<T> 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.

view this post on Zulip Karl (Nov 22 2026 at 21:59):

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:

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:

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<Option<T>> 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.

view this post on Zulip Luke Boswell (Nov 22 2026 at 22:09):

Thank you @Karl --- lots of detail here. I have no concerns with any of this, it looks like a nice cleanup of the glue API and enables much nicer type safety in generated glue. I'm sure it will benefit more than just Rust platforms.

view this post on Zulip Luke Boswell (Nov 22 2026 at 22:10):

Would you like me to try it out on one of my rust platforms? or should we make a PR for Roc?

view this post on Zulip Luke Boswell (Nov 22 2026 at 22:10):

@Richard Feldman would you prefer this lands in 0.1.1?

view this post on Zulip Karl (Nov 22 2026 at 22:10):

Feel free to try it out. I've ported all my Rust stuff over so it's not completely untested.

view this post on Zulip Richard Feldman (Nov 22 2026 at 22:12):

Glue isn't coupled to the compiler, so it can land whenever!

view this post on Zulip Karl (Nov 22 2026 at 22:13):

There are some compiler changes to allow the glue to generate typed callables.

view this post on Zulip Luke Boswell (Nov 22 2026 at 22:16):

@Richard Feldman here is the diff
https://github.com/roc-lang/roc/compare/main...grayrest:roc:rust-glue-rework

view this post on Zulip Richard Feldman (Nov 22 2026 at 22:17):

we can just land it via normal PR :+1:


Last updated: Nov 26 2026 at 20:35 UTC