Compiled Moth calls registered Rust host functions, and Rust calls builder-selected Moth exports, through one closed value boundary. Accepted design with implementation deferred.
The native host ABI is the physical Wasm boundary between compiled Moth and a native Rust embedder. It covers registered host imports called from Moth and builder-selected Moth exports called from Rust. Lappet checks and executes these facts and never derives them from Wasm carriers, source names or Rust layouts.
This is a closed value boundary for the restricted host-binding profile. Ordinary Moth inputs cross as non-retained reads. Results become independent Moth storage. Only registered opaque host resources give Rust shared or exclusive access to retained host state. No alias, lifetime owner, ownership tag or destruction responsibility of ordinary Moth storage crosses it.
Owners:
docs/developer-docs/project-builders/host-packages.mtf owns the Rust signature profile and its Moth meaning.ValidatedMemoryPlan still owns every allocation, cleanup and ownership decision inside Moth. The boundary layouts here don't constrain Moth's internal string, collection or family representations.crates/lappet/docs/host-abi.md owns Lappet's adapter checks, staging table, resource table, host context and fault handling.The semantic rules are unchanged. A fallible call runs once and takes either its success edge or its error edge. Ordered success slots stay separate from the single error channel. No Result value, tuple or semantic aggregate is manufactured at the boundary.
Accepted design with implementation deferred. The Wasm backend lowers no registered host-binding import and has no fallible, Error or boundary-handle lowering. No ValidatedMemoryPlan producer exists either. These layouts are the target contract for that producer. They don't authorise a temporary memory planner, a guessed layout or an executable artefact with placeholder ABI facts. Current support lives in the progress matrix.
u32 linear-memory offsets, never host pointers. Address and length arithmetic is checked. An out-of-bounds or overflowing range is a boundary fault, never truncated.i32 or f32 carrier and 8 bytes for an i64 or f64 carrier, naturally aligned. Narrow integers are stored canonically extended in their 4-byte field. Frame storage is separate from Moth's ordinary 1, 2, 4 and 8 byte scalar storage.repr(C) nor a Rust reference to guest memory implements a frame.The host side checks everything the guest writes. It validates every argument, span, tag, token, status, reserved field and active-payload padding it reads. A noncanonical value is a boundary fault.
Guest code trusts fields the host adapter writes, because the adapter validates each value before writing it. That covers import results and export arguments. Generated guest code doesn't revalidate them, apart from its own semantic guards such as the external binary-float check below. An import status other than 0 or 1 is never written by a conforming adapter. Generated code traps on it.
| Moth | Wasm carrier | Canonical value | |---|---|---| | Bool | i32 | Exactly 0 or 1 | | Char | i32 | Unicode scalar value, no surrogate | | I8, I16, I32 | i32 | Value in the exact signed range, canonically sign-extended | | U8, U16 | i32 | Value in the exact unsigned range, canonically zero-extended | | U32 | i32 | All 32 bits, reinterpreted as unsigned | | Byte | i32 | 0 through 255, canonically zero-extended | | I64, U64 | i64 | All 64 bits with the declared signedness | | F32 | f32 | Finite, except a raw host import result | | F64 | f64 | Finite, except a raw host import result |
Byte and U8 share wire bits and keep distinct canonical identities. A matching carrier never selects or converts a semantic type. The descriptor's canonical type decides which check applies.
Binary floats follow the external numeric contract. Import arguments, export arguments and export results must be finite and the receiving side checks them. A float result from a host import crosses as its raw carrier. HIR's external binary-float guard validates it at the resolved precision before Moth code observes it. Through a declared Error! channel a non-finite result becomes builtin Error code 304. Otherwise the integrity guard halts. The adapter never faults on a non-finite import result. See External binding contracts.
F16 isn't part of the V1 host profile, because the host-packages Rust profile has no F16 shape and V1 defines no binary16 conversion. Dec values, records, choices, collections, maps, tuples and functions have no V1 host encoding.
A string parameter is two i32 carriers, data address then byte length. Inside a frame it uses this record:
```text AbiSpan size 8, align 4 +0 data u32 Wasm32 byte address +4 len u32 UTF-8 byte length ```
The bytes are UTF-8 with no terminator. The canonical empty string is (0, 0). Nonempty data at address zero isn't inherently invalid. The reader checks that data + len fits in memory without overflow, that len is at most 2_147_483_647 and that the bytes are valid UTF-8. The compiler may materialise a span from any valid internal string representation. A span is not a string header requirement.
A span is valid only for the synchronous boundary operation that received it. The receiver either borrows it for that operation or copies it. It never retains it.
A host import never calls a guest allocator. A Rust-produced string returns a staged ticket instead:
```text AbiStagedText size 16, align 8 +0 ticket u64 Nonzero single-use staging token +8 len u32 UTF-8 byte length, at most 2_147_483_647 +12 reserved u32 Zero ```
The empty string is (0, 0, 0) and has no staging entry. A nonempty result has a nonzero ticket naming an entry in the receiving instance's staging table. A ticket is never a host pointer.
After the import returns, compiler-generated guest code allocates an independent string through its validated memory plan. It then calls the reserved import moth-abi-v1.staged_text_take(ticket i64, destination i32, len i32), which has no result. The host checks that the ticket is live in this instance, that len equals the staged length and that the destination range is in bounds. It then copies the bytes and consumes the ticket. Any mismatch is a boundary fault.
Tickets have a bounded lifetime:
staged_text_take itself is exempt.The guest has no discard helper. A ticket leaves the table only by being taken or by the host's fault and teardown cleanup. An allocation failure in the generated take sequence therefore traps. It never becomes an invented Error! result. Host side effects that already happened aren't rolled back.
A Moth export returning a string to Rust writes an AbiSpan into its result frame. The export wrapper first copies every returned string into call-scope storage, including String? payloads and the error message, so no span points at storage the Moth program keeps. Lappet copies the bytes into an owned Rust String before ending the scope. Staged tickets are used only for Rust-produced strings.
V1 supports one T? layer whose payload is an eligible scalar or a string. There are no nested options, nullable-pointer encodings or sentinel values.
A parameter flattens to an i32 tag followed by the payload carriers. Tag 0 is none and tag 1 is present. Every payload carrier is zero for none.
A frame field starts with a u32 tag at offset zero, followed by the payload at its natural frame alignment. The field rounds up to the larger of the tag and payload alignment.
| Frame payload | Size | Layout | |---|---:|---| | U32? and other 4-byte scalars | 8 | tag @0, value @4 | | I64? and other 8-byte scalars | 16 | tag @0, padding @4, value @8 | | String? as AbiSpan | 12 | tag @0, span @4 | | String? as AbiStagedText | 24 | tag @0, padding @4, staged record @8 | | Opaque resource ?, layout only | 16 | tag @0, padding @4, token @8 |
An invalid tag or a nonzero absent payload is a boundary fault. none, a present zero and a present empty string stay distinct. The canonical option type identifies T. A shared physical layout doesn't make two option types interchangeable.
i32 out_frame as the final parameter and the function has no Wasm result.Every fallible call takes i32 out_frame as its final parameter and returns i32 status:
0: success. Read only the ordered success slots.1: declared error. Read only the error record.Error.code is ordinary error data. Code 0 with status 1 is still an error.
A result frame is a physical union of two independently laid-out payloads, each starting at offset zero:
Only the active channel's fields become Moth values. The failure edge never reads success fields and the success edge never reads the error record. Moth's HIR Call and Invoke remain the semantic authority. The frame is neither a tuple nor a Result.
Builtin Error has message String and code U32. Its record depends on the direction:
```text AbiHostError size 24, align 8 Rust import to Moth +0 message AbiStagedText +16 code u32 +20 reserved u32 Zero
AbiGuestError size 12, align 4 Moth export to Rust +0 message AbiSpan +8 code u32 ```
V1 host bindings and exports use only the builtin Error! channel. Custom Moth E! types stay available to Moth source and to Moth wrappers over host bindings. Selecting an export with a custom E! channel is diagnosed at selection. A Rust failure becomes a Moth error only when the binding returns it through the declared channel. A panic, trap, malformed span, invalid token or descriptor mismatch is a fault, never status 1.
The conceptual import fn(text String) -> U32, Error! lowers to:
```text params (i32 text_data, i32 text_len, i32 out_frame) result i32 status frame size 24, align 8 success U32 @0 failure AbiHostError @0 ```
An export returning I64, Error! uses a frame of size 16 and alignment 8. Its success payload is 8 bytes and its 12-byte AbiGuestError rounds up to the frame alignment.
A registered opaque resource crosses as one i64 token, or an 8-byte, 8-aligned frame field. Zero is invalid. A token names an entry in a host-owned resource table. It is not a host pointer, a Moth allocation-family handle or an authorisation credential. The host resolves and checks every token before any Rust reference exists. Token issue, uniqueness, access guards and lifecycle belong to Lappet's resource table.
The guest stores tokens as plain values. It never stores host pointers or borrow state in linear memory.
V1 host bindings accept resources only as &T and &mut T parameters, as host-packages defines them. The host resource API creates and closes resources on the Rust side. A token reaches the guest as an export argument. Resource results, optional resources and guest-side close bindings have a fixed carrier and no V1 Rust mapping.
For example, Rust creates a Window through the host resource API and receives a token. It calls a selected export open_ui |window ~Window| and passes the token as one i64 argument. Moth later calls the host binding resize(~window, 800, 600) with that token. The adapter resolves it in the instance's table, takes exclusive access for the call and releases the access when Rust returns.
Each reachable host binding imports one function:
moth-host-v1<canonical package path>#<symbol path>, with symbol path components joined by ., for example @platform#has_prefix or @core/io#input.newThe item is unique because canonical package paths can't contain # and symbol components can't contain .. Registry validation of the # rule is a compiler prerequisite. The item omits PackageOrigin because a canonical package path is unique within one external-package registry. It derives only from the canonical binding identity, never from a registration-order or build-local ID. The manifest still carries the structured identity. Lappet matches implementations by that identity and never parses the item string.
Compiler-owned ABI helper imports use the module moth-abi-v1. Compiler-owned helper exports use the prefix moth_abi_v1_. Builder-selected export names can't start with moth_ or __moth and can't equal memory or any other compiler-emitted export.
A builder selects host-callable exports explicitly. An eligible function is a concrete function on the package facade's public surface. Public visibility alone exports nothing, there is no moth_start convention and private or unselected declarations are never exported. Each selection names one facade export binding and supplies a builder-chosen Wasm export name, unique within the artefact.
An export accepts the V1 parameter families on this page, including resource tokens. It returns zero or more ordered success slots of scalars, strings and their options, with an optional builtin Error! channel. Selection rejects resource and optional-resource results. The compiler emits a checked wrapper using the same direct-result and result-frame conventions as imports. Unsupported signature types are diagnosed at selection.
Moth to Rust. The guest builds valid spans and a zeroed frame, then calls the import. The host adapter checks frame bounds and alignment and every argument before Rust runs. Rust runs once and the adapter writes only the active result, staging owned text. The guest resumes, takes staged text into its own storage and continues on the edge selected by the status. A host import never calls into the guest. V1 has no callbacks, nested guest calls or async calls.
Rust to Moth. An export call runs inside one call scope, served by three reserved helper exports:
| Helper | Signature | Behaviour | |---|---|---| | moth_abi_v1_scope_open | () -> () | Opens the instance's single scope. Traps if a scope is open | | moth_abi_v1_scope_reserve | (size i32, align i32) -> i32 | Returns scope-owned storage. Traps on a size of zero, an alignment other than 4 or 8, allocation failure or no open scope | | moth_abi_v1_scope_close | () -> () | Releases every scope-owned allocation. Traps with no open scope |
The host:
(0, 0) with no reservationScopes don't nest. Reservations and returned spans are valid only inside their scope. Closing releases only scope-owned storage, including the wrapper's result copies, and never storage the Moth program keeps. The host calls only helpers and the selected export while a scope is open.
The call fails as a whole when any step faults. A trap in a helper or the export is a guest trap. A noncanonical status or result field is a boundary fault. In both cases the host discards any values already copied and makes no further guest call. That includes skipping scope close.
A faulted instance therefore keeps any open scope and can't take another export call under the V1 helper set. Lappet's runtime checkpoint decides fault disposition within that limit. Reusing a faulted instance needs an approved reset helper in a later ABI version.
| Path | Outcome | Cleanup owner | |---|---|---| | String argument to Rust | Rust receives a call-scoped &str, borrowed or copied | The adapter drops any copy when the call ends | | Rust returns a string | Ticket staged, frame written | Guest takes the ticket | | Rust returns builtin Error | Status 1, message staged | Same as a staged string | | Invalid argument, span, token or frame | Boundary fault before Rust runs | Nothing to release. Lappet's fault handling applies | | Rust panics or the adapter faults | Host fault, never status 1 | Lappet's fault handling discards the call's staged entries | | Guest allocation fails while taking text | Guest trap | Lappet's fault handling discards the ticket | | Ticket outstanding at entry return or another import | Boundary fault | Lappet's fault handling discards the ticket | | Export call succeeds | Host copies results to Rust values | Scope close releases scope storage | | Export returns Error! | Host copies AbiGuestError | Scope close releases scope storage | | Export status or result frame is noncanonical | Boundary fault | No guest call runs. Lappet's fault handling applies | | Export or scope helper traps | Guest trap. Guest state may be partial | No guest call runs. Lappet's fault handling applies |
Host IO already performed is never rolled back.
The compiler produces one immutable host manifest per Wasm artefact and the build system returns it with that artefact. It is separate from the build system's output-ownership manifests. It describes only reachable required imports and builder-selected exports. Each entry records:
The manifest is a compiler-owned value. A serialised form is deferred until persistent artefacts need one. Target validation proves legality before emission. Before guest start, Lappet matches the manifest against the supplied Rust implementations and the module's actual imports and exports, including physical signatures. Missing, extra or incompatible requirements and memory or protocol mismatches fail closed. Lappet never repairs a mismatch by guessing a name or installing a stub.
| Family | V1 status | |---|---| | Exact scalars except F16 | Supported | | F16, Dec | Deferred | | String inputs and results | Supported | | One T? layer over a supported scalar or string | Supported | | Builtin Error! channel | Supported | | Custom E! on host bindings or exports | Deferred. Map in Moth source | | Opaque resource parameters &T, &mut T | Supported | | Resource results, optional resources, guest-side close | Carrier fixed. No V1 Rust mapping | | Zero or one success slot on host imports | Supported | | Several ordered success slots on host imports | Layout fixed. Registration rejects them in V1 | | Several ordered success slots on exports | Supported. Lappet's Rust call API is later runtime design | | Byte buffers | Deferred | | Records, choices, collections including {Byte}, maps, tuples | Deferred | | Callbacks, async calls, re-entry | Excluded from V1 |
A deferred family needs its own approved layout before any binding accepts it. A V1 binding never maps it implicitly.
The Wasm producer must deliver these before any native host call executes:
ValidatedMemoryPlan producer for the boundary's string, frame and scope allocations.# rule.ExternalWasmLowering::HostFunction placeholder.out_frame and status, plus builtin Error value lowering.i64 resource-token carriage, replacing today's i32 handle comment on ExternalAbiType::Handle.staged_text_take import and the call-scope helper exports.host.assertion_failed import into the reserved helper namespace with a frozen span-based signature. Today it takes an i32 string handle and the HTML builder's JavaScript bootstrap implements it, so that host moves with it.crates/lappet/docs/host-abi.md: Lappet adapter, tables and fault handling