本页尚未翻译,以下为英文原文。
#1.8. WASM component model - ffi::wit
本页内容
The WebAssembly Component Model (bytecodealliance.org; Preview 2 stabilized in January 2024) is the foundation for defining typed cross-language interfaces. It replaces the raw pointer + length model that traditional C ABI FFI (1.7) relies on with rich types: record / variant / resource.
#1.8.1. WIT - WebAssembly Interface Types
WIT is a language-neutral interface definition language.
package example:fs;
interface fs {
record stat {
size: u64,
mtime: u64,
is-dir: bool,
}
variant error {
not-found,
permission-denied,
io-error(string),
}
resource file {
constructor(path: string);
read: func(buf-size: u32) -> result<list<u8>, error>;
close: func();
}
open: func(path: string) -> result<file, error>;
}
An interface defined this way can be imported or exported from any language: Rust, Go, Python, Nabi and so on.
#1.8.2. Binding form on the Nabi side
The import side uses an external component. Here wit/fs.wit holds the 1.8.1 interface with package example:fs; at its top.
ffi::wit::import { "wit/fs.wit" } // relative to this source file
use example::fs::fs::{File, Error};
let f = File::new("data.txt");
let bytes = try f.read(1024); // throws (Error) -> List<u8>
f.close();
The export side provides a component; calculator.wit declares add: func(a: s32, b: s32) -> s32 in a world.
ffi::wit::export { "calculator.wit" }
#[wit::export]
fn add(a: i32, b: i32) -> i32 { a + b }
#Paths and placement
- A path is relative to the source file. It names a
.witfile or a package directory, whosedeps/holds its dependencies. - The item is allowed in the program's package and in dependencies. Its bindings go in the module that holds it (in a dependency, that dependency's module), under
ns::pkg::iface(wasi::filesystem::types). - WIT types become PascalCase Nabi types (
descriptor-type→DescriptorType,file→File); functions and fields become snake_case.
#Worlds
A world in a named file is the component. Otherwise the keyword decides: ffi::wit::import imports the interfaces, ffi::wit::export exports them. include ... with { a as b } renames the included items.
#Type mapping
| WIT | Nabi |
|---|---|
record | struct |
variant, enum | enum |
flags | struct of bool fields with Default (at most 32 flags) |
option<T> | T? (nested options keep their layers: option<option<T>> → T??) |
result<T, E> | Result<T, E>; a function returning it is throws (E) -> T |
tuple<..> | tuple |
list<T> | List<T> |
list<T, N> | [T; N] |
string | str (UTF-8) |
char, bool, f32, f64 | the same |
sN / uN | iN / uN |
future<T> | AsyncFuture<T> |
stream<T> | core::channel::Receiver<T> (closing the sender ends it) |
error-context | bare::ffi::wit::ErrorContext |
imported resource | a handle struct, dropped with using / Drop |
exported resource | the user's #[wit::export] pub struct |
#Async
An async func is an async fn, both imported and exported. A synchronous task (a preview 2 main, a synchronous export) cannot wait for the component model; doing so is a runtime panic, so async imports are awaited inside async exports. A preview 3 command exports wasi:cli/[email protected] as #[wit::export] async fn run() -> Result<(), ()>. Async export calls run concurrently, each a component model task; a call returns its result in its own turn. Inside an async export, sockets and timers are waited on between the host's events; with component model events also pending they are checked at least every 10 ms (a preview 2 pollable and the component model's events cannot be waited on at once). An async export that waits for what nothing delivers waits; another call may still deliver it.
The async canonical ABI the generated bindings call lives in std::wit: it runs on the executor, and stream<T> maps to a core type. Memory helpers, blocks, handles and ErrorContext stay in bare::ffi::wit.
#Exports
An exported function is a #[wit::export] fn in the item's module, matched to the WIT function by its snake_case name. An exported resource is a #[wit::export] pub struct whose impl gives new (the constructor), the methods and the static functions; a fallible constructor (result<r, ..>) is a throwing new, and the resource's destructor runs its Drop. A missing export is a compile error.
A package that exports WIT and whose entry file has neither fn main nor top-level statements is a reactor: it exports no wasi:cli/run (4.16.1).
#Targets
WIT needs wasm32-wasip2 (a WASI preview 2 component); on any other target it is a compile error. Exports may be called before main: the runtime starts on the first export call.
A prebuilt dependency carries the .wit files its ffi::wit items read in its NABIHIR (refs-lang 9.4.7); a dependent does not read them from disk.
#Restrictions
An imported interface cannot use types of an interface the component exports; that is a compile error.
#Binding runtime - bare::ffi::wit
The generated bindings call these helpers; ordinary code uses the bindings. Blocks come from the C allocator, including the ones the host fills through cabi_realloc, and a lifted string or list frees its block once copied into GC memory. The values one import call lowers into blocks are freed together after the call; an export's are freed by its post-return function.
// bare::ffi::wit: linear memory at canonical ABI addresses (i32)
unsafe fn load_u8(a: i32) -> u8; // also load_u16 / load_i32 / load_i64 / load_f32 / load_f64
unsafe fn store_u8(a: i32, v: u8); // also store_u16 / store_i32 / store_i64 / store_f32 / store_f64
// joined flat slots of a variant
fn f32_bits(x: f32) -> i32;
fn f32_from(x: i32) -> f32;
fn f64_bits(x: f64) -> i64;
fn f64_from(x: i64) -> f64;
fn char_from(x: i32) -> char; // panics on a non-scalar
fn bad_case() -> !; // panics: discriminant out of range
const BLOCKED: i32 = -1; // a copy or call did not finish at once
const DROPPED: i32 = 1; // a copy's other end was dropped
unsafe fn free(a: i32);
unsafe fn str_take(p: i32, n: i32) -> str; // copies, then frees the block
unsafe fn bytes_take(p: i32, n: i32) -> List<u8>; // copies, then frees the block
struct Blocks { /* private */ }
impl Blocks {
fn new() -> Blocks;
fn alloc(self, size: i32, align: i32) -> i32; // an empty block is the address `align`
fn str(self, s: str) -> (i32, i32); // (address, length)
fn bytes(self, l: List<u8>) -> (i32, i32); // (address, length)
fn free(self); // frees every block
}
struct Handle { /* private */ }
impl Handle {
fn own(h: i32) -> Handle;
fn borrowed(h: i32) -> Handle;
fn get(self) -> i32; // panics once dropped or passed on
fn take(self) -> i32; // gives an own away; panics on a borrow
fn release(self) -> i32 | none; // the handle to drop, if still owned
}
struct Table<T> { /* private */ }
unsafe impl<T> Sync for Table<T> {}
impl<T> Table<T> {
unsafe fn new() -> Table<T>; // the caller keeps it to one thread at a time
fn insert(self, v: T) -> i32; // the rep
fn get(self, rep: i32) -> T; // panics once taken
fn take(self, rep: i32) -> T?; // frees the slot; none if taken already
}
struct ErrorContext { /* private */ }
impl ErrorContext { // WASI targets only
fn new(msg: str) -> ErrorContext;
fn debug_message(self) -> str; // the host may give an empty one
fn raw(self) -> i32;
fn from_raw(h: i32) -> ErrorContext;
}
impl Drop for ErrorContext { /* error-context.drop */ }
Copies of a Handle share one cell: passing an own on or dropping it empties every copy. A Table<T> keeps an exported resource's values by representation (rep) until the host drops its handle ([dtor]).
The type ErrorContext exists on every target; its methods and Drop exist on the WASI targets. Blocks, Handle and Table<T> implement Debug as their type name, and ErrorContext as ErrorContext { handle: n } (0.5.12); so do the std::wit types Waiting, FutureOps<T> and StreamOps<T>. The functions that panic on a bad argument (char_from, bad_case, Handle::get / take, Table::get) are #[track_caller], and their messages follow 0.5.10 rule 6 (wit::char_from: not a Unicode scalar value, Handle::get: resource used after it was dropped or passed on). The slot helpers f32_bits, f32_from, f64_bits, f64_from and char_from keep the names the generated bindings call; they are canonical ABI names, outside the 0.5.11 naming table.
#1.8.3. Differences between C FFI and WIT
The two approaches differ clearly along several axes.
| Aspect | C FFI (1.7) | WIT (this chapter) |
|---|---|---|
| Type system | C primitives + user structs | record / variant / resource |
| Safety | low (raw ptrs managed by hand) | high (typed) |
| Memory management | malloc/free | resource (automatic destructor) |
| Error handling | errno / return value convention | first-class result<T, E> |
| String | null-terminated | length-prefixed UTF-8 |
| List | (ptr, len) manual | list<T> automatic |
| Call cost | almost none (direct call) | trampoline (~ns) |
| Scope | every native target | wasm32-wasip2 (preview 2 component) |
| unsafe required | ✓ | ✗ |
#1.8.4. Selection criteria
The criteria are simple: they depend on what is being called and where it is deployed.
| Scenario | Recommendation |
|---|---|
| Calling a traditional C library | C FFI (1.7) |
| System calls (libc, Win32) | C FFI |
| GPU / SIMD intrinsics | C FFI |
| Safe interface with other languages | WIT |
| Deployment to WASM environments | WIT |
| Plugin / sandbox isolation | WIT |
| Multi-language (Modular / Mojo etc.) | WIT |
The main significance of this chapter is that Nabi supports both traditional C FFI and WIT. Users choose either according to their safety, performance and target environment constraints.
#1.8.5. References
For further reading:
Found a mistake? Edit this page on GitHub. Last updated