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.
I didn't explicitly restrict things to just the glue layer so a couple compiler feature requests grew out of the session:
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.rocdeclaresArgPod : { kind : U8, a : I32, b : I32 }. The host writesabi::AnonStruct17fa5d8cd542867 { kind, a, b }in eight places — the name the author gave it is discarded between declaration and emission.
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 u8intocallable_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.
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 "
Elementmoves ifInfogrows — a glue regen and an ABI change," and its staleness check lives in the consumer's Justfile (statthe roc binary, shasum the platform sources). Nothing on the roc side lets a host detect that its bindings no longer match the app.
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.
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.
Drop on refcounted leaves (RocStr, RocListWith<T>, RocBox<T>, RocErasedCallable) plus a generated Drop per tag union; records use derived drop glue. Rejected: explicit release helpers (chosen first, then revisited — Rust's drop glue is the reachability closure, so the gap can't reopen); Drop-bomb.Clone = incref uniformly, including generated records and tag unions. Rejected: Clone-on-leaves-only, which was hedging a cost that doesn't exist — Element::incref is ≤4 relaxed atomics, bounded by the static type.try_into_iter() -> Result<IntoIter, Self>, iter() for borrows. Rejected: clone-on-shared (silent cost cliff); no consuming iterator at all.roc_alloc/roc_dealloc linker symbols. Forced by Drop taking no parameters. Rejected: keeping the vtable (chosen first, incompatible with Drop); registered global host pointer; split symbol/vtable APIs — the two-paths-disagree shape.RocRuntime trait and roc_runtime!(Impl) macro. dbg/expect_failed/crashed take &[u8].SystemRuntime, methods directly callable. Rejected: DefaultRuntime (implies automatic and recommended, both false); TestingRuntime (used as a production building block).no_roc_std_helpers and unexpected_cfgs.alias.name at the four .alias drill-through sites. Module-qualified; canonical by (module, name) sort; others as pub type; each use site spelled with the alias reached there. Rejected: one canonical name spelled everywhere (BorderTok in an Element signature); hash-canonical with all names as aliases (hash leaks into rustc errors).unsafe trait RocElement, RocList<T: RocElement>, RocListRaw escape hatch.RocBox<T> newtype with safe deref.r# raw identifiers; fixing only the tag sites.[u8; disc_offset] + zero-sized alignment marker at both widths; union deleted; payload_x_unchecked() as escape hatch. Rejected: keeping the 64/32 split; union everywhere — Roc's unrounded payload area is inexpressible as a Rust union, and the divergence is reachable on x86-64.into_view(), constructors. Rejected: Option-returning accessors (no exhaustiveness); view enum without constructors._0/_1 otherwise, with a doc comment listing each slot's Roc type, and a warning scoped to variants with ≥2 slots of the same type. Rejected: tuple structs (padding shifts indices); per-position newtypes (Deref reintroduces the swap hazard, and without Deref reads become t._0.0); refusing positional payloads outright.store.zig, layout.zig, and the glue README — tag-last with an unrounded payload area is a space optimization (16 vs 24 bytes on the canonical example), not a convention.call(), args struct and return buffer from committed layout with AbiLayout assertions, Clone/Drop. Rejected: generated Args structs with a generic call helper; args-only typing.mem::zeroed replaced by constructors, roc_unreachable() -> !, and T::zeroed() emitted only for types with no refcounted fields.From<&str>, from_str, from_iter, new); try_* for the genuinely fallible. No panic path in generated code. Rejected: blanket Result (overscoped — RocOps.alloc already unwraps, so OOM is fatal by contract); abort-everywhere. [ASSUMPTION] null from roc_alloc aborts through roc_crashed.mod raw; every into_raw() lives inside them. Rejected: the AbiChecked token.roc_abi_assert!(), opt-in. Rejected: unconditional link-time symbol (breaks app-less builds); stub macro; hash-suffixed entrypoint names (blast radius across linker, shim, hot-reload).refcount(), element_stride(), is_seamless_slice().improper_ctypes allows scoped to mod raw. Single #[path] file, rustfmt::skip spelled correctly. Rejected: generated crate; rustfmt-clean emission.Compiler-side work (alias retention, fingerprint, teardown reachability) for all three emitters; the Rust API redesign Rust-only.
Try fails to compile.rustfmt_skip is the pre-2018 spelling, inert.disc_offset diverges on x86-64.make_roc_host defaults to a different allocator than the host's own symbols."" with no compile_error!.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.
One item: whether Zig and C adopt equivalents of the view/constructor surface, or stop at the Phase 1 metadata fixes.
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.
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.
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(),
}
}
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.
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.
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.
That should be enough to get the idea across.
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.
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
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.
Karl said:
named
roc-solidbecause 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
@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.
Here is the Odin glue repo - https://github.com/Pixelsprout/roc-odin-glue
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.
:thumbs_up: no rush or anything.
Rust Glue writeup
compiler code
converted branch of my server platform to show what the diff looks like.
This is using a patched compiler?
Yes, the details of what the patches do are in the writeup.
I cant access the writeup link, I think zulip downloads it but I cant find it :sweat_smile:
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 |
AbiErasedCall). Typed Rust callables cannot be generated without it.glue.zig. It is a memory-safety bug today, independent of Rust.Send and Sync, and these tests are what keep that sound.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).
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:
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.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.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.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.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.ArgPod : { kind : U8, a : I32, b : I32 } reaches the host as AnonStruct17fa5d8cd542867; Kite had 63 such references across about ten crates.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.
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.
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.
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.
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.
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.
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.
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().
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.
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.
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.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.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<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.
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:
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:
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.just check passes.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.
call and call_with) satisfy design.md's "enforced by signatures" intent, or whether you would rather require the context argument everywhere.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.
Would you like me to try it out on one of my rust platforms? or should we make a PR for Roc?
@Richard Feldman would you prefer this lands in 0.1.1?
Feel free to try it out. I've ported all my Rust stuff over so it's not completely untested.
Glue isn't coupled to the compiler, so it can land whenever!
There are some compiler changes to allow the glue to generate typed callables.
@Richard Feldman here is the diff
https://github.com/roc-lang/roc/compare/main...grayrest:roc:rust-glue-rework
we can just land it via normal PR :+1:
Last updated: Nov 26 2026 at 20:35 UTC