Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Host fns and declaration files

One linkage keyword, one implementer:

keywordimplementation lives inbound at link against
host fn / host structthe embedding Rust — a typed registrationthe load-time contract (below)
prelude builtin / pub builtin rowsthe engine itself — compiler-lowerednothing; the decl is a pure signature contract

rut→rut names resolve through use paths (modules and visibility); host→rut entry points are entry fn (loading and the embed loop).

Surfaces live in declaration files — .d.rut — so compiling rut code never requires any Rust, and a published package can ship its compiled bodies plus a hand-written surface.

Host pkgs

A package directory whose manifest declares type = "host" is a host pkg — pure surface, no rut source:

// server/rut.jsonc
{
  "name": "server",
  "type": "host",
  "entry": { "type": "./server.d.rut" }
}
// server/server.d.rut
pub host fn subscribe(bus: opaque, topic: str, handler: str) -> nil;
pub host fn emit(bus: opaque, topic: str, payload: str) -> nil;

Consumers reach a host pkg two ways:

The loader lowers the declared signatures into the mounted surface at load time; the compiler type-checks calls against them. A host pkg packs into a .rutbundle like any dep (module bundles).

The surface grammar

host fn name(params) -> T;            // concrete signature; generics are a
                                      // compile error — a generic parameter
                                      // has no shape the boundary checks
host struct Name { fields }           // flat record; every field a crossing
                                      // type; no methods, no field
                                      // initializers — the shape IS the
                                      // whole surface
prelude builtin fn name<T>(params) -> T;   // engine fn, compiler-lowered
prelude builtin class Name<T> { .. }       // engine type member contract
                                           // (the closed async pair among
                                           // them — `Future<T>`, `RunContext`)
prelude builtin impl i32 { .. }            // engine methods on a primitive
pub builtin class Name<T> { .. }           // the import-gated twin (below)

Rules:

  • The crossing set — host fn signatures are concrete over: nil, the primitives, str, bytes, and opaque. Returns may additionally use the answer optionals ?str / ?bytes / ?opaque. Named records never cross — a host struct decl is surface, not a signature type — and the anonymous-tuple lane belongs to the entry fn surface (value boundary). Everything else (user classes, Vec<T>, [T], interface-typed values, closures) is a compile error on the declaration.
  • any is not in the language. An any spelling fails at resolution as an unknown type — there is no any type to write. Seal polymorphic values with opaque(v) / opaque::downcast<T>(v) (opaque).
  • builtin is the engine’s reservation — spelled only in the toolchain’s own decl files (core, calc). A builtin in an embedder decl is a compile error. The engine’s contracts are spellings on types: the bracket markers on inherent impl members and the closed builtin class pair; library polymorphism stays plain interface (interfaces).
  • builtin is a contextual keyword: .d.rut-only; elsewhere it is a legal identifier.

The two builtin spellings

A builtin decl spells one of two strict forms — a bare builtin diagnoses “builtin must be spelled prelude builtin (ambient) or pub builtin (import-gated)”:

  • prelude builtin — the ambient engine surface: the name binds in every compilation unit, no use needed. The primitives and their builtin impl methods, opaque, StackTrace, and panic/string_join/capture_stacktrace are all ambient.
  • pub builtin — the import-gated engine surface: the name resolves only through use core::{ .. }, the way a package’s names do. Today’s rows are the closed async pair — Future<T>, RunContext — the disposal context, DisposalContext, and the weak reference, Weak<T> (interfaces, async and await, the Rc heap, weak references). The engine’s weave never consults the gate — it keys on the engine symbols — so a module with no imports still iterates, awaits, and launches; only spelling a name in source gates.

Using a pub builtin name without the use line is a resolution miss that names the fix, never a bare “unknown name”:

`Future` is not in scope — `use core::{ Future }`

The split is per name: a unit that imports one gated name still sees every ambient name for free, and an unused name in a use core line stays a lint, not an error.

  • opaque wraps native state; there is no host class. rut wraps the handle in a class of its own — the wrapper-class pattern (native containers API surface). Destructors still run deterministically: when a box’s rc hits 0, the payload’s finalize hook runs, then Rust Drop (the Rc heap).

Declaration mode

A .d.rut is parsed in declaration mode: declarations only, each complete as a surface.

allowednotes
use / pubvisibility exactly as in a module; non-exported decls are known inside the file, nameable nowhere else
letwith load-time constant initializers
enumthe member list is the whole definition
interfacemember signatures are the whole definition — signatures-only fits the surface model
structfields only, with load-time initializers
host fn / host structsignatures only, concrete over the crossing set
prelude builtin / pub builtin rowstoolchain decl files only — the two spellings above

Forbidden — the parser errors “implementation in a declaration file”: any fn/class body, statements. Symmetrically, a .rut file that spells host errors “belongs in a .d.rut”.

Signatures are derived, not hand-written

The registered callable’s Rust shape is the .d.rut row. The installer lane is a HostPkg builder per pkg — rows under bare names, the scope (the pkg’s name) spelled once — handed to the chain with pkg(Offer::Host(..)) — pkg(hp) coerces:

// one builder per host pkg; the scope string appears exactly once
let mut logger = rut_vm::HostPkg::new("server");
rut_vm::pkg_fn!(logger, "make", (&str,) -> OpaqueRef,
    |vm: &mut Vm, name: &str| vm.alloc_opaque_str(name::to_string()));
rut_vm::pkg_fn!(logger, "emit", (OpaqueRef, &str, &str) -> (),
    |_vm, _bus, _topic, _payload| Ok(()));

// the built pkg rides the run chain; .compile() installs it against
// the offered rows snapshot
let compiled = rut_driver::RutRun::new()
    /* ..offers.. */
    .pkg(logger.build())
    .entrypoint("app")
    .compile()?;

pkg_async_fn! is the async twin: one row spelling emits the five-row family (__start/__yield/__take/__cancel + the decl-row trap), the same expansion the ctx declares. The raw macros — register! / register_async! on the bare registry (see embedding and native modules) — remain the escape hatch (hand-spelled <scope>::<name> strings, the flat table’s own responsibility); everything above them is the same derived-signature machinery:

let mut hosts = rut_vm::interp::HostRegistry::new();
hosts.register::<_, (&str,), OpaqueRef, _>(
    "server::make", |vm: &mut Vm, name: &str| vm.alloc_opaque_str(name::to_string()),
);
  • The signature is a fixed array of type ids derived from the closure’s parameter and return types; a param type with no crossing impl is a compile error at the register site.
  • Both body shapes fit: -> R (infallible) and -> Result<R, Trap> (fallible). Errors travel an explicit trap channel — a trapped body propagates as Err(Trap) with a rut backtrace (embedding and native modules).
  • &str / &[u8] params are zero-copy borrows scoped to exactly the call (value boundary).
  • One installer per pkg: a duplicate row name inside a builder panics, a second Offer::Host for the same scope panics (at the .compile() install), and a pkg cannot spell another pkg’s rows — the scope comes solely from HostPkg::new.

The load-time contract — asymmetric, by design

Offering a host pkg declares; the embedding Rust binds. The .compile() install checks the two sides against each other, per pkg, against the offered rows snapshot (rut_driver::host_pkg_ctx(pkgs) — the same snapshot exposed for hosts that bind outside the chain):

  • scope offered, a declared row never bound — a panic naming the pkg (the installer left it out), and .build() refuses a boot naming it again when the installer never ran at all;
  • signature drift on a declared row — a panic; this is the only drift gate on the boot path;
  • scope NOT offered — the whole pkg merges inert: no panic, no gate. Blanket installs are legal (the CLI installs all of them; a program that offers a subset carries the rest as dead bindings), and rows the decl does not name ride as inert extras.

The raw lane’s verify_against(&rut_driver::declared_host_fns(&pkgs)) re-checks the whole flat table and panics on all three mismatch classes:

  1. declared but unbound — a rut call would trap mid-run;
  2. bound but undeclared — no surface declares what the host installed;
  3. signature drift — the decl says (opaque, str, str) -> nil, the binding took (opaque, i64, str).

The law follows the offer: offer what you bind — with the asymmetry the offer law needs: rut-declares-but-host-never-binds is loud; host-binds-but-rut-never-declares rides inert.

Slots, not strings

Compiling a declaration file assigns every host fn a stable slot id in declaration order; the module binary carries the slot table. Calls compile to callnat { slot } — names are binding-time labels, resolved once at boot, never dispatch keys, never in IR. A typo’d binding is a startup error, never a runtime one. IR cannot inline into native bodies; if a body should be optimizable, it is rut source — the wrapper class is exactly that place.

Async host fns

// http_host/net/mod.d.rut — an async row expands into a five-row
// family on the path-qualified name
pub host async fn http_send(c: opaque, method: str, url: str,
                            headers: str, body: bytes) -> opaque;

The embedder binds the family with one spelling; the closure spawns the work, hands out a completer clone, and returns. On the installer lane the row name is the scope-relative spelling — bare for a root row, the mod path for a row under a surface tree (net::http_send; the scope itself prefixes once, at the install):

let mut http = rut_vm::HostPkg::new("http_host");
rut_vm::pkg_async_fn!(http, "net::http_send",
    (OpaqueRef, &str, &str, &str, &[u8]) -> OpaqueRef,
    |c: OpaqueRef, method: &str, url: &str, headers: &str, body: &[u8]|
        -> rut_vm::Completer<OpaqueRef> {
        let done = rut_vm::Completer::new();
        let w = done.clone();
        std::thread::spawn(move || {
            match do_request(c, method, url, headers, body) {
                Ok(r)  => w.complete(r),
                Err(e) => w.fail(e.to_string()),
            }
        });
        done
    },
    /* optional abort hook: */ move |_c| { /* best-effort cancel */ },
);
// the built pkg rides the chain: RutRun::new()...pkg(http.build())

// the raw lane (bare registry, full `scope::path::name` strings) — the
// escape hatch, same emitter:
// rut_vm::register_async!(hosts, "http_host::net::http_send", ...);

pkg_async_fn!(pkg, name, (P…) -> R, start [, abort]) (and its raw twin register_async!(hosts, …)) emits the family the compiler’s weave joins:

emitted rowmeaning
<name>the decl row itself; calling it directly traps — the weave mints the future at the call site
<name>__start(P…) -> opaqueruns the closure, boxes the Completer as the future’s state cell
<name>__yield(state, cx) -> i32resumption probe: 0 pending, 1 ready, 2 failed
<name>__take(state) -> Rmarshals the answer onto the VM thread; a failed completer traps here
<name>__cancel(state)the abort hook when given; otherwise the disclosed no-op
Completer<T> APIMeaning
Completer::new()a fresh cell; clone() shares it (one Arc)
complete(v) / fail(msg)settle from any thread (atomics + mutex only)
poll() -> i32the driving loop’s probe
take_result() -> Result<T, Trap>VM thread only; a fail message becomes the trap at the await

Thread law: the VM stays single-threaded; workers touch only the completer. Cancellation is best-effort — a worker runs to its blocking completion and the late answer is discarded. See the host futures bridge and async and await.

Declaration files as artifacts

A published package ships:

artifactrole
mod.rutcthe compiled module binary: bodies + the surface, the linking truth (module binary and verification)
mod.d.rutthe surface text — hand-written, editable, publishable (humans, LSP); documentation only, never the loader’s source of truth
  • The surface rides the binary: a consumer binds p’s exports from mod.rutc alone. Nothing is rebuilt from .d.rut text — impl-to-fn ids, interface-table indices, and namespace/host rows are not derivable from text without guesswork.
  • Link compares the consumer’s bound surface against the binary’s export table — a pure data compare. Drift is a load error naming both modules, never a runtime surprise.
  • Publishing is not encryption: bodies are compiled and local names are stripped (--release drops member-name strings), but code is recoverable with effort. What publishing guarantees is API discipline.

Surface resolution during compilation

When module M uses package p, the compiler resolves p’s surface, first hit wins:

  1. source — p’s rut source on the source path: compile it normally;
  2. bundle — a mounted .rutbundle: its compiled .rutc (bodies + surface on the wire) — or its bundled source for a splice-needed group; explicit mounts outrank stray sources, never dev source;
  3. host registry — for host pkgs, the .d.rut the embedder ships beside the registered implementation.

Bodies resolve only at link/run. Compiling M against a package whose implementation is absent is legal and complete — checking passes; only running requires the bodies.

End-to-end shape

The chat-bus plugin is the canonical walkthrough: a Rust server binds server::subscribe/server::emit over its own EventBus box, the plugin subscribes rut export names per topic, and every emit re-enters rut to format the wire line — see 03 — Plugin. For a full application host with mounted std packages and an async entry, see 06 — GitHub viewer CLI.