Introduction
WeaveFFI generates idiomatic bindings for 11 languages from one API definition, over a stable C ABI. Write the API as safe Rust tagged with WeaveFFI’s attributes, or as a YAML or JSON IDL implemented by any library that can export C symbols (C, C++, Zig, and so on). WeaveFFI emits packages for C, C++, Swift, Kotlin, Node.js, WebAssembly, Python, .NET, Dart, Go, and Ruby that all call the same C functions.
The design in one page
One definition, two front doors. A Rust producer tags ordinary items
(#[weaveffi::export] on a function or an impl block,
#[weaveffi::record] on a struct, and so on). Each attribute emits the
item’s extern "C" functions and embeds a description of the item in the
compiled library, and the CLI reads that description back out to emit the
bindings, so the bindings describe exactly the library you compiled,
#[cfg] and Cargo features included. A non-Rust producer writes an
IDL instead and implements the C header WeaveFFI
generates from it.
One library, one namespace. Every record, enum, error domain,
interface, callback interface, and function has a name unique across the
library, and every C symbol is the library’s prefix plus that name
(kvstore_Store_open). An IDL may still be split across files with
imports:, and a Rust crate across modules; neither changes a name.
Identity drives every name. A library has one resolved
identity: a package name, a C symbol prefix, and a
native library base name. For a Rust producer all three come from the crate
(kvstore gives kvstore_Store_open, libkvstore.so, and an npm, PyPI, or
NuGet package named kvstore). Nothing a generator emits is named after
WeaveFFI, so any number of WeaveFFI-built libraries can live in one process.
A small, explicit C ABI. In revision 6 every value
crosses as exactly one C value, in every position: a scalar by value, an
optional scalar as a {p}_opt_* struct, an object as a pointer, and
everything else (strings, bytes, typed arrays of numbers, and the
serialized value buffers that carry records,
rich enums, and the remaining optionals, lists, and maps) as one
{p}_run, a pointer and a byte length. A callback interface is one
{ctx, vtable} struct. Every fallible call reports through a {p}_error
struct carrying a code, a length-delimited message, and the code’s fields.
Async functions complete through a callback that fires exactly once, and
cancellation is a first-class runtime code.
Bindings that refuse to drift. Every declaration exports a contract function returning a hash of its signature. Each consumer checks the ABI revision and every declaration it was generated with when it loads the library, so a stale binding fails loudly, naming the declaration that changed, instead of misreading memory, while a library that only added declarations, error codes, or callback methods keeps loading.
Idiomatic generators. Each target maps the model onto its own idioms:
objects become classes with deterministic disposal and a garbage-collector
backstop, async functions become async/await, coroutines, promises, or
tasks with native cancellation, iterators stay lazy, and error domains
become typed exceptions or error values. The
capability matrix summarizes all eleven.
Standalone output. Generated packages are self-contained: helper code
(the value-buffer codec, error types, object wrappers, loaders) is generated
into each package, and no target needs compiled glue of its own, so
consumers never install WeaveFFI. weaveffi package bundles prebuilt native
libraries into publishable packages per ecosystem.
Where to next
- Getting Started: a Rust producer called from C and Python in a few minutes, plus the IDL path for a C implementation.
- The Rust Producer Macros: every attribute, with a compiled example of each.
- C ABI Contract: the normative description of the boundary.
- Comparison and FAQ: how WeaveFFI relates to UniFFI, Diplomat, cbindgen, and the single-language bridges.
- Stability and Versioning: what the version numbers promise.
Getting Started
This guide builds a small Rust library, generates bindings for it, and calls
it from C and from Python. A second, shorter path at the end starts from an
IDL instead and implements the generated C header in C. The code on this
page is the examples/getting-started
crate and the examples/idl/greeter
project, which the workspace’s tests build and call.
Install the CLI
You need a stable Rust toolchain. Install the
weaveffi CLI from crates.io (or grab a prebuilt binary with
cargo binstall weaveffi-cli):
cargo install weaveffi-cli
weaveffi --version
Write the producer
Create a library crate and add the weaveffi crate. It needs no
crate-type: WeaveFFI builds the C dynamic library itself (with cargo rustc --crate-type cdylib).
cargo new --lib mathlib
cd mathlib
cargo add weaveffi
Replace src/lib.rs with this. Everything here is safe Rust; the attributes
write the extern "C" layer.
/// Errors the math functions report.
#[weaveffi::error]
#[derive(Debug)]
pub enum MathError {
/// division by zero
DivisionByZero = 1,
}
/// Add two integers, wrapping on overflow.
#[weaveffi::export]
pub fn add(a: i32, b: i32) -> i32 {
a.wrapping_add(b)
}
/// Divide `a` by `b`, failing when `b` is zero.
#[weaveffi::export]
pub fn div(a: i32, b: i32) -> Result<i32, MathError> {
a.checked_div(b).ok_or(MathError::DivisionByZero)
}
/// Greet someone by name.
#[weaveffi::export]
pub fn greet(name: &str) -> String {
format!("Hello, {name}!")
}
// The runtime symbols (errors, memory, cancel tokens), once per library.
weaveffi::export_runtime!();
A few things to notice:
- Every C symbol starts with the crate’s name, so this crate exports
mathlib_add,mathlib_div, andmathlib_greet, plus the runtime (mathlib_error_clear,mathlib_run_free, and so on). A library is one namespace, so a symbol is the prefix and the item’s name, wherever in the crate the item is declared. Result<i32, MathError>makesdivthrow theMathErrordomain. The enum’s discriminants are the stable error codes, and the macro generates itsDisplayfrom each variant’s doc comment (or a#[weaveffi(message = "...")]template), which is the message consumers see. AResultwhose error type is an untyped error (String,std::io::Error,weaveffi::Error) works too: it throws a message without a code to match on.weaveffi::export_runtime!()appears exactly once, at the crate root.
The producer macro guide covers records, enums, objects, callbacks, iterators, async functions, and custom types.
Configure and generate
Run weaveffi init in the crate. It writes a weaveffi.toml whose
[project] table points at the crate itself, then lists anything the crate
still needs (the weaveffi dependency, an exported item, the
export_runtime! call):
weaveffi init
The file it writes generates the C header and the Python package; edit
targets to pick the languages you ship (without it, every target is
generated):
[project]
input = "."
out = "bindings"
targets = ["c", "python"]
Generate the bindings. With a [project] table, weaveffi generate needs
no arguments and works from any directory in the project:
weaveffi generate
weaveffi generate builds the library with Cargo’s dev profile (pass
--profile <name> for another, and -F/--features for Cargo features),
then reads the API from the library it built: the attributes embed a
description of every exported declaration in the library, so the bindings
match the compiled code exactly, #[cfg] included. weaveffi extract
prints that description as an IDL.
The output has one directory per target: the C target writes
bindings/c/mathlib.h, and the Python target writes an installable package
named mathlib. Run weaveffi generate again after any change: it rewrites
only the files whose contents changed and removes files a previous run wrote
that it no longer produces, using the generation records it keeps in
bindings/.weaveffi/ (commit them with the bindings).
Call it from C
The header is the contract every other binding is built on. Each value is
one C value: a string is a mathlib_run (a pointer and a byte length, never
NUL-terminated), every call overwrites a mathlib_error the caller provides,
and a returned run is released with mathlib_run_free:
/* A C consumer of the getting-started library, built against the generated
header (bindings/c/mathlib.h). */
#include <stdio.h>
#include <string.h>
#include "mathlib.h"
int main(void) {
/* Refuse a library built from different source than the header. */
if (mathlib_abi_version() != MATHLIB_ABI_VERSION || mathlib_contract_check() != NULL) {
fprintf(stderr, "mathlib.h doesn't match the loaded library\n");
return 1;
}
mathlib_error err; /* every call overwrites it */
printf("2 + 3 = %d\n", mathlib_add(2, 3, &err));
mathlib_div(1, 0, &err);
if (err.code == mathlib_MathError_DivisionByZero) {
printf("error %d: %.*s\n", err.code, (int)err.message_len, (const char*)err.message_ptr);
mathlib_error_clear(&err);
}
/* A string crosses as a run: its UTF-8 bytes and their length, no NUL. */
const char* name = "C";
mathlib_run arg = {(const uint8_t*)name, strlen(name)};
mathlib_run greeting = mathlib_greet(arg, &err);
printf("%.*s\n", (int)greeting.len, (const char*)greeting.ptr);
mathlib_run_free(greeting);
return 0;
}
Build it against the library weaveffi generate built:
cc -I bindings/c main.c -L target/debug -lmathlib -o main
DYLD_LIBRARY_PATH=target/debug ./main # LD_LIBRARY_PATH on Linux
2 + 3 = 5
error 1: division by zero
Hello, C!
The first check is the one every generated binding makes for you when it
loads the library: mathlib_abi_version() must equal the header’s
MATHLIB_ABI_VERSION, and mathlib_contract_check() returns the name of
the first declaration the library has changed since the header was
generated, or NULL. Errors and Memory states
every ownership rule the generated bindings follow for you.
Call it from Python
While you iterate, run weaveffi generate --dev: it generates as usual,
then copies the library it built into the generated packages that look for
a bundled copy (the Python package does) and prints how the other targets
find it. Then install the package:
weaveffi generate --dev
pip install ./bindings/python
import mathlib
print(mathlib.add(2, 3)) # 5
print(mathlib.greet("Python")) # Hello, Python!
try:
mathlib.div(1, 0)
except mathlib.MathError as e:
print(e) # (1) division by zero
On import the package checks the library’s ABI revision and every
declaration’s contract, so a library built from incompatible source fails to
load with an error naming the declaration that’s missing or changed. To load
a library from somewhere else, set MATHLIB_LIBRARY to its full path; every
target that loads the library at run time honors that {PREFIX}_LIBRARY
variable. The Python page documents the generated
surface.
Ship it
weaveffi package --target python
weaveffi package builds the library in release mode for this machine
(that’s weaveffi build), then writes installable artifacts to dist/:
here a wheel with the library inside, which needs neither MATHLIB_LIBRARY
nor a compiler:
pip install dist/python/mathlib-*.whl
Packaging covers more platforms (iOS, Android,
Windows, wasm32), every target’s artifacts, and publishing.
Implementing an IDL in C
A producer doesn’t have to be Rust. Start from an IDL, generate the C header,
and implement it in any language that can export C symbols. Outside a Rust
crate, weaveffi init writes a starter IDL and a weaveffi.toml:
mkdir greeter && cd greeter
weaveffi init # writes greeter.yml and weaveffi.toml
Edit greeter.yml to declare the API (the IDL reference
has the full schema):
# yaml-language-server: $schema=https://weaveffi.com/weaveffi.schema.json
version: "0.13.0"
doc: A greeter implemented in C.
functions:
- name: add
doc: Add two integers, wrapping on overflow.
params:
- { name: a, type: i32 }
- { name: b, type: i32 }
return: i32
- name: greet
doc: Greet someone by name.
params:
- { name: name, type: string }
return: string
For an IDL the identity comes from [package] in weaveffi.toml, so the
prefix and the library are both greeter:
[project]
input = "greeter.yml"
out = "bindings"
targets = ["c", "python"]
[package]
name = "greeter"
version = "0.1.0"
Generate the header and implement it:
weaveffi generate --target c # writes bindings/c/greeter.h
The API’s own functions come first. GREETER_DEFINE_CONTRACT defines every
contract function with the hashes the header was generated with, and a
synchronous function stores a cleared error in out_err on success:
/* One contract function per declaration, as the header computed them. */
GREETER_DEFINE_CONTRACT
int32_t greeter_add(int32_t a, int32_t b, greeter_error* out_err) {
memset(out_err, 0, sizeof *out_err); /* success: a cleared error */
return (int32_t)((uint32_t)a + (uint32_t)b);
}
greeter_run greeter_greet(greeter_run name, greeter_error* out_err) {
memset(out_err, 0, sizeof *out_err);
static const char hello[] = "Hello, ";
size_t len = sizeof hello - 1 + name.len + 1;
uint8_t* text = greeter_alloc(len); /* the consumer frees it with greeter_run_free */
if (text == NULL) {
static const char oom[] = "out of memory";
greeter_error_set(out_err, -1, (const uint8_t*)oom, sizeof oom - 1);
greeter_run none = {NULL, 0};
return none;
}
memcpy(text, hello, sizeof hello - 1);
if (name.len != 0) memcpy(text + sizeof hello - 1, name.ptr, name.len);
text[len - 1] = '!';
greeter_run out = {text, len};
return out;
}
Every producer also exports the runtime surface: the ABI revision, one
allocator for every run it hands out (8-aligned, released by its own
run_free), the error helpers, cancel tokens, and the leak counter:
/* The runtime surface every producer exports. */
uint32_t greeter_abi_version(void) { return GREETER_ABI_VERSION; }
/* One allocator for every run: returned strings and buffers, error messages
and payloads, and runs a consumer allocates. calloc's alignment is at
least 8 on every supported platform. */
uint8_t* greeter_alloc(size_t len) { return len != 0 ? calloc(len, 1) : NULL; }
void greeter_run_free(greeter_run run) { free((void*)run.ptr); }
static const uint8_t* copy(const uint8_t* ptr, size_t len) {
uint8_t* run = greeter_alloc(len);
if (run != NULL) memcpy(run, ptr, len);
return run;
}
void greeter_error_clear(greeter_error* err) {
if (err == NULL) return;
free((void*)err->message_ptr);
free((void*)err->payload_ptr);
memset(err, 0, sizeof *err);
}
void greeter_error_free(greeter_error* err) {
greeter_error_clear(err);
free(err);
}
void greeter_error_set(greeter_error* err, int32_t code, const uint8_t* message_ptr,
size_t message_len) {
if (err == NULL) return;
greeter_error_clear(err);
err->code = code;
if (message_ptr != NULL && message_len != 0) {
err->message_ptr = copy(message_ptr, message_len);
err->message_len = err->message_ptr != NULL ? message_len : 0;
}
}
void greeter_error_set_payload(greeter_error* err, const uint8_t* ptr, size_t len) {
if (err == NULL) return;
free((void*)err->payload_ptr);
err->payload_ptr = ptr != NULL && len != 0 ? copy(ptr, len) : NULL;
err->payload_len = err->payload_ptr != NULL ? len : 0;
}
/* Cancel tokens (this API has no async functions, but every library exports
the same runtime surface). */
struct greeter_cancel_token {
atomic_int refs;
atomic_bool cancelled;
};
greeter_cancel_token* greeter_cancel_token_create(void) {
greeter_cancel_token* token = malloc(sizeof *token);
if (token != NULL) {
atomic_init(&token->refs, 1);
atomic_init(&token->cancelled, false);
}
return token;
}
void greeter_cancel_token_cancel(greeter_cancel_token* token) {
if (token != NULL) atomic_store(&token->cancelled, true);
}
bool greeter_cancel_token_is_cancelled(const greeter_cancel_token* token) {
return token != NULL && atomic_load(&((greeter_cancel_token*)token)->cancelled);
}
void greeter_cancel_token_destroy(greeter_cancel_token* token) {
if (token != NULL && atomic_fetch_sub(&token->refs, 1) == 1) free(token);
}
/* Leak counters: kind -1 is 0 because this producer doesn't count. */
uint64_t greeter_debug_live(int32_t kind) {
(void)kind;
return 0;
}
The C ABI contract lists
what a hand-written producer owes its consumers, including honoring a
vtable’s GREETER_VTABLE_THREAD_AFFINE flag once the API has callbacks.
Build it as libgreeter.so (libgreeter.dylib on macOS, greeter.dll on
Windows). The file defines GREETER_BUILD before it includes the header, so
the header’s GREETER_API exports the symbols on Windows too:
cc -shared -fPIC -I bindings/c greeter.c -o libgreeter.so
Then run weaveffi generate for the other targets; they load it exactly as
they load a Rust producer. From Python, for example:
weaveffi generate --target python
pip install ./bindings/python
GREETER_LIBRARY=$PWD/libgreeter.so python3 -c "import greeter; print(greeter.add(2, 3))" # 5
Next steps
- Project Configuration:
[package]metadata,[build]settings, per-target options, and how regeneration cleans up stale files. - Packaging: building every platform and publishing the artifacts.
- Samples and Examples: the tested example crates, and three
complete producers from the minimal
calculatorto the feature-completekvstore. - Generators: what each language gets.
- Gate CI on
weaveffi generate --checkso committed bindings can’t drift; see Stability and Versioning.
The Rust Producer Macros
A Rust producer is an ordinary library crate. You tag the items you want to
export with WeaveFFI’s attributes, wherever they are in the crate, and call
weaveffi::export_runtime!() once at the crate root. Each attribute emits
its item’s extern "C" functions, marshalling every value through the
audited runtime inside the weaveffi crate, so the crate contains no
unsafe glue. Each also embeds a description of its item in the compiled
library, and the CLI reads the API from there (weaveffi generate builds the
crate first), so the generated bindings describe exactly what the library
was compiled with.
Every example on this page is a region of
examples/macro-tour,
a small address book whose tests call the generated C functions the way a
consumer does.
Setup
[dependencies]
weaveffi = "0.25"
The crate needs no crate-type: the CLI builds the C dynamic library itself
with cargo rustc --lib --crate-type cdylib, and weaveffi build adds the
staticlib an Apple build needs. Add crate-type = ["cdylib", "rlib"] only
if you also want a plain cargo build to produce the dynamic library.
The prefix is the crate name. Every C symbol starts with the crate’s
library name ([lib] name, else the package name with - mapped to _),
which the attributes read from CARGO_CRATE_NAME as they expand. The CLI
derives the same prefix from cargo metadata, and it isn’t configurable:
setting [package] c_prefix or library in weaveffi.toml for a Rust
producer is an error. The macro-tour crate exports macro_tour_add,
macro_tour_Book_new, macro_tour_error_clear, and so on, and builds
libmacro_tour.so.
export_runtime!() exactly once, at the crate root:
weaveffi::export_runtime!();
It takes no arguments and exports the
runtime surface under the crate’s
prefix (abi_version, the error helpers, alloc, run_free, the cancel
token functions, and debug_live). It also defines the crate’s hidden tag
type, crate::__weaveffi::Tag, which every attribute’s expansion names, so
a crate that forgets the call fails to compile at its first exported item
with an unresolved crate::__weaveffi.
A library is one namespace. Rust modules organize the source; they
don’t scope exported names. A declaration in any module or file joins the
library’s one namespace, so every exported record, enum, error domain,
interface, callback interface, and free function needs a name unique across
the crate. Two items with the same name export the same contract and
metadata symbols, so the build fails with a symbol ... is already defined
error on the second one.
Each declaration carries its contract and its description. An
attribute exports one contract function per declaration
({prefix}_contract_{id}, returning the hash of its canonical signature;
see the contract) and one metadata frame
(see Library Mode). Both are computed
from the same resolved types the CLI uses for the bindings, so a library and
the bindings generated from it always agree.
The attributes
| Attribute | On | Effect |
|---|---|---|
#[weaveffi::export] | a fn or async fn; an inherent impl block of an interface | Exports a free function, or every pub fn of the block as a constructor, method, or static. |
#[weaveffi::record] | a struct with named fields | A record, crossing by value in a value buffer. |
#[weaveffi::enumeration] | an enum | A C-style enum (unit variants, crossing as an int32_t) or a rich enum (variants with named fields, crossing in a value buffer). |
#[weaveffi::error] | an enum with explicit positive discriminants | An error domain. Generates Display and std::error::Error unless written #[weaveffi::error(no_display)]. |
#[weaveffi::interface] | a struct | A reference-counted object type, which must be Send + Sync. Export its methods with #[weaveffi::export] on its impl blocks. |
#[weaveffi::callback_interface] | a Send + Sync trait | A method set the consumer implements, accepted as Arc<dyn Trait> or Option<Arc<dyn Trait>>. |
#[weaveffi::custom(repr = R, lift = f, lower = g)] | a type alias or a struct | A type that crosses the ABI as R. |
weaveffi::export_runtime!() | the crate root, once | The runtime symbols and the crate’s tag type. |
Two helper attributes refine an item: #[weaveffi(skip)] leaves a pub fn
of an exported impl block out of the bindings, and
#[weaveffi(message = "...")] sets an error code’s message template. Doc
comments flow into the IDL and every binding, and
#[deprecated(note = "...")] becomes the IDL’s deprecated: text and each
language’s deprecation marker.
Only tagged items are exported; private helpers, use items, and state are
left alone. Each attribute expands on its own, and every value is marshalled
through its type’s traits, so a type is resolved by rustc wherever it’s
declared: in another module, behind a type alias, or (for a custom type) in
another crate.
Types
| Rust | IDL | Crosses the ABI as |
|---|---|---|
i8..i64, u8..u64, f32, f64, bool | same | the scalar; a bool is a C bool, checked to be 0 or 1 |
usize, isize | u64, i64 | the scalar, range-checked on the way in (out of range is -3) |
#[weaveffi::enumeration] C-style enum | the enum | int32_t, checked to be a declared value |
Option<T> of any of those | T? | a {p}_opt_{prim} struct (an optional enum is a {p}_opt_i32) |
String, &str | string | a {p}_run of UTF-8 |
char | string | a run holding exactly one Unicode scalar value (anything else is -3) |
Vec<u8>, &[u8] | bytes | a run of raw bytes |
Vec<T> or &[T] of i8, i16, i32, i64, u16, u32, u64, f32, f64 | [T] | a typed array: a run of packed elements |
#[weaveffi::record] struct, rich enum | the type | a run holding a value buffer |
every other Option<T>, Vec<T>, &[T], and HashMap<K, V> or BTreeMap<K, V> | T?, [T], {K:V} | a run holding a value buffer |
&T, Arc<T>, Option<&T>, Option<Arc<T>> of an interface T; Self or T as a return | T, T? | an object pointer |
Arc<dyn Trait>, Option<Arc<dyn Trait>> of a callback interface | Trait, Trait? | a {p}_{Trait} {ctx, vtable} struct (parameters only) |
weaveffi::Iter<T> | iter<T> | an iterator pointer (returns only) |
a #[weaveffi::custom] type | its repr | as its repr |
weaveffi::CancelToken | none: it makes the function cancellable | the launcher’s cancel-token slot |
How a type crosses never changes its IDL spelling or its surface type in a
binding (i64? is an optional integer and [f64] a list of doubles in every
language); only the transport differs, and inside a value buffer every type
uses the buffer encoding. A reference (&str, &[u8], &[f64],
&Contact, &Book) is a calling convention, not an IDL distinction: the
generated function lends the lifted argument for the call, and a &[T] of a
typed-array element reads the caller’s array in place. Objects compose with
every buffered shape, so Vec<Arc<T>>, Option<Arc<T>>, an Arc<T> record
field, and weaveffi::Iter<Arc<T>> all work.
A parameter that fails these checks fails the call with -3 and a message
of the form {param}: {message}, where a rejected value is quoted (value: "ab" is not a valid char, mode: 7 is not a valid Mode).
A type without a WeaveFFI crossing (u128, a raw pointer, a Box<T>, a
struct without an attribute) fails to compile, with a trait error naming the
type or, for the shapes the attributes recognize, a message saying what to
use instead. For integers wider than 64 bits, declare a custom type with a
String repr.
Functions
/// Add two integers, wrapping on overflow.
#[weaveffi::export]
pub fn add(a: i32, b: i32) -> i32 {
a.wrapping_add(b)
}
/// The number of words in `text`.
#[weaveffi::export]
pub fn word_count(text: &str) -> usize {
text.split_whitespace().count()
}
/// The arithmetic mean of `values`, or none for an empty list.
#[weaveffi::export]
pub fn mean(values: &[f64]) -> Option<f64> {
if values.is_empty() {
return None;
}
Some(values.iter().sum::<f64>() / values.len() as f64)
}
A function’s parameters are plain names whose types are values (T),
borrows (&str, &[f64], &Contact, &Book, Option<&T>), or callback
interfaces. It returns nothing, a value, a weaveffi::Iter<T>, or a
Result of one. These export macro_tour_add, macro_tour_word_count, and
macro_tour_mean:
int32_t macro_tour_add(int32_t a, int32_t b, macro_tour_error* out_err);
uint64_t macro_tour_word_count(macro_tour_run text, macro_tour_error* out_err);
macro_tour_opt_f64 macro_tour_mean(macro_tour_run values, macro_tour_error* out_err);
An exported function can’t be generic, and a parameter named self, ctx,
out_err, callback, context, or cancel_token collides with a slot the
C ABI adds (SlotCollision).
Errors
A Result<T, E> return makes the callable fallible with return type T
(Result<(), E> returns nothing), and E decides what it throws.
Error domains
/// The address book's error domain. Each variant's value is its stable
/// code, and its fields travel with the error as its payload.
#[weaveffi::error]
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(i32)]
pub enum BookError {
/// contact not found
#[weaveffi(message = "no contact with id {id}")]
NotFound {
/// The id that was looked up.
id: u64,
} = 1,
/// the book is full
#[weaveffi(message = "the book is full ({capacity} contacts)")]
Full {
/// The book's capacity.
capacity: u32,
} = 2,
/// a contact needs a name
EmptyName = 3,
/// a listener rejected the contact
#[weaveffi(message = "a listener rejected {name}")]
Rejected {
/// The rejected contact's name.
name: String,
} = 4,
/// a listener failed
#[weaveffi(message = "{message}")]
ListenerFailed {
/// The listener's message.
message: String,
} = 5,
}
/// Any listener failure that isn't a `BookError` code arrives as a
/// `ForeignError`; this keeps it typed for the original caller.
impl From<ForeignError> for BookError {
fn from(e: ForeignError) -> Self {
Self::ListenerFailed { message: e.message }
}
}
When E is a #[weaveffi::error] enum, the callable is throws: E in the
IDL, and every binding raises a typed error for each code, with the code’s
fields as properties. Book::add below returns Result<Contact, BookError>.
- Codes. Each variant’s discriminant is its stable code: explicit,
positive, and unique within the domain. A variant may carry named fields,
which travel as the error’s payload (a value buffer
of the fields); Rust then requires the enum to be
#[repr(i32)]. A field can’t reach an interface, directly or through a record or rich enum; the CLI’s validator reports it asObjectInErrorPayload. - Messages. The macro generates
Displayandstd::error::Error, so the enum must implementDebug. A variant’s message is its#[weaveffi(message = "...")]template, which may interpolate the variant’s fields by name ({id}, or{id:?}forDebug), else the first line of its doc comment, else the variant name.BookError::NotFound { id: 99 }.to_string()isno contact with id 99, the message every binding’s error carries. To writeDisplayyourself (with thiserror, say), write#[weaveffi::error(no_display)]; the enum must then implementDisplay, and the macro generates neither impl. - Names. Code values only need to be unique within their domain (two
domains may both use
1), but code names must be unique across the whole library (DuplicateErrorCodeName), because several targets flatten them into one namespace. - Open domains. Adding a code later never breaks a deployed binding, which reports an unknown code as the domain’s base error with its code and message.
Untyped errors
/// Parse a decimal integer. Any `std::error::Error` converts into
/// `weaveffi::Error` with `?`, so this function throws an untyped error
/// carrying the parse error's message.
#[weaveffi::export]
pub fn parse_number(text: &str) -> Result<i64, weaveffi::Error> {
Ok(text.trim().parse()?)
}
/// The square root of `x`. A `String` error is untyped too.
#[weaveffi::export]
pub fn checked_sqrt(x: f64) -> Result<f64, String> {
if x < 0.0 {
return Err(format!("cannot take the square root of {x}"));
}
Ok(x.sqrt())
}
When E is an untyped error, the callable is throws: any: a failure
reports the runtime code -1 with E’s Display text as the message, and
bindings raise the library’s base error. The untyped errors are
weaveffi::Error, String, &'static str, std::io::Error,
Box<dyn std::error::Error> (with or without + Send + Sync),
weaveffi::ForeignError, and, with the weaveffi crate’s anyhow feature,
anyhow::Error. Every std::error::Error converts into weaveffi::Error
with ?, which is the easy way to return any other error type.
A function that returns a plain T can’t fail. A panic in producer code is
caught at the boundary and reported as code -2, which bindings treat as a
bug (see Errors and Memory).
Records and enums
/// How a contact is filed: a C-style enum, which crosses as an `int32_t`.
#[weaveffi::enumeration]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Kind {
/// Friends and family.
Personal,
/// Colleagues.
Work = 10,
/// Everyone else (`11`, one more than the previous variant).
Other,
}
/// One contact: a record, which crosses by value.
#[weaveffi::record]
#[derive(Clone, Debug, PartialEq)]
pub struct Contact {
/// The book-assigned id.
pub id: u64,
/// The display name.
pub name: String,
/// An email address, if known.
pub email: Option<String>,
/// How the contact is filed.
pub kind: Kind,
/// Free-form labels.
pub tags: Vec<String>,
}
/// A change to a book: a rich enum, whose variants carry fields.
#[weaveffi::enumeration]
#[derive(Clone, Debug, PartialEq)]
pub enum Change {
/// A contact was added.
Added {
/// The new contact.
contact: Contact,
},
/// A contact was removed.
Removed {
/// The removed contact's id.
id: u64,
},
/// Every contact was removed.
Cleared,
}
A record or rich enum crosses as a value buffer; a C-style enum crosses as
its int32_t discriminant, which the producer checks against the declared
values (any other is a marshalling failure, -3). None of them exports a C
function. A variant’s discriminant is its = value, an integer literal that
fits in an i32, or one more than the previous variant’s (Kind::Other is
11); a rich enum’s discriminants are the tags in its buffer encoding. A
rich enum’s variants use named fields or none (tuple variants are
rejected). A field may be any value type, including usize, char, a
custom type, and an object. A record or rich enum may contain itself (or a
type that contains it) through a Vec or map, as in children: Vec<Node>. Records, enums, error domains, interfaces, and callback
interfaces can’t be generic.
Custom types
A custom type crosses the ABI as another type, its repr, and converts at
the boundary with two functions you name. Declare it on a type alias (which
may name a foreign type, such as std::time::Duration or uuid::Uuid) or
on a struct:
/// A timeout: a `std::time::Duration`, crossing as whole milliseconds. The
/// bindings see a `u64`.
#[weaveffi::custom(repr = u64, lift = timeout_from_millis, lower = timeout_to_millis)]
pub type Timeout = Duration;
fn timeout_from_millis(ms: u64) -> Result<Duration, std::convert::Infallible> {
Ok(Duration::from_millis(ms))
}
fn timeout_to_millis(timeout: &Duration) -> u64 {
u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX)
}
/// An email address, crossing as its string. `lift` rejects a string
/// without an `@`, which fails the call as a marshalling error.
#[weaveffi::custom(repr = String, lift = Email::parse, lower = Email::to_text)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Email(String);
impl Email {
fn parse(text: String) -> Result<Email, String> {
if text.contains('@') {
Ok(Email(text))
} else {
Err(format!("{text:?} is not an email address"))
}
}
fn to_text(&self) -> String {
self.0.clone()
}
}
/// The domain of an email address (what follows the `@`).
#[weaveffi::export]
pub fn email_domain(email: Email) -> String {
email.0.rsplit('@').next().unwrap_or_default().to_string()
}
repris a type that crosses on its own (String, an integer,Vec<u8>, a record, …). The IDL, the contract, and every binding see the repr, soemail_domainisemail_domain(email: string) -> stringand aTimeoutparameter is au64.lift: fn(R) -> Result<T, E>withE: Displayruns on the way in. A failure fails the call with the marshalling code-3andE’s message, prefixed with the parameter’s name (email: "ada" is not an email address).lower: fn(&T) -> Rruns on the way out.
A custom type works in every position: parameters, returns, async results,
iterator items, callback parameters and returns, record, rich-enum, and
error-payload fields, and nested in Option, Vec, and maps. Bindings
expose the repr; mapping it to a language’s own type is up to the consumer.
Interfaces
An interface is shared across the boundary (by consumer wrappers, records,
collections, and in-flight async calls), so the type must be Send + Sync
and keeps mutable state behind interior mutability. Export its members with
#[weaveffi::export] on an inherent impl block (not a trait impl, and
not a generic one):
/// An address book: an interface, a reference-counted object the bindings
/// wrap in a class.
#[weaveffi::interface]
pub struct Book {
capacity: u32,
next_id: AtomicU64,
contacts: Mutex<BTreeMap<u64, Contact>>,
listeners: Mutex<Vec<Arc<dyn Listener>>>,
}
#[weaveffi::export]
impl Book {
/// An empty book holding up to `capacity` contacts (a constructor: it
/// returns `Self`).
pub fn new(capacity: u32) -> Self {
Self {
capacity,
next_id: AtomicU64::new(1),
contacts: Mutex::new(BTreeMap::new()),
listeners: Mutex::new(Vec::new()),
}
}
/// The capacity of a book made by `new_default` (a static: no receiver,
/// and it doesn't return the interface).
pub fn default_capacity() -> u32 {
100
}
/// An empty book with the default capacity.
pub fn new_default() -> Self {
Self::new(Self::default_capacity())
}
/// Add a contact, returning it with its new id. Fails with `EmptyName`,
/// `Full`, or `Rejected`, or with a listener's own error.
pub fn add(
&self,
name: String,
email: Option<Email>,
kind: Kind,
) -> Result<Contact, BookError> {
if name.trim().is_empty() {
return Err(BookError::EmptyName);
}
let contact = Contact {
id: self.next_id.fetch_add(1, Ordering::Relaxed),
name,
email: email.map(|e| e.0),
kind,
tags: Vec::new(),
};
// Never hold a lock while a consumer's callback runs: it may call
// back into the book.
for listener in self.listeners() {
if !listener.approve(&contact)? {
return Err(BookError::Rejected { name: contact.name });
}
}
{
let mut contacts = lock(&self.contacts);
if contacts.len() >= self.capacity as usize {
return Err(BookError::Full {
capacity: self.capacity,
});
}
contacts.insert(contact.id, contact.clone());
}
self.notify(&Change::Added {
contact: contact.clone(),
});
Ok(contact)
}
/// The contact with `id`. Fails with `NotFound`.
pub fn get(&self, id: u64) -> Result<Contact, BookError> {
lock(&self.contacts)
.get(&id)
.cloned()
.ok_or(BookError::NotFound { id })
}
/// Remove the contact with `id`, returning whether it existed.
pub fn remove(&self, id: u64) -> bool {
let removed = lock(&self.contacts).remove(&id).is_some();
if removed {
self.notify(&Change::Removed { id });
}
removed
}
/// The number of contacts.
pub fn count(&self) -> usize {
lock(&self.contacts).len()
}
/// The number of contacts.
#[deprecated(note = "use `count`")]
pub fn size(&self) -> u32 {
u32::try_from(self.count()).unwrap_or(u32::MAX)
}
/// Another reference to this same book (a method taking
/// `self: Arc<Self>`).
pub fn share(self: Arc<Self>) -> Arc<Book> {
self
}
/// Lock the contacts for Rust callers. Its return type can't cross the
/// boundary, so `skip` leaves it out of the bindings.
#[weaveffi(skip)]
pub fn contacts_mut(&self) -> MutexGuard<'_, BTreeMap<u64, Contact>> {
lock(&self.contacts)
}
/// Remove every contact (exported only when the crate is built with
/// its `admin` feature).
#[cfg(feature = "admin")]
pub fn purge(&self) -> u32 {
let removed = std::mem::take(&mut *lock(&self.contacts));
self.notify(&Change::Cleared);
u32::try_from(removed.len()).unwrap_or(u32::MAX)
}
}
Each pub fn of the block is classified by its signature:
- a method takes
&selforself: Arc<Self>(&mut selfandselfby value are rejected: objects are shared); - a constructor has no receiver, isn’t
async, and returns the interface:Self,Arc<Self>, or the type by name, optionally in aResult; - a static has no receiver and returns anything else, or is an
async fn.
Constructors are synchronous, so an async fn without a receiver that
returns the interface (Self, Arc<Self>, or the type by name, optionally
in a Result) is an async static factory. A free async fn returning the
object works too (the kvstore sample’s open_store).
An object parameter &T is borrowed for the call; Arc<T> (or
Option<Arc<T>>) is a new strong reference taken for you, so you may store
it. A by-value T parameter doesn’t compile. An object you return transfers
one strong reference to the consumer. A private fn, or a pub fn marked
#[weaveffi(skip)], isn’t exported, so a public helper whose signature
can’t cross the ABI (a guard, a closure, a borrowed iterator) stays usable
from Rust. An interface may have several exported impl blocks; the
sections below add Book’s iterator, callback, and async members that way.
The attribute also exports {prefix}_{Type}_clone and _destroy, which add
and release a reference. Every binding wraps the reference in a class that
releases it exactly once:
typedef struct macro_tour_Book macro_tour_Book;
macro_tour_Book* macro_tour_Book_new(uint32_t capacity, macro_tour_error* out_err);
macro_tour_run macro_tour_Book_add(const macro_tour_Book* self, macro_tour_run name,
macro_tour_run email, macro_tour_Kind kind,
macro_tour_error* out_err);
macro_tour_Book* macro_tour_Book_clone(const macro_tour_Book* self);
void macro_tour_Book_destroy(macro_tour_Book* self);
Iterators
Return weaveffi::Iter<T> (built with Iter::new from anything
IntoIterator whose iterator is Send + 'static) when the consumer should
pull elements lazily instead of receiving a materialized list:
#[weaveffi::export]
impl Book {
/// Every contact's name in id order, pulled lazily from a snapshot.
pub fn names(&self) -> weaveffi::Iter<String> {
let names: Vec<String> = lock(&self.contacts)
.values()
.map(|c| c.name.clone())
.collect();
weaveffi::Iter::new(names)
}
}
It may be wrapped in a Result, and T may be any value type, including an
object, an optional scalar, or a typed array (weaveffi::Iter<Option<i64>>,
weaveffi::Iter<Vec<i32>>). Iterators are returns of synchronous callables
only: an Iter parameter, a nested Iter, and an async function returning
one are rejected. Each binding pulls one element per step of its own
iteration idiom and releases the iterator exactly once.
Callback interfaces
A callback interface is the inverse of an interface: the consumer implements
it and the producer calls it, from any thread, for as long as it holds the
Arc. When the last clone drops, the consumer’s release hook runs exactly
once (on whichever thread drops it).
/// Approves the contacts a book adds and hears about its changes. The
/// consumer implements it; the book calls it, from any thread.
#[weaveffi::callback_interface]
pub trait Listener: Send + Sync {
/// Whether `contact` may be added. A consumer may also fail with one of
/// `BookError`'s codes, which `add` then fails with.
fn approve(&self, contact: &Contact) -> Result<bool, BookError>;
/// A change the book made.
fn on_change(&self, change: &Change) -> Result<(), ForeignError>;
}
Accept one as Arc<dyn Trait>, or Option<Arc<dyn Trait>> when the
consumer may pass none:
#[weaveffi::export]
impl Book {
/// Subscribe `listener` until the book is released.
pub fn subscribe(&self, listener: Arc<dyn Listener>) {
lock(&self.listeners).push(listener);
}
}
The rules:
- The trait is
Send + Syncand not generic, and has at least one method. The receiver is&self, and methods are synchronous. - Parameters may be any value type, borrowed (
&str,&Contact) or owned. Strings, bytes, typed arrays, and buffered values are lent to the consumer for the call; an object parameter moves one strong reference to the consumer, so it’s spelledArc<T>(orOption<Arc<T>>).&mutparameters are rejected. - Every method returns
Result<T, E>, because the consumer’s implementation can fail, andEmust implementFrom<weaveffi::ForeignError>.Tis()or any value type, including an object (Arc<T>, orOption<Arc<T>>when the consumer may return none). A plainTis a compile error. The consumer allocates a returned run with{prefix}_alloc, and the runtime adopts it for you. - A callback interface is valid only as a parameter of a function or an interface member, never in a return, a record, a collection, or another callback.
The error type decides what the method throws. When E is a
#[weaveffi::error] domain, the method is throws: E (approve above): the
consumer may fail with one of E’s codes, fields included, and it arrives
as that typed variant, its message rendered by your Display from the
fields. Any other consumer failure (an untyped exception, a code E
doesn’t declare) reaches E through From<ForeignError>. When E is
anything else (ForeignError itself, as in on_change), the method is
throws: any, and every consumer failure goes through
From<ForeignError>.
BookError maps foreign failures into its own ListenerFailed code, so
Book::add uses ? on a listener’s typed Rejected and on any other
listener failure alike, and the original caller sees a typed BookError
either way.
ForeignError is what the runtime hands to From: a code (-4 when
the consumer’s implementation failed or, for a
thread-affine vtable, was
called off its thread; -3 when it returned a value the runtime couldn’t
accept) and the consumer’s message. It implements Display, so it’s a
valid error type for an exported function too (which is then throws: any).
Don’t hold a lock across a callback call: the consumer’s implementation may
call back into your library and wait on the same lock. Snapshot the state
you need, release the lock, then call out, as Book::add does.
Async functions and cancellation
An async fn (a free function, method, or static) lowers to a launcher that
returns immediately and a completion callback that fires exactly once. A
trailing weaveffi::CancelToken parameter makes it cancellable:
#[weaveffi::export]
impl Book {
/// Every contact, in id order, collected on a producer thread.
pub async fn export_all(&self) -> Vec<Contact> {
lock(&self.contacts).values().cloned().collect()
}
}
/// Greet `name` after `delay`. The trailing `CancelToken` makes the
/// function cancellable: cancelling drops the future (and the sleep), and
/// the call completes as cancelled.
#[weaveffi::export]
pub async fn greet_later(name: String, delay: Timeout, _cancel: CancelToken) -> String {
tokio::time::sleep(delay).await;
format!("Hello, {name}!")
}
When the consumer cancels, the runtime drops your future at its next
suspension point and completes the call with code -5; you don’t need to
poll the token. Call cancel.is_cancelled() only for cooperative cleanup,
such as work running on another thread. Only an async fn takes a
CancelToken, as its last parameter. An async function can’t borrow an
optional parameter (take Option<T> by value), can’t return an iterator,
and can’t be a constructor. Async and Cancellation covers the
executors and the C shape.
Conditional compilation and features
A #[cfg] on an exported item (a function, an impl block, a record, enum,
error domain, interface struct, callback trait, or custom type) or on a
member of an exported impl block applies to everything generated for it:
its C functions, its contract functions, and its metadata. An item a build
compiles out has none of them, so the library never claims a declaration it
doesn’t have. Book::purge above exists only in a build with the crate’s
admin feature.
Because weaveffi generate reads the API from the built library, the
bindings follow the build’s #[cfg]. Every command that builds the
producer takes -F/--features, --all-features, and
--no-default-features (or [build] features, all_features, and
no_default_features in weaveffi.toml), and passes them to every build:
the one the API is read from and each platform’s in weaveffi build. So
weaveffi generate -F admin generates bindings with purge, and they load
only a library built with it: against one without it, the contract check
fails with “Book.purge is missing from the library”. A library with extra
declarations loads fine.
Leak checks
The weaveffi crate’s leak-check feature counts live objects, foreign
callbacks, iterators, cancel tokens, and runs (including error messages).
{prefix}_debug_live(kind) reports them (0 objects, 1 callbacks, 2
iterators, 3 tokens, 4 runs), and kind -1 returns 1 to say the
library counts. Without the feature the symbol still exists and returns 0
for every kind. Every sample enables it, and every conformance consumer
asserts that all five counts are zero at exit.
[dependencies]
weaveffi = { version = "0.25", features = ["leak-check"] }
What the macros reject
Each rejection is a compile error on the offending item:
| Source | Why |
|---|---|
a crate without weaveffi::export_runtime!() | every expansion names the crate’s tag type, which the call defines |
a generic function, impl block, or type | each exported item has one C shape |
#[weaveffi::export] on a trait impl, or on anything but a fn or an impl | export an interface’s inherent impl block |
| a parameter that isn’t a plain name (a pattern) | each parameter becomes one named C slot |
&mut T, *const T, *mut T parameters | take &T or a value and return the result; declare a pointee as an interface |
Box<dyn Trait> | callbacks are shared: take Arc<dyn Trait> |
an interface method on self or &mut self | use &self or self: Arc<Self> with interior mutability |
an interface that isn’t Send + Sync | objects are shared across threads; the compiler names the field |
| two exported items with the same name, in any modules | a library is one namespace (the second fails with symbol ... is already defined) |
a CancelToken that isn’t the last parameter of an async fn | cancellation belongs to async calls |
an Iter parameter, an async function returning an Iter | iterators are returns of synchronous callables |
a callback method that’s async, takes &mut parameters, or returns a plain T | return Result<T, E> with E: From<weaveffi::ForeignError> |
| a callback trait without methods, an empty record, an enum without variants | each lowers to something with at least one member |
| tuple fields in a record, variant, or error code | fields need names to appear in the IDL |
| an error variant without an explicit positive discriminant | codes are stable values; 0 and negatives belong to the runtime |
a discriminant that isn’t an integer literal fitting an i32 | it crosses as an int32_t |
#[weaveffi::error(no_display)] on an enum without Display | you opted out of the generated impl |
#[weaveffi::custom] without repr, lift, or lower | all three are required |
| arguments to any other attribute | only error and custom take arguments |
The rest of the IDL’s rules (error code
names unique across domains, map key types, objects in error payloads,
reserved names, and so on) are checked by the CLI’s validator when it reads
the API, which every command does; run weaveffi validate or weaveffi generate --check in CI.
See also
- Samples and Examples:
kvstoreuses every feature on this page. - C ABI Contract: what the generated functions implement.
- Rust API Map: the items the
weavefficrate exports.
Errors and Memory
This guide states who owns every value that crosses the C ABI and how
failures travel back to the caller. The generated bindings follow these rules
for you; they matter when you consume the C header directly, implement it by
hand, or audit a binding. The C ABI contract is the
normative text. Examples use the kvstore and calculator samples, whose
prefixes are kvstore and calculator.
How values cross
Every value crosses as exactly one C value, chosen by its family, in every position: a parameter, a return, an async result, an iterator item, and a callback method’s argument and return.
| Family | IDL types | C value | Into the producer (parameter) | Out of the producer (return, async result, iterator item) | Callback argument | Callback return |
|---|---|---|---|---|---|---|
| Direct | integers, f32, f64, bool, C-style enums | the scalar (an enum is an int32_t) | copied | copied | copied | copied |
| OptDirect | T? of a Direct type | {p}_opt_{prim} ({bool has; T value;}) | copied | copied | copied | copied |
| Run | string, bytes, typed arrays ([i8] … [f64]), and every record, rich enum, other optional, list, and map | {p}_run ({const uint8_t* ptr; size_t len;}) | borrowed for the call | owned by the consumer: release with {p}_run_free | borrowed for the call | allocated by the consumer with {p}_alloc; the producer adopts it |
| Object | interfaces, I? | const {p}_{I}* as a parameter, {p}_{I}* elsewhere | borrowed for the call | one strong reference moves to the consumer: release with {p}_{I}_destroy | one strong reference moves to the consumer | one strong reference (a fresh _clone) moves to the producer |
| Callback | callback interfaces (parameters only) | {p}_{Cb} ({void* ctx; const vtable*}) | the consumer’s; the producer calls free(ctx) once | never returned | never | never |
Borrowed means the callee may read the value only until the call returns and copies anything it keeps. Everything a producer hands back belongs to the receiver, who releases it exactly once. The transfers in the other direction are a callback method’s return value, which the producer adopts, and an object passed to a callback, which the consumer adopts.
Runs
Every string, bytes, typed array, and value buffer is a run: a pointer and a length in bytes, passed by value. The producer owns the allocator for every run it hands out (a return, an async result, an iterator item, an error’s message and payload), and two runtime functions manage runs:
uint8_t* kvstore_alloc(size_t len); /* a zero-filled, 8-aligned run; NULL for 0 */
void kvstore_run_free(kvstore_run run); /* returned runs and alloc runs */
Every run the producer allocates has alignment 8, so a consumer can read a
returned run in place as any element type (a typed array of double, say)
without copying it first.
A consumer releases a returned run with {p}_run_free, passing it back
exactly as it got it. It allocates a run with {p}_alloc(len) only when it
hands bytes to the producer: a callback method’s string, bytes, typed
array, or buffer return, which the producer adopts and frees, or (on
wasm32) an argument staged in the module’s linear memory. Null with length
0 is the empty run everywhere: {p}_alloc(0) returns null, and freeing
the empty run is a no-op; a null pointer with a non-zero length is
malformed. Never free a run with the language’s own allocator, and never
hand the producer memory that didn’t come from {p}_alloc where it adopts
it. An error’s message and payload are released with the error
({p}_error_clear or {p}_error_free), never with {p}_run_free.
Strings, bytes, and typed arrays
A string is UTF-8 and never NUL-terminated, so an interior NUL survives the
trip. A string that isn’t valid UTF-8, or a run with a null pointer and a
non-zero length, fails the call with the marshalling code -3.
/* The calculator sample's `greet(name: string) -> string`. */
calculator_error err;
calculator_run name = {(const uint8_t*)"Ada", 3};
calculator_run text = calculator_greet(name, &err);
if (err.code == 0) {
printf("%.*s\n", (int)text.len, (const char*)text.ptr);
calculator_run_free(text);
}
A list of i8, i16, i32, i64, u16, u32, u64, f32, or f64 is
a typed array: a run of the packed native elements. Its len still
counts bytes (a multiple of the element size), and its pointer must be
aligned for the element; a ragged or misaligned array fails with -3.
[u8] is bytes, and [bool] is a value buffer, because its bytes must
be checked.
/* calculator's `running_total(values: [i32]) -> [i32]`. */
const int32_t xs[] = {1, 2, 3};
calculator_run in = {(const uint8_t*)xs, sizeof xs};
calculator_run out = calculator_running_total(in, &err);
const int32_t* totals = (const int32_t*)out.ptr; /* {1, 3, 6}: out.len / 4 elements */
calculator_run_free(out);
Optional scalars
An optional integer, float, bool, or C-style enum (i64?, Kind?) is a
{p}_opt_{prim} struct, {bool has; T value;}, passed and returned by
value; an optional enum is a {p}_opt_i32. value is 0 when has is
false, and a present value is still range-checked, so an undeclared enum
value fails with -3. Nothing is allocated, so nothing is freed.
/* kvstore's `Store.expires_at(key: string) -> i64?`. */
kvstore_opt_i64 at = kvstore_Store_expires_at(store, key, &err);
if (err.code != 0) {
kvstore_error_clear(&err); /* failed */
} else if (at.has) {
printf("expires at %lld\n", (long long)at.value);
} /* else: no expiry */
Value buffers
Records, rich enums, the remaining optionals (all but Interface?), lists,
and maps cross as one serialized value buffer
in a run, however deep the nesting. A parameter is a run the caller encodes
and frees itself. A return is one producer allocation the consumer decodes
and then releases once with {p}_run_free; the strings and records it
decodes are copies, so nothing inside is freed separately. The exception is
an object token inside a buffer, which carries one strong reference the
reader adopts. Inside a buffer, optional scalars and numeric lists use the
buffer encoding like every other type.
Objects
Interface objects are reference counted by the producer (an Arc<T> in a
Rust producer). Each interface has two lifecycle functions:
kvstore_Store* kvstore_Store_clone(const kvstore_Store* self); /* +1 */
void kvstore_Store_destroy(kvstore_Store* self); /* -1 */
A pointer is a strong reference. _clone returns another reference to the
same object (the pointer value is unchanged), _destroy releases one, and
the object is dropped when the last reference goes. Both accept null as a
no-op.
| Position | Rule |
|---|---|
parameter (Store, Store?) | borrowed for the call; the producer takes its own reference if it keeps the object |
| return, async result, iterator element | one strong reference moves to the consumer |
| callback method argument | one strong reference moves to the consumer |
| callback method return | one strong reference moves to the producer |
| token inside a value buffer (either direction) | carries one strong reference; the reader adopts it |
Two consequences follow. A consumer that encodes an object into a buffer
must call _clone and write the new pointer, never the one its wrapper
holds. And a buffer that contains objects is decoded exactly once, because
each token is one reference.
Every generated wrapper owns exactly one reference and releases it through
the language’s disposal idiom (close(), Dispose(), deinit, a C++
destructor, Close()), with a finalizer or cleaner backstop where the
runtime has one. Each binding also keeps the wrapper alive for the duration
of every native call, so a wrapper that becomes unreachable mid-call can’t
free the object under it. An in-flight async call holds its own reference.
Callback interfaces
A callback-interface parameter is one {p}_{Cb} struct passed by value:
{void* ctx; const {p}_{Cb}_vtable* vtable;}. The consumer owns ctx (a
generated binding uses a key into a table that keeps the implementation
alive) and a static vtable per interface, whose header records its size,
its flags, and its free hook, followed by one entry per method in
declaration order. A null vtable is none (Cb?). From the
macro tour:
typedef struct macro_tour_Listener { void* ctx; const macro_tour_Listener_vtable* vtable; } macro_tour_Listener;
struct macro_tour_Listener_vtable {
uint32_t size; /* sizeof the vtable, as the consumer compiled it */
uint32_t flags; /* 0, or MACRO_TOUR_VTABLE_THREAD_AFFINE */
void (*free)(void* ctx);
bool (*approve)(void* ctx, macro_tour_run contact, macro_tour_error* out_err);
void (*on_change)(void* ctx, macro_tour_run change, macro_tour_error* out_err);
};
The producer may call any entry, any number of times, from any thread
(subject to thread affinity), until it calls
free(ctx) exactly once; free may also run on any producer thread.
Vtables are open. A consumer generated before a method was appended
passes a shorter vtable, and the producer accepts it: calling a method past
the consumer’s size, or one whose entry is null, fails with -4 and a
message naming the method, without calling anything. A vtable shorter than
its header fails the call that passed it with -3.
Arguments to a callback method are lent for the call: runs must be
copied or decoded before returning, and objects move one reference to the
consumer. Returns move to the producer: a run the consumer returns is
one it allocated with {p}_alloc(len), which the producer adopts and frees,
and an object is a fresh _clone. The producer adopts whatever the method
returned even when it failed, so a consumer that fails after allocating
doesn’t leak. A return the producer can’t accept (text that isn’t UTF-8, a
null I, an out-of-range enum value, a malformed buffer, a misaligned
array) fails the method with -3.
Thread-affine callbacks
Some runtimes can only run a value-returning callback on one thread: a Dart
callback that returns a value must run on its isolate’s thread. Such a
binding sets bit 0 of the vtable’s flags, {P}_VTABLE_THREAD_AFFINE. The
producer then records the thread that passed it the vtable, and a method
that returns a value, called from any other thread, fails with -4 and the
message callback called off its thread without reaching the consumer.
void methods and free may still run on any thread, and the binding
forwards them to its own thread. In a Rust producer the failure arrives as a
ForeignError converted into the method’s error type, like any other
callback failure. Only the Dart target sets the flag; every other target
passes 0.
Iterators
An iter<T> return is an opaque {p}_..._Iterator*. _next(iter, &item, &err) writes one element and returns 1, or returns 0 at the end; each
element is owned by the consumer under the return rules above. _next
checks that out_item is non-null before it pulls an element, so a bad call
never loses one. _destroy is called exactly once, on exhaustion or when the
consumer abandons the iteration early. The generated wrappers do both. An
iterator is advanced by one caller at a time: a _next that arrives while
another is in progress on the same iterator (from another thread, or
re-entrantly from a callback the producer’s next calls) fails with -3
rather than blocking.
/* kvstore's `Store.keys(prefix: string?) -> iter<string>`. */
kvstore_Store_KeysIterator* keys = kvstore_Store_keys(store, no_prefix, &err);
kvstore_run key;
while (kvstore_Store_KeysIterator_next(keys, &key, &err) == 1) {
printf("%.*s\n", (int)key.len, (const char*)key.ptr);
kvstore_run_free(key);
}
kvstore_Store_KeysIterator_destroy(keys);
Errors
The error struct
Every synchronous function, interface member, iterator launcher, and
iterator _next takes a trailing {p}_error* out_err:
typedef struct kvstore_error {
int32_t code; /* 0 success, >0 domain code, <0 runtime code */
const uint8_t* message_ptr; /* UTF-8, NOT NUL-terminated, producer-owned */
size_t message_len;
const uint8_t* payload_ptr; /* the code's fields as a value buffer, or NULL */
size_t payload_len;
} kvstore_error;
The call overwrites the slot without reading it: on success it stores a
cleared error, and on failure it stores the code, message, and payload and
returns a zero value (0, false, NULL, the empty run, an absent
optional) that must not be used or freed. So the caller may pass
uninitialized memory, and after reading a failure it releases the message
and payload with {p}_error_clear(&err). A struct reused for many calls must
be cleared after each failure, or the message leaks.
The message is message_len bytes of UTF-8 at message_ptr, with no NUL
terminator, so print it with a length (%.*s) or copy it. An empty message
is a null message_ptr with length 0, even when code is non-zero.
kvstore_error err;
uint64_t n = kvstore_Store_count(store, &err);
if (err.code != 0) {
fprintf(stderr, "count failed (%d): %.*s\n",
err.code, (int)err.message_len, (const char*)err.message_ptr);
kvstore_error_clear(&err);
}
An async completion receives a heap-boxed error instead (or NULL on
success), released with {p}_error_free, which also frees the box.
_clone, _destroy, an iterator’s _destroy, and async launchers take no
out_err.
Codes
| Code | Meaning |
|---|---|
0 | success |
> 0 | a code of the error domain the callable throws |
-1 | untyped: the failure of a throws: any callable, or an async call the executor couldn’t start |
-2 | the producer panicked; the message carries the panic text |
-3 | marshalling failure: a null run with a non-zero length, a null self or object where one is required, invalid UTF-8, a bool byte other than 0 or 1, an out-of-range enum value or integer conversion (a usize that doesn’t fit, a char that isn’t one scalar), a ragged or misaligned typed array, a custom type’s lift rejecting its input, a malformed value buffer (including a map with a repeated key), an incomplete vtable header, an iterator advanced concurrently |
-4 | a consumer’s callback-interface implementation failed, doesn’t implement the method called, or was called off its thread; the message is the consumer’s or names the method |
-5 | cancelled: an async call’s cancel token fired, or its executor dropped it (async completions only) |
Domain codes are positive, so the two ranges never collide. Code values are
unique only within a domain (the calculator sample’s
CalcError.DivisionByZero and ParseError.NotANumber are both 1), so a
binding interprets a positive code by the domain of the callable that
reported it. The C header declares each domain as a typedef int32_t with
its codes as constants (kvstore_KvError_KeyNotFound = 1001).
Domain errors and the trap channel
Every callable has one error strategy, recorded on it in the model, and every target applies it the same way:
- Domain (
throws: KvError). A positive code is a typed domain error: an exception subclass, a SwiftErrorcase, a Goerrorvalue, carrying the code, the producer’s message, and the payload fields as properties. Domains are open: a positive code the binding wasn’t generated with (the producer gained a code since) surfaces as the domain’s base error type with the code and message preserved, and its payload is discarded undecoded. A negative code surfaces as the package’s root error type with that code. - Untyped (
throws: any). Failure is-1with a message, and surfaces as the package’s root error type carrying the message. There’s no code to match on. Negative runtime codes surface the same way. - Trap (no
throws). The function can’t report an error, so any non-zero code is a bug, and the binding traps on it (see the trap policy). It never dresses the code up as a domain error.
Under every strategy, -5 on an async call surfaces as the language’s own
cancellation error (see Async and Cancellation).
Error types are named after the IDL (each target’s root error has a fixed
name or the package’s; see Naming), never
after WeaveFFI. Every target derives a domain’s type name from its IDL name with one shared
rule (see Naming): KvError stays
KvError (or becomes KvException), and Failure becomes FailureError.
A Rust producer’s domain error message is its Display output, generated
from the variant’s #[weaveffi(message = "...")] template or doc comment.
The IDL’s message: (a Rust variant’s template, else its doc comment’s
first line) is the documented default that generated docs and consumer-side
constructors use.
The trap policy
A failure of a call that can’t report one is a producer bug (a panic, an
argument the producer couldn’t lift, a callback failure it let through a
call that can’t report one), and every binding treats it the same way: it
raises the language’s unchecked error rather than a declared one, naming the
runtime code and the producer’s message so the bug can be diagnosed from the
report. In C, the caller reads err.code itself; Swift, which has no
unchecked errors, stops with fatalError; Go panics; the other targets
throw an error type outside the domain hierarchy. Each language page names
its exact type. Cancellation (-5) isn’t a bug and always surfaces as the
language’s cancellation error.
Load-time checks
Before the first call, every binding checks the library’s ABI revision and
the contract of every declaration it
was generated with. A failed check is a catchable error, never a crash,
so an application can report a stale or mismatched library and carry on: the
language’s load or import error where loading can fail, and a check function
where it can’t (Swift and Go). A C consumer compares {p}_abi_version()
with {P}_ABI_VERSION and calls {p}_contract_check() itself, as
Getting Started shows.
The message names the declaration that’s missing or changed (“Store.get
changed since these bindings were generated”). Declarations the library has
and the bindings don’t are fine.
Payloads
An error code may declare fields. When the producer raises it, the fields are
serialized into payload_ptr/payload_len in the value-buffer format, and
each binding exposes them as properties of the error it raises. A code with
no fields leaves the payload null. {p}_error_clear and {p}_error_free
release the payload with the message. A payload never carries an object (a
binding that doesn’t know a code discards its payload undecoded).
When a callback fails
A consumer’s callback implementation can fail in the consumer’s language. The
binding catches the failure in its trampoline and reports it through the
vtable entry’s out_err with the runtime surface:
void kvstore_error_set(kvstore_error* err, int32_t code,
const uint8_t* message_ptr, size_t message_len);
void kvstore_error_set_payload(kvstore_error* err, const uint8_t* ptr, size_t len);
Both copy their arguments with the producer’s allocator; a consumer never stores its own allocation in the struct. What the consumer reports follows the method’s strategy:
- A method that throws a domain (
throws: KvError) may report a positive code of that domain, attaching the code’s fields encoded as a value buffer with{p}_error_set_payload. Any other failure it reports as-1with a message. - A method that throws
anyreports-1with a message. - A method that declares no errors reports
-4with a message (any non-zero code is accepted).
On the producer’s side, a declared code whose payload decodes arrives as
that typed error. Everything else (-1, a code the domain doesn’t declare,
any failure of a method without a domain) reaches the producer as a callback
failure, -4 with the consumer’s message, so a consumer bug can’t
impersonate a domain error.
The producer decides what the failure means for the call in progress.
Nothing unwinds and nothing is deferred: in a Rust producer every callback
trait method returns Result<T, E> with E: From<weaveffi::ForeignError>,
and the failure arrives as an Err. When E is the method’s domain, a
typed code arrives as its variant (with the message re-rendered from its
fields by the domain’s Display), and any other failure is converted from a
ForeignError. A producer function propagates the failure with ? into its
own error type. Mapping ForeignError into a variant of the function’s
domain (the macro tour’s
BookError::ListenerFailed) keeps the call typed for the original caller;
returning ForeignError itself makes the function throws: any, so the
original caller sees -1 with the consumer’s message.
Panics
A Rust producer’s generated functions catch panics and report them as -2.
Destructors (_destroy) have no error slot, so a panic in a Drop
implementation is swallowed rather than unwinding into C. Async functions
report panics through the completion callback.
Leak checks
{p}_debug_live(kind) reports how many resources are live, so a test
harness can assert that a consumer released everything: 0 objects, 1
foreign callbacks, 2 iterators, 3 cancel tokens, and 4 runs (returned
runs, error messages and payloads not yet cleared, and {p}_alloc runs not
yet freed or adopted). Kind -1 returns 1 when the producer counts at all
and 0 when it doesn’t, so a harness can tell “nothing is live” from
“nothing is counted”. A Rust producer counts only with the weaveffi
crate’s leak-check feature; without it every kind returns 0. A consumer
that keeps a failed error around without clearing it shows up as a live run.
Thread safety
Every #[weaveffi::interface] type is Send + Sync (the macro asserts it),
so a macro-built producer may be called from any thread, and the bindings add
no thread restriction of their own. Callback methods and async completions
may arrive on any producer thread; each binding hops to its own scheduler
where the language requires it, and the Dart binding marks its vtables
thread-affine. A hand-written producer with
thread-affine state should document it, and must honor the vtable flag.
Pitfalls
- Treating
lenas an element count. A typed array’slencounts bytes, like every run’s. - Reading the message as a C string. It isn’t NUL-terminated and may be
null; use
message_len. - Freeing borrowed inputs. Parameters are the caller’s; never pass them
to
run_freeor_destroy. - Misaligned typed arrays. A typed-array parameter must be aligned for
its element; slicing a byte buffer at an odd offset fails the call with
-3. - Encoding an object without
_clone. The token hands away a reference your wrapper still needs; the later_destroyover-releases. - Decoding an object-carrying buffer twice. The second decode adopts references that no longer exist.
- Not clearing an error after a failure. The message and payload leak.
error_clearon an async error. It leaks the box; useerror_free.- Freeing a callback’s returned run. A run a callback method returns
belongs to the producer once returned; allocate it with
{p}_allocand don’t free it. - Holding a lock across a callback call. The consumer’s implementation may call back into the producer, which then waits on the lock you hold; snapshot state, release the lock, then call.
Async and Cancellation
An async function returns immediately and delivers its result later, through
the language’s own async idiom: async/await in Swift, Python,
JavaScript, C#, and Dart, a suspend fun in Kotlin, a std::future in C++,
and a blocking call that honors a context.Context in Go. A cancellable
async function is also cancelled through that idiom: cancelling the awaiting
task, coroutine, or promise cancels the native call.
Declaring async functions
In Rust, write an async fn (a free function, method, or static). A final
weaveffi::CancelToken parameter makes it cancellable. From the
macro tour:
#[weaveffi::export]
impl Book {
/// Every contact, in id order, collected on a producer thread.
pub async fn export_all(&self) -> Vec<Contact> {
lock(&self.contacts).values().cloned().collect()
}
}
/// Greet `name` after `delay`. The trailing `CancelToken` makes the
/// function cancellable: cancelling drops the future (and the sleep), and
/// the call completes as cancelled.
#[weaveffi::export]
pub async fn greet_later(name: String, delay: Timeout, _cancel: CancelToken) -> String {
tokio::time::sleep(delay).await;
format!("Hello, {name}!")
}
In an IDL, set async: true, and optionally cancellable: true, on a
function, method, or static:
functions:
- name: greet_later
doc: Greet `name` after `delay_ms` milliseconds.
params:
- { name: name, type: string }
- { name: delay_ms, type: u64 }
return: string
async: true
cancellable: true
async composes with throws, with object and buffered results, and with
every parameter type. Constructors can’t be async (AsyncConstructor), so
an async factory is an async function or static that returns the interface.
In Rust, an async fn in an exported impl that returns Self (or the
interface) is exported as such a static, and a free async fn returning
the object works too. Async functions
can’t return iterators (AsyncIteratorReturn), and cancellable without
async is a validation error (CancellableNotAsync). A Rust async fn
can’t borrow an optional parameter (Option<&T>); take Option<T>.
The C ABI shape
An async function lowers to a launcher named after the function itself and a
completion callback type named {symbol}_callback:
typedef void (*macro_tour_greet_later_callback)(void* context, macro_tour_error* err,
macro_tour_run result);
void macro_tour_greet_later(macro_tour_run name, uint64_t delay,
macro_tour_cancel_token* cancel_token, /* cancellable only */
macro_tour_greet_later_callback callback, void* context);
result is the return’s one C value, exactly as for a synchronous return (a
scalar, a {p}_opt_*, a run, or an object pointer), and is absent for a
function that returns nothing: the completion is then void (*)(void* context, {p}_error* err). kvstore’s async Store.version_of(key: string) -> u32? completes through void (*)(void* context, kvstore_error* err, kvstore_opt_u32 result). On failure result is the zero value. The
launcher has no out_err: every failure, including a marshalling failure of
an input, arrives through the callback.
The completion contract
The runtime guarantees these for every launch:
- Exactly once. The callback fires exactly once, on success, on a
domain error, on a marshalling failure (
-3), on a panic (-2, including one while the launcher lifts its inputs), on a consumer callback failure (-4), on cancellation (-5), and when the executor can’t take the call (-1). It may fire before the launcher returns, and a nullcallbackdiscards the result. - From any thread. It runs on whatever thread completes the future: an
executor thread, a Tokio worker, or (on
wasm32) the caller’s own stack. Each binding hops back to its own scheduler before touching consumer state. - Inputs taken at launch. The launcher copies runs and retains objects
and
selfbefore it returns, so the consumer may release its arguments as soon as the launcher returns. - Owned results.
errisNULLon success; otherwise it’s heap-boxed, owned by the consumer, and released with{p}_error_free. A run result is owned by the consumer and released with{p}_run_freeafter decoding, and an object result moves one strong reference. - Dropped futures complete. If the executor drops a future before it
finishes (a runtime shutting down, say), the call completes with
-5. - Spawn failures complete. If the executor can’t take the future (a
custom spawner panics, or the default executor can’t start its threads),
the call completes with
-1and a message saying why.
A consumer of the raw C surface follows the same rules in its callback: read or decode everything, free it, and adopt object pointers.
Cancellation
The runtime surface provides reference-counted cancel tokens:
macro_tour_cancel_token* token = macro_tour_cancel_token_create(); /* refcount 1 */
macro_tour_greet_later(name, 60000, token, on_done, ctx);
macro_tour_cancel_token_cancel(token); /* any thread, any time; idempotent */
macro_tour_cancel_token_destroy(token); /* drops the consumer's reference */
The launcher takes its own reference on the token, so the consumer may cancel
and destroy its reference at any point after the launch, even before the
call completes. Cancelling wakes the producer’s future; the runtime then
drops the future and completes the call with code -5 and the message
cancelled, unless it had already completed. A null token means “never
cancelled”.
Producer code doesn’t need to check the token: dropping the future cancels
it at its next suspension point, and RAII guards run as usual. Poll
cancel.is_cancelled() only for cooperative cleanup of work the future
doesn’t own, such as a thread it spawned (the kvstore sample’s
Store::compact stops its background pause that way). A future that never
suspends can’t be interrupted; it runs to completion and its result wins.
Per-target surface
| Target | Async surface | Cancellation |
|---|---|---|
| C | launcher plus callback | a {p}_cancel_token* argument |
| C++ | std::future<T> | a cancel-token argument |
| Swift | async (async throws) | cancelling the Task |
| Kotlin | suspend fun | cancelling the coroutine |
| Node.js | Promise<T> | an AbortSignal |
| WebAssembly | Promise<T> | an AbortSignal |
| Python | awaitable | cancelling the awaiting task |
| .NET | Task<T> | a CancellationToken |
| Dart | Future<T> | a cancel-token object |
| Go | blocking call with a context.Context | the context’s cancellation |
| Ruby | blocking call | a cancel-token keyword argument |
A cancelled call raises the language’s cancellation error. Go and Ruby block
the calling goroutine or thread until the completion fires (the native work
still runs off-thread), so call them from a goroutine or Thread for
concurrency. The exact types and signatures are on each language page.
Choosing an executor
Something has to drive each future between launch and completion. The runtime routes every future to the process-wide executor:
-
Tokio (the default). The
weavefficrate’stokiofeature is on by default, and with it the executor is Tokio: the current runtime when the launcher is called from inside one, otherwise a multi-thread runtime the library creates on first use (its threads are namedweaveffi-async). That runtime enables every Tokio driver the build compiles in, so turn on the Tokio features your futures need (time,net, and so on) in your own dependency ontokio, as the macro tour does fortokio::time::sleep. Usetokio::task::spawn_blockingfor synchronous work inside a future.[dependencies] weaveffi = "0.25" tokio = { version = "1", features = ["time"] } -
A thread per call. With
default-features = false, there’s no Tokio dependency, and each async call runs on a thread of its own (also namedweaveffi-async), which drives the future with a minimal blocking executor and exits when the call completes. A future woken from another thread resumes on its own thread. There’s no reactor, so a future that awaits Tokio’s I/O or timers never wakes; use this for futures that wait only on channels, other threads, or nothing at all. A thread that can’t start completes the call with-1.[dependencies] weaveffi = { version = "0.25", default-features = false } -
Custom. Call
weaveffi::set_spawneronce at startup, before the first async launch; it overrides both defaults. It accepts anyFn(BoxFuture) + Send + Sync + 'static:/// Run every async export on `handle`'s runtime instead of the default
/// executor. Call it once, before the first async call. pub fn run_async_exports_on(handle: tokio::runtime::Handle) { let installed = weaveffi::set_spawner(move |future| { handle.spawn(future); }); // Only the first spawner installed in a process takes effect. let _ = installed; }
The first call wins; later calls return an error. The spawner must not
block, because the launcher calls it on the consumer's thread. Every
future it receives is already wrapped so a panic becomes a `-2`
completion, a spawner that drops a future still produces a `-5`
completion, and a spawner that panics completes the call with `-1`.
- **`wasm32`.** There are no threads (Tokio is never compiled in there, so
the `tokio` feature has no effect), and the future is polled inline before
the launcher returns. A future that finishes after bounded work is fine. A
future that's still pending once nothing can wake it (it awaits a timer or
I/O) is dropped, and the call completes with `-1` and the message `async
function suspended with no executor on wasm32` rather than hanging the
module. A call usually completes before an `AbortSignal` can fire, so on
this target cancellation mostly matters for a signal that's already
aborted when the call starts.
## Pitfalls
- **Awaiting Tokio without the `tokio` feature.** The thread-per-call
executor has no reactor, so the future never wakes and the callback never
fires; keep the default feature or install a Tokio spawner.
- **Blocking a Tokio worker.** A future that blocks (synchronous I/O, a
long computation) holds a runtime thread; wrap the work in
`tokio::task::spawn_blocking`.
- **Expecting the token to stop CPU-bound work.** Cancellation drops the
future at a suspension point. Long synchronous loops should yield or check
`is_cancelled()`.
- **Clearing an async error.** `err` is boxed; release it with
`{p}_error_free`, not `error_clear`.
- **Leaking a result run.** A raw C callback that only copies the result
must still free it with `{p}_run_free`.
Project Configuration
A project’s settings live in one weaveffi.toml at its root. The API
definition (a Rust producer crate or an IDL) describes only the API; this
file says where it is, what the library is called, how it’s built and
packaged, and how each target is generated. Every table is optional, and
every unknown table or key is an error, so a typo fails the run instead of
being ignored.
[project]
input = "." # this crate, or an IDL such as "kvstore.yml"
out = "bindings"
targets = ["c", "swift", "kotlin", "python"]
[package]
version = "1.2.0"
description = "An embedded key-value store"
license = "MIT"
authors = ["Example <hello@example.dev>"]
repository = "https://github.com/example/kvstore"
[build]
platforms = ["darwin-arm64", "ios-arm64", "ios-sim-arm64", "android-arm64"]
features = ["sync"]
[generators.swift]
name = "KVStore"
weaveffi init writes a starter file: in a Rust crate it points input at
the crate ("."); elsewhere it also writes a starter IDL.
Discovery
With an explicit input (weaveffi generate api.yml, weaveffi generate path/to/crate), the CLI uses the nearest weaveffi.toml at or above the
input. With no input, it looks for weaveffi.toml in the current directory
and its parents and reads [project] input, so weaveffi generate works
from anywhere inside the project, like cargo build. --config <path>
names a file explicitly. Without any file, every setting takes its default.
[project]
| Key | Default | Meaning |
|---|---|---|
input | none | The API definition: a Rust producer crate (its directory, usually ".", or its Cargo.toml), whose API is read from its built library (see Library Mode), or a .yml, .yaml, or .json IDL (TOML is only for this file) |
out | bindings | Output directory for generate |
targets | every default target | Targets to generate when --target isn’t given (weaveffi init writes ["c", "python"]) |
Paths are relative to the directory holding weaveffi.toml. Command-line
arguments (the input, -o/--out, -t/--target) override the table. A
targets entry that isn’t a target is an error, so a typo can’t silently
generate nothing.
[package]
[package] resolves into the library’s identity:
the package name every ecosystem publishes under, the C symbol prefix,
and the native library base name. Generators derive every other name from
these three.
| Key | Meaning |
|---|---|
name | Distribution name (may contain - or .) |
version | Version stamped into every manifest (default 0.1.0) |
description, license, authors, homepage, repository | Manifest metadata |
c_prefix | C symbol prefix; IDL inputs only |
library | Native library base name (lib{library}.so); IDL inputs only |
dist | Where weaveffi package writes its artifacts (default dist); not part of the identity |
The rules depend on the input:
| Rust producer (a crate) | IDL | |
|---|---|---|
name | [package] name, else the crate’s Cargo package name | [package] name, else the input file stem |
prefix | the crate’s library name ([lib] name, else the package name with - mapped to _) | c_prefix, else snake-case name |
library | same as prefix (the cdylib WeaveFFI builds) | library, else snake-case name |
| metadata | [package], falling back to cargo metadata (workspace-inherited version.workspace = true included) | [package] |
A Rust producer’s prefix is what the attributes compiled into its symbols,
so it can’t be configured: setting c_prefix or library for a Rust
producer is an error. Renaming the published package with name is fine.
[build]
How a Rust producer is compiled. profile, the deployment targets, and
platforms apply to weaveffi build and weaveffi package (see
Packaging); the commands that build a producer’s host
library to read its API (generate, validate, and extract) use the
dev profile unless --profile names another. The feature keys apply to
every build.
| Key | Default | Meaning |
|---|---|---|
features | none | Cargo features every build of the producer enables |
all_features | false | Build the producer with --all-features |
no_default_features | false | Build the producer with --no-default-features |
platforms | the host | Platform ids to build when --platforms isn’t given |
profile | "release" | The Cargo profile build and package use (--profile overrides it) |
macos_deployment_target | "11.0" | MACOSX_DEPLOYMENT_TARGET, and the macOS version wheel tags carry |
ios_deployment_target | "13.0" | IPHONEOS_DEPLOYMENT_TARGET |
android_api | 21 | The minimum Android API level, which picks the NDK compiler |
manifest | the project’s crate | The producer’s Cargo.toml, for an IDL project built from a Rust crate |
Features reach every build. -F/--features, --all-features, and
--no-default-features on generate, validate, extract, build, or
package replace the three feature keys, and whichever set applies is
passed to every build of the producer: the host build library mode reads
the API from as much as each platform’s build. So a declaration behind
#[cfg(feature = "...")] is in the bindings exactly when it’s in the
libraries they load.
[generators.<target>]
One table per target (c, cpp, swift, kotlin, node, wasm,
python, dotnet, dart, go, ruby) holds that generator’s options,
and each target’s page under Generators lists its
keys. Every target that names its package after the library spells the
override name (the Swift package and module, the npm package, the .NET
namespace, the Go module path, and so on). Name overrides never change which
native library a package loads; that’s always {library}. No target has a
C prefix of its own: the prefix belongs to the library.
The C target has one key:
| Key | Default | Meaning |
|---|---|---|
buffer_helpers | true | Also emit {library}_buffer.h, with a C struct and codec for every value-buffer type, when the API passes any value buffers |
Generation records
Rendering is pure: each target renders its files in memory, and the orchestrator does every write. Every run renders every selected target, then:
- Only files whose contents changed are rewritten, so file timestamps (and incremental builds) stay stable. When nothing changed, nothing is written.
- The orchestrator records the files each target produced in
{out}/.weaveffi/{target}.json. Files the previous run recorded that the current run no longer produces (a renamed type, a removed function) are deleted. Files you added under the output directory (anode_modules/, a build directory) are never touched, and a record entry outside its target’s own directory is ignored.
Commit the records with the generated bindings, so generate --check on a
fresh checkout sees stale files too. --dry-run validates and prints every
file the targets render, without writing.
CI
weaveffi generate --check renders in memory and compares with the output
directory without writing anything:
weaveffi generate --check # uses [project]
weaveffi generate path/to/crate -o bindings --target c,swift --check
It lists every file that would change (+ added, ~ modified, -
removed, where a stale file from the previous run counts as removed) and
exits 0 when the directory is up to date and 1 otherwise. weaveffi generate --diff prints the same changes as a unified diff, also without
writing (it exits 0; add --check to exit 1 on changes). --dry-run
and --dev can’t be combined with either. weaveffi validate --format json
prints one JSON object with the result, counts, and any errors (each with a
code matching the error catalog);
--warn adds advisory warnings, which never change the exit status.
Pitfalls
- Config travels with the definition. Two checkouts with different
weaveffi.tomlfiles generate different packages from the same source. Commit the file next to the definition and let discovery find it. - Features on one command only. Building the libraries you ship with a
feature that
generatedidn’t have (or the reverse) gives bindings that don’t match them. Put shipped features in[build] featuresso every command sees the same set. - Name overrides don’t rename the library. The targets that load the
library at run time also accept a full path in the
{PREFIX}_LIBRARYenvironment variable; the targets that link it (C, C++, Swift, and Go) find it when they’re built (see each target’s page).
Packaging
weaveffi generate emits binding source. Shipping it takes two more steps:
weaveffi build cross-compiles the Rust producer once per platform, and
weaveffi package turns those builds into the artifacts each ecosystem
installs: wheels, npm tarballs, gems, a SwiftPM package with its
XCFramework, a NuGet package, and so on. Consumers install them with
pip, npm, gem, SwiftPM, or dotnet and need no compiler.
weaveffi build --platforms darwin-arm64,ios-arm64,ios-sim-arm64
weaveffi package --target python,node,swift
Both read [project], [package], and [build] from weaveffi.toml (or
take an explicit input), and every artifact loads the library named by the
identity’s library field.
Build
weaveffi build finds the producer crate with cargo metadata (the
project’s crate, [build] manifest, or --manifest-path) and runs
cargo rustc --lib once per platform with the artifact kinds that platform
needs, so the crate’s own crate-type doesn’t matter. It builds with the
release profile unless --profile (or [build] profile) names another,
and with the project’s Cargo features (-F/--features, --all-features,
--no-default-features, or the [build] keys). A Rust producer’s API is
then read from the first library it built (see Library Mode),
so nothing is compiled twice. build produces only the producer’s library:
no target needs compiled glue of its own.
| Platform | What build produces |
|---|---|
| macOS | the cdylib, with install name @rpath/lib{library}.dylib, plus the staticlib an XCFramework slice is made from |
| iOS | the staticlib |
| Linux, Android | the cdylib, with soname lib{library}.so (Android also 16 KB page-aligned) |
| Windows | the DLL and its import library |
wasm32 | the .wasm module, linked with --export-table --growable-table |
It sets MACOSX_DEPLOYMENT_TARGET and IPHONEOS_DEPLOYMENT_TARGET from
[build], and for Android it finds the NDK (ANDROID_NDK_HOME,
ANDROID_NDK_ROOT, or the newest ndk/<version> of the Android SDK) and
points Cargo’s linker and the cc crate at the NDK’s clang for the
configured API level. Everything lands in the Cargo target directory:
target/weaveffi/
darwin-arm64/ libkvstore.dylib libkvstore.a
ios-arm64/ libkvstore.a
android-arm64/ libkvstore.so
wasm32/ kvstore.wasm
Every platform is checked before anything compiles; a platform this machine can’t build (a missing rustup target, a missing NDK, or a host that can’t build it: Apple platforms need macOS, Windows needs Windows) is skipped with a warning naming the fix, and the run fails only when no requested platform can be built.
build and package follow one policy for a missing external tool (a C
compiler, the NDK, Xcode, the .NET SDK): they warn, skip the artifact that
needs it, finish everything else, and list every skipped artifact at the
end. The run still exits 0; pass --strict to exit 1 when anything was
skipped (as CI should).
Package
weaveffi package runs build for the requested platforms, then writes
each target’s artifacts to the dist directory (-o, else [package] dist,
else dist). With --binaries <dir>, it skips the build and reads a
directory laid out like target/weaveffi/ instead; that’s how CI hands
libraries built on separate runners to one packaging job, and how a
producer that isn’t a Rust crate is packaged. A Rust producer’s API is read
from the first library in the directory.
| Target | Artifacts | Publish with |
|---|---|---|
python | one platform wheel per desktop platform, the library inside the import package | twine upload |
node | one npm tarball per desktop platform ({package}-{os}-{cpu}) carrying only the library, plus the main package, which lists them as optional dependencies and depends on koffi | npm publish for each, platform packages first |
wasm | an npm tarball with the .wasm module | npm publish |
ruby | one platform gem per desktop platform | gem push |
swift | C{Module}.xcframework.zip (static libraries for every Apple platform built), its .sha256, and the SwiftPM package whose binary target points at the archive’s URL and checksum | upload the archive, then commit and tag the package |
dotnet | a project with runtimes/<rid>/native/ libraries, and the .nupkg that dotnet pack builds from it | dotnet nuget push |
kotlin | a Gradle project with the Android libraries under src/main/jniLibs/<abi>/ and the desktop ones under JNA’s src/main/resources/<os>-<arch>/ | Gradle |
dart | a pub package with the desktop libraries under native/<platform>/ | dart pub publish |
go | a module with the libraries and cgo flags that link the right one | push the module to its repository |
c, cpp | archives of the headers, the libraries per platform, and a CMakeLists.txt | attach to a release |
Each target’s page under Generators documents its
artifacts’ names and layout. Each archive is deterministic (fixed timestamps
and order), so the same builds always produce the same bytes and checksums.
A target skips platforms its ecosystem has no slot for (a wheel has no
Android tag, NuGet no wasm32 runtime), and a target with nothing to ship
is named in a note.
Platforms
--platforms takes a comma-separated list of platform ids; without it,
build and package use [build] platforms, else the host. With
--binaries, the default is every platform directory present.
| Platform id | Rust target | Shipped by |
|---|---|---|
darwin-arm64 | aarch64-apple-darwin | every desktop target, and swift |
darwin-x64 | x86_64-apple-darwin | every desktop target, and swift |
linux-x64 | x86_64-unknown-linux-gnu | every desktop target |
linux-arm64 | aarch64-unknown-linux-gnu | every desktop target |
windows-x64 | x86_64-pc-windows-msvc | every desktop target |
ios-arm64 | aarch64-apple-ios | swift |
ios-sim-arm64 | aarch64-apple-ios-sim | swift |
ios-sim-x64 | x86_64-apple-ios | swift |
android-arm64 | aarch64-linux-android | kotlin (and c) |
android-x64 | x86_64-linux-android | kotlin (and c) |
wasm32 | wasm32-unknown-unknown | wasm (and c) |
Swift and the XCFramework
package fuses the Apple static libraries into C{Module}.xcframework
(iOS device, iOS simulator, and macOS slices, with a group’s architectures
fused by lipo), zips it, and writes its SHA-256 checksum. The packaged
Package.swift declares the C module as a .binaryTarget(url:checksum:),
so apps link the library with no flags. The URL comes from the Swift
target’s configuration (see Swift); to publish,
upload the archive to that URL and commit the package to the repository
consumers depend on. This step runs xcodebuild, so it needs macOS with
Xcode; elsewhere the Swift package is skipped.
What still needs the ecosystem’s tools
- Publishing. There’s no
weaveffi publish; run each ecosystem’s own upload command on the artifacts. - NuGet.
packagerunsdotnet pack, so the .NET SDK must be installed; without it the.nupkgis skipped (and--strictfails the run) after everything else is written. - Kotlin. The output is a Gradle project, not an
.aaror.jar, so build one with Gradle. - Cross-architecture Linux. Building
linux-arm64on an x64 host needs a cross linker (CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER); an arm64 runner is simpler.
CI recipe
Build each platform on a runner that can, upload target/weaveffi/, then
package once:
jobs:
build:
strategy:
matrix:
include:
- runner: macos-latest
platforms: darwin-arm64,darwin-x64,ios-arm64,ios-sim-arm64
targets: aarch64-apple-darwin,x86_64-apple-darwin,aarch64-apple-ios,aarch64-apple-ios-sim
- runner: ubuntu-latest
platforms: linux-x64,android-arm64,android-x64,wasm32
targets: aarch64-linux-android,x86_64-linux-android,wasm32-unknown-unknown
- { runner: ubuntu-24.04-arm, platforms: linux-arm64, targets: "" }
- { runner: windows-latest, platforms: windows-x64, targets: "" }
runs-on: ${{ matrix.runner }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.targets }}
- run: cargo install weaveffi-cli
- run: weaveffi build --platforms ${{ matrix.platforms }} --strict
- uses: actions/upload-artifact@v4
with:
name: weaveffi-${{ matrix.runner }}
path: target/weaveffi/
package:
needs: build
runs-on: macos-latest # the XCFramework needs xcodebuild
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
pattern: weaveffi-*
path: prebuilt
merge-multiple: true
- run: cargo install weaveffi-cli
- run: weaveffi package --binaries prebuilt --strict
The Linux runner finds the NDK through ANDROID_NDK_HOME (or the SDK
preinstalled on GitHub’s images). A platform you can’t build can be dropped
from the matrix; every target packages whatever subset is present.
Library Mode
The CLI never reads Rust source. A Rust producer’s API is read from the
library the crate builds: each WeaveFFI attribute embeds a description of its
declaration in the compiled library, and weaveffi generate, validate,
extract, build, and package read it back out. The bindings therefore
describe exactly what the library was compiled with: #[cfg], Cargo
features, type aliases, and macro expansion all resolved.
A Rust project’s input is the crate: its directory ([project] input = ".",
which weaveffi init writes) or its Cargo.toml.
weaveffi generate # build the crate (dev profile), read it, generate
weaveffi generate --profile release # read a release build instead
weaveffi generate -F sync,metrics # build it with Cargo features
weaveffi generate --library target/x86_64-unknown-linux-gnu/release/libkvstore.so
Without --library, the CLI resolves the crate with cargo metadata (its
name, version, library name, and target directory), runs cargo rustc --lib --crate-type cdylib --profile <profile> with the project’s Cargo features
(Cargo’s errors and warnings print as usual), and reads the cdylib it
built, so the crate needs no crate-type of its own. --profile defaults
to dev, and the features are -F/--features, --all-features, and
--no-default-features, else [build] features, all_features, and
no_default_features (see Project Configuration): the
same set every build of the producer uses, so the bindings and the shipped
libraries agree on every #[cfg(feature = "...")].
--library skips the build and reads the given file: a shared library, a
static archive, or a .wasm module, for any platform (an Android .so
reads fine on a Mac). With no crate at all (no input argument and no
[project] input), --library reads the library on its own: the prefix
comes from its metadata and the library name from its file name, and a file
holding the metadata of several WeaveFFI crates is an error that asks for
the crate.
Extracting an IDL
weaveffi extract prints the API the library embeds as an IDL document,
which is useful for reviewing the API surface, committing a canonical IDL
next to the crate, or handing the API to a non-Rust implementation.
weaveffi extract # the project's crate, YAML to stdout
weaveffi extract path/to/crate -o api.yml
weaveffi extract -f json -o api.json # JSON
weaveffi extract --library libkvstore.dylib
| Flag | Default | Meaning |
|---|---|---|
-o, --out | stdout | Write to a file |
-f, --format | yaml | yaml or json |
--library | build the crate | Read this library instead |
--profile | dev | The Cargo profile to build the crate with |
-F, --features; --all-features; --no-default-features | [build]’s | The Cargo features to build the crate with |
--config | discovered | The weaveffi.toml to use |
The document is validated before it’s printed, so what extract prints
always generates. An IDL input is an error: there’s nothing to extract.
The extracted IDL carries no package identity. When you generate from it,
the identity comes from [package] in weaveffi.toml (IDL rules), not from
Cargo.toml, so set name, c_prefix, and library to match the crate if
the generated bindings must load the Rust library.
How the API is embedded
For every declaration (a function, an interface and each of its members, a
record, an enum, an error domain, a callback interface) the attribute emits
an exported static holding one frame, a little-endian u32 length and
then compact JSON recording the declaration (in the IDL’s own shape), the
source location of its attribute, the crate’s prefix, the schema version,
and the ABI revision. The static is named the crate’s uppercase prefix,
_META_, and 16 uppercase hex digits of the FNV-1a 64 hash of the
declaration’s path (Book.add), so it never collides with another
declaration or another crate:
#[unsafe(export_name = "MACRO_TOUR_META_...")]
#[cfg_attr(target_family = "wasm", unsafe(link_section = "weaveffi_meta"))]
#[used]
pub static __WEAVEFFI_META: [u8; N] = /* the frame */;
The CLI reads native libraries with the object crate, walking the symbol
tables for _META_ symbols and reading each one’s bytes from the section
that holds it (every member of a static archive included). A wasm32
module keeps its data out of reach of any symbol table, so there the frames
go to the weaveffi_meta custom section, which the linker fills with every
frame back to back. The CLI keeps the frames carrying the crate’s own
prefix (a dependency that is itself a WeaveFFI producer embeds frames too)
and assembles them into the API, ordering each kind of declaration by where
its attribute is written (file, line, then column), whatever order the
linker laid the statics out in. A frame built by another WeaveFFI version
(another schema version or ABI revision) is an error.
A frame carries its declaration’s #[cfg] (and, for an interface member,
its impl block’s), so a declaration a build compiles out is missing from
that build’s metadata exactly as it’s missing from its symbols and its
contract functions. The macro tour’s
Book::purge is in the API only when the crate is built with its admin
feature (weaveffi extract -F admin).
A library with no frames for the crate (the API isn’t tagged) is an error
that says what’s missing: tagged items and one weaveffi::export_runtime!()
call.
Iterating: generate --dev
weaveffi generate --dev generates as usual, then points the generated
packages at the library the API was read from (the one it just built, or
--library’s):
- it copies the library into each generated package that looks for a bundled copy (when the library is a shared library), so it loads with no environment variables;
- for every other target that loads the library at run time, it prints the
{PREFIX}_LIBRARY=<path>to set; - for the targets that link the library when they’re built (C, C++, Swift,
and Go), it prints the directory to link with (
-L<dir> -l{library}) and to put on the loader path; - WebAssembly needs a
wasm32build, which--devdoesn’t make (weaveffi build --platforms wasm32does).
--dev needs a Rust producer (or --library), and can’t be combined with
--check, --diff, or --dry-run. Rerun it after changing the crate:
copies don’t follow later builds. Each target’s page says where its package
looks for the library.
Generating from a build script
The CLI is also a library. weaveffi_cli::project::Project locates a
project the way the weaveffi command does, and the
weaveffi_cli::codegen::Orchestrator generates it, so a crate that ships
bindings for an IDL-defined library can generate them from its build.rs:
// build.rs
use weaveffi_cli::codegen::Orchestrator;
use weaveffi_cli::project::Project;
fn main() -> miette::Result<()> {
println!("cargo::rerun-if-changed=weaveffi.toml");
println!("cargo::rerun-if-changed=api.yml");
let project = Project::discover(env!("CARGO_MANIFEST_DIR"))?;
let targets = project.config.targets(None)?;
Orchestrator::new()
.with_targets(targets.iter().map(AsRef::as_ref))
.run(&project.model()?, &project.config.out_dir(None))?;
Ok(())
}
[build-dependencies]
weaveffi-cli = "0.25"
miette = "7"
Project::discover finds the nearest weaveffi.toml at or above the
directory, and the orchestrator writes the [project] targets into
[project] out, rewriting only changed files.
A build script runs before its crate is compiled, so it can’t read its own
crate’s library: from a build.rs, the project’s input must be an IDL, or
the API must come from a library built earlier, named with
Project::library(path). Pointing a crate’s own build.rs at the crate is
an error that says so. For a Rust producer, generate after the build
instead: weaveffi generate in CI or a cargo xtask.
Type mapping
| Rust | IDL |
|---|---|
i8..i64, u8..u64, f32, f64, bool | same |
usize, isize | u64, i64 |
char | string |
String, &str | string |
Vec<u8>, &[u8] | bytes |
Vec<T>, &[T] | [T] |
Option<T>, Option<&T> | T? |
HashMap<K, V>, BTreeMap<K, V> | {K:V} |
weaveffi::Iter<T> | iter<T> |
&T, Arc<T> (interface), Self, Arc<Self> | T |
Arc<dyn Trait> (callback interface) | Trait |
weaveffi::CancelToken (an async fn’s last parameter) | removed; sets cancellable: true |
Result<T, E>, E a #[weaveffi::error] domain | return T, throws: E |
Result<T, E>, E an untyped error | return T, throws: any |
a #[weaveffi::custom] type | its repr |
| a type alias | its target |
| a tagged record, enum, or interface | its name |
Compositions map recursively: Option<Vec<i32>> is [i32]? and
Vec<Arc<Book>> is [Book]. An async fn sets async: true, and ()
and Result<(), E> returns are no return. A callback method’s Result<T, E> follows the same rule as a function’s: a domain E throws that domain,
and an untyped one (ForeignError included) throws any. A type is named
in the IDL by its declaration’s name alone, wherever in the crate it’s
declared.
Limits
- Error messages. A
#[weaveffi::error]variant’s doc comment becomes the code’sdoc:, and the code’smessage:is the variant’s#[weaveffi(message = "...")]template as written, else its doc comment’s first line, else the variant name. The runtime message is the generatedDisplay(the template filled from the fields), which the IDL can’t express. - Deprecation versions.
#[deprecated(since = "...")]keeps only the note; the IDL has nosincefield. - Parameter docs. Rust doesn’t allow doc comments on function
parameters, so an extracted API has no parameter
doc; describe parameters in the function’s own doc comment.
The CLI’s tests build the fixture producer in
crates/weaveffi-cli/tests/fixtures/producer, check that weaveffi extract
prints exactly its expected.yml, and check that generating from the
library and from that IDL gives identical output.
IDL Schema
An IDL document describes one library’s API: its records, enums, error
domains, interfaces, callback interfaces, and functions. YAML and JSON are
accepted (TOML is only for weaveffi.toml, never for
an IDL); this page uses YAML, read as YAML 1.2, so a name YAML reads as null
(null, ~) has to be quoted (name: "null"). It documents schema version
0.13.0, the only version the current tools accept. A Rust producer never
writes one by hand (the attributes embed the API in the built library, and
weaveffi extract prints it as an IDL), but the
schema is the same either way.
The YAML on this page is included from the documents in
examples/idl,
which a test loads and validates the way weaveffi validate does. A block
whose first line is # rejected: is a document the validator refuses, with
the error it reports; the test checks that too.
Editor support
The CLI prints a JSON Schema for the document with weaveffi schema, and a
copy is checked in as
weaveffi.schema.json
and published at https://weaveffi.com/weaveffi.schema.json. Editors using
the YAML Language Server pick it up from a header comment:
# yaml-language-server: $schema=https://weaveffi.com/weaveffi.schema.json
Document structure
A library is one namespace, so a document is flat: every declaration sits at the top level, in a list by kind.
version: "0.13.0"
doc: An in-memory address book.
| Key | Type | Meaning |
|---|---|---|
version | string (required) | Must be "0.13.0" |
doc | string | Documentation for the library as a whole |
imports | array of paths | Other IDL files whose declarations join this library (see Multi-file IDLs) |
records | array of Record | Plain data types with named fields |
enums | array of Enum | C-style or rich enums |
errors | array of ErrorDomain | Error domains |
interfaces | array of Interface | Reference-counted object types |
callbacks | array of CallbackInterface | Method sets the consumer implements |
functions | array of Function | Free functions |
The document describes only the API. Package identity and generator options
live in weaveffi.toml. Every object rejects unknown
keys, so a misspelled field fails to parse instead of being ignored.
Function
The same shape describes free functions, interface constructors, methods, and statics, and callback-interface methods, with the restrictions noted in their sections.
| Field | Type | Meaning |
|---|---|---|
name | string (required) | Function name |
params | array of Param | Ordered parameters (default none) |
return | TypeRef | Return type; omit for none |
doc | string | Documentation |
throws | string | The error domain the callable reports (BookError), or any for an untyped error; omit when it can’t fail (see Error domains) |
async | bool | Complete asynchronously (default false) |
cancellable | bool | Accept a cancel token; requires async: true |
deprecated | string | Deprecation message propagated to every binding |
A Param has a required name and type and an optional doc. A parameter
may not be named self, ctx, out_err, callback, context, or
cancel_token, the slots the C ABI adds (SlotCollision).
Types
A TypeRef is a string:
| Syntax | Meaning |
|---|---|
i8 i16 i32 i64 u8 u16 u32 u64 | Fixed-width integers |
f32 f64 | IEEE 754 floats |
bool | Boolean |
string | UTF-8 text |
bytes | Byte string ([u8] is accepted and becomes bytes) |
Name | A record, enum, interface, or callback interface, by name |
T? | Optional |
[T] | List |
{K:V} | Map |
iter<T> | Lazy iterator (returns only) |
usize, isize, u128, i128, and char aren’t primitives; a reference
to one is reported as UnsupportedPrimitive (use u64 or i64 for sizes,
and string for characters). A reference to a name nothing declares is
UnknownTypeRef.
The parser reads outside in: [Contact?] is a list of optional contacts and
[Contact]? an optional list. Composites nest to any depth. Quote anything
YAML would otherwise interpret ("string?", "[i32]", "{string:i32}").
How a type is spelled never depends on how it crosses the ABI. At a call
boundary every value is one C value: a
scalar or C-style enum by value, an optional one (i32?, Kind?) as a
{p}_opt_* struct, an interface as a pointer, and everything else as a
{p}_run holding a string’s UTF-8, raw bytes, a typed array (a list of any
integer or float but u8), or a value buffer. Every
binding surfaces them as its ordinary optional and list types; inside a
record, variant, or error payload every type uses the value-buffer encoding.
Map keys must be an integer, bool, string, or a C-style enum, so
every target can use its native dictionary with exact equality. Floats,
bytes, composites, and objects are rejected:
# rejected: InvalidMapKey
version: "0.13.0"
functions:
- name: by_weight
params:
- { name: index, type: "{f64:i32}" }
Iterators are lazy: every binding pulls one element per step of its
native iteration idiom and destroys the iterator exactly once. iter<T> is
valid only as the outermost return of a synchronous callable. It’s rejected
in a parameter, a field, or nested in another type
(IteratorInInvalidPosition), and as the return of an async function
(AsyncIteratorReturn):
# rejected: IteratorInInvalidPosition
version: "0.13.0"
functions:
- name: consume
params:
- { name: items, type: "iter<i32>" }
Type positions
“Buffered field” means a record field, rich-enum variant field, or error payload field.
| Type | Param | Return | Buffered field | Inside T? [T] {K:V} | Map key | Callback param | Callback return |
|---|---|---|---|---|---|---|---|
integers, floats, bool | yes | yes | yes | yes | integers, bool | yes | yes |
string | yes | yes | yes | yes | yes | yes | yes |
bytes | yes | yes | yes | yes | no | yes | yes |
| C-style enum | yes | yes | yes | yes | yes | yes | yes |
| record, rich enum | yes | yes | yes | yes | no | yes | yes |
| interface | yes | yes | yes, except in an error payload | yes | no | yes | yes |
| callback interface | yes, bare or Cb? | no | no | no | no | no | no |
T?, [T], {K:V} | yes | yes | yes | yes | no | yes | yes |
iter<T> | no | yes (sync) | no | no | no | no | no |
A record or rich enum may not contain itself by value, directly or through
other records and variants (RecursiveType); a list, map, or optional of it
is fine.
Records
A record is a value type with named fields, crossing the ABI by value as a value buffer. Bindings map it to a data class, struct, or record type; no per-record C functions exist.
| Field | Type | Meaning |
|---|---|---|
name | string (required) | Type name |
doc | string | Documentation |
deprecated | string | Deprecation message |
fields | array of Field (required, non-empty) | Each with name, type, optional doc |
records:
- name: Contact
doc: One contact.
fields:
- { name: id, type: u64, doc: The book-assigned id. }
- { name: name, type: string }
- { name: email, type: "string?" }
- { name: kind, type: Kind }
- { name: tags, type: "[string]" }
- { name: notes, type: "{string:string}" }
Enums
An enum is a fixed set of variants.
| Field | Type | Meaning |
|---|---|---|
name | string (required) | Type name |
doc, deprecated | string | Documentation, deprecation message |
variants | array of Variant (required, non-empty) | Each with name, optional value, doc, and fields |
A variant’s value is its i32 discriminant; without one it’s one more
than the previous variant’s (0 for the first), as in Rust and C, so
Kind below is Personal = 0, Work = 10, Other = 11. When no variant
has fields, the enum is C-style: it crosses as an int32_t and may be
a map key. When any variant has fields, the enum is rich (a sum type):
it crosses as a value buffer holding the variant’s value as a tag
followed by its fields, and bindings map it to a Swift enum with associated
values, a sealed class hierarchy, a tagged union, and so on. Unit and data
variants may mix.
enums:
- name: Kind
doc: How a contact is filed.
variants:
- { name: Personal }
- { name: Work, value: 10 }
- { name: Other }
- name: Change
doc: A change to a book.
variants:
- name: Added
fields:
- { name: contact, type: Contact }
- name: Removed
fields:
- { name: id, type: u64 }
- { name: Cleared }
Variant names and values are unique within an enum, and a variant’s field names are unique within the variant.
Error domains
An error domain is a named set of stable codes that callables report. Each
binding generates a typed error (an exception hierarchy, a Swift Error
enum, a Go error type) so consumers match on the names you declared. A
library may declare any number of domains.
| Field | Type | Meaning |
|---|---|---|
name | string (required) | Domain type name (BookError) |
doc | string | Documentation |
codes | array of Code (required) | The codes |
Each code has a required name (PascalCase by convention), positive code,
and default message, plus an optional doc and optional fields: a
structured payload with the same shape as record fields, delivered as
properties of the raised error.
errors:
- name: BookError
doc: The address book's errors.
codes:
- name: NotFound
code: 1
message: contact not found
fields:
- { name: id, type: u64 }
- name: Full
code: 2
message: the book is full
fields:
- { name: capacity, type: u32 }
- { name: EmptyName, code: 3, message: a contact needs a name }
- name: Rejected
code: 4
message: a listener rejected the contact
fields:
- { name: name, type: string }
A function, constructor, method, static, or callback method says how it can
fail with throws:
throws: {Domain}names the one domain it reports (Book.addbelow).throws: anyreports an untyped error: a message, with no code a consumer can match on (parse_numberbelow). Bindings surface it as the library’s base error type. A Rust producer’sResult<T, E>isthrows: anywhenEis an untyped error (weaveffi::Error,String,std::io::Error, …).- No
throws(count) means a plain signature that can’t report an error; a failure there is a producer bug and traps (see Errors and Memory).
A throws that names something other than an error domain is rejected:
# rejected: UnknownErrorDomain
version: "0.13.0"
records:
- name: Contact
fields:
- { name: name, type: string }
functions:
- name: get_contact
params:
- { name: id, type: u64 }
return: Contact
throws: Contact
Domains are open. Each code has its own contract function, so a producer may add codes to a domain without breaking a deployed binding. A binding that receives a positive code it wasn’t generated with reports it as the domain’s base error type with the code and message preserved, and discards its payload undecoded. That’s why payload fields are plain data: a field may not reach an interface, directly or through a record or rich enum:
# rejected: ObjectInErrorPayload
version: "0.13.0"
interfaces:
- name: Store
methods:
- { name: count, return: u64 }
errors:
- name: StoreError
codes:
- name: Locked
code: 1
message: the store is locked
fields:
- { name: holder, type: Store }
Codes must be positive (0 is success and negative codes belong to the
runtime) and unique within their domain (DuplicateErrorCode). Code names
must be unique across every domain in the library
(DuplicateErrorCodeName), because several targets flatten them into one
namespace; qualify one (OrderNotFound) when two domains need the same
idea. A domain name is a declaration name like any other, but it isn’t a
value type: type: BookError is ErrorDomainAsType. any is reserved and
can’t name a domain.
Interfaces
An interface is an object type: state with identity and behavior that lives in the producer and crosses the ABI as an opaque, reference-counted pointer. Consumers see a class whose constructors, methods, and statics call into the producer.
| Field | Type | Meaning |
|---|---|---|
name | string (required) | Type name |
doc, deprecated | string | Documentation, deprecation message |
constructors | array of Function | Return a new instance; no return, never async |
methods | array of Function | Take the instance implicitly |
statics | array of Function | No instance |
interfaces:
- name: Book
doc: An address book.
constructors:
- name: new
params:
- { name: capacity, type: u32 }
methods:
- name: add
params:
- { name: name, type: string }
- { name: email, type: "string?" }
- { name: kind, type: Kind }
return: Contact
throws: BookError
- name: get
params:
- { name: id, type: u64 }
return: Contact
throws: BookError
- name: remove
params:
- { name: id, type: u64 }
return: bool
- { name: count, return: u64 }
- { name: size, return: u32, deprecated: use count }
- name: names
doc: Every contact's name, pulled lazily.
return: "iter<string>"
- name: subscribe
params:
- { name: listener, type: Listener }
- name: export_all
return: "[Contact]"
async: true
- { name: merged_with, params: [{ name: other, type: "Book?" }], return: Book }
statics:
- { name: default_capacity, return: u32 }
An interface needs at least one member, and constructor, method, and static
names share one namespace. A constructor named new becomes the canonical
constructor where the target has one (Swift init, Python __init__);
others become static factories. For an async factory, declare an async
static that returns the interface.
An interface may appear in every position except a map key and an error
payload: parameters, returns, optionals, lists, map values, record and
variant fields, iterator elements, async results, and callback parameters
and returns. Book? at the top level of a parameter or return is a nullable
pointer. Every position moves or borrows references by the rules in
Errors and Memory.
An interface lowers to an opaque type, one function per member (methods take
a leading self), and implicit _clone and _destroy functions you never
declare. From the document above (prefix contacts):
typedef struct contacts_Book contacts_Book;
contacts_Book* contacts_Book_new(uint32_t capacity, contacts_error* out_err);
contacts_run contacts_Book_get(const contacts_Book* self, uint64_t id, contacts_error* out_err);
contacts_Book* contacts_Book_merged_with(const contacts_Book* self, const contacts_Book* other,
contacts_error* out_err);
contacts_Book* contacts_Book_clone(const contacts_Book* self);
void contacts_Book_destroy(contacts_Book* self);
Callback interfaces
A callback interface is the inverse of an interface: methods the consumer implements and the producer calls, any number of times and from any thread, for as long as it holds the implementation.
| Field | Type | Meaning |
|---|---|---|
name | string (required) | Type name |
doc, deprecated | string | Documentation, deprecation message |
methods | array of Function (required, non-empty) | In vtable order |
callbacks:
- name: Listener
doc: Approves the contacts a book adds and hears about its changes.
methods:
- name: approve
params:
- { name: contact, type: Contact }
return: bool
throws: BookError
- name: on_change
params:
- { name: change, type: Change }
throws: any
Methods are restricted:
- synchronous: no
async, nocancellable(InvalidCallbackMethod); - they return nothing or any type except an iterator
(
InvalidCallbackMethod) or a callback interface (CallbackInterfaceInInvalidPosition); a string, bytes, typed-array, or buffered return is a run the consumer allocates with{p}_allocand the producer adopts, and an object return moves one reference to the producer; - parameters may be any type except an iterator
(
IteratorInInvalidPosition) or a callback interface (CallbackInterfaceInInvalidPosition); an object parameter moves one reference to the consumer.
A method may declare throws like any callable. With throws: BookError
its consumer may fail with one of the domain’s codes, with the code’s
fields, and the producer receives the typed error; with throws: any a
consumer failure reaches the producer as an untyped error with its message.
Every failure of a method without throws, and a code its domain doesn’t
declare, reaches the producer as the runtime code -4. Each callback method
has its own contract function, and vtables are open, so appending a method
to a callback interface doesn’t break a deployed binding; reordering methods
or inserting one before others moves vtable slots and does.
A callback interface is valid only as a parameter of a function,
constructor, method, or static, passed bare (Listener) or optional
(Listener?, where none is a null vtable). Anything else is
CallbackInterfaceInInvalidPosition:
# rejected: CallbackInterfaceInInvalidPosition
version: "0.13.0"
callbacks:
- name: Listener
methods:
- { name: on_event, params: [{ name: id, type: i64 }] }
functions:
- name: current_listener
return: Listener
A callback interface lowers to an argument struct and a vtable type that
starts with a header (the vtable’s size, its flags, and the free
release hook) followed by one entry per method in declaration order:
typedef struct contacts_Listener { void* ctx; const contacts_Listener_vtable* vtable; } contacts_Listener;
struct contacts_Listener_vtable {
uint32_t size;
uint32_t flags;
void (*free)(void* ctx);
bool (*approve)(void* ctx, contacts_run contact, contacts_error* out_err);
void (*on_change)(void* ctx, contacts_run change, contacts_error* out_err);
};
void contacts_Book_subscribe(const contacts_Book* self, contacts_Listener listener,
contacts_error* out_err);
Functions
Free functions use the Function shape:
functions:
- name: greet_later
doc: Greet `name` after `delay_ms` milliseconds.
params:
- { name: name, type: string }
- { name: delay_ms, type: u64 }
return: string
async: true
cancellable: true
- name: word_count
params:
- { name: text, type: string }
return: u64
- name: mean
params:
- { name: values, type: "[f64]" }
return: "f64?"
- name: parse_number
params:
- { name: text, type: string }
return: i64
throws: any
async: true makes a function, method, or static complete through a
callback, surfaced as each language’s async idiom, and cancellable: true
adds a cancel token; both are covered in
Async and Cancellation. Constructors can’t be async
(AsyncConstructor), and cancellable requires async:
# rejected: CancellableNotAsync
version: "0.13.0"
functions:
- { name: ping, return: bool, cancellable: true }
deprecated: on a function, method, static, record, enum, interface, or
callback interface propagates its message to every binding’s native
deprecation marker.
Multi-file IDLs
A large API can be split across files. A document’s top-level imports:
lists other IDL files, as paths relative to the importing file, and every
declaration of an imported file joins the importer’s one namespace. A
declaration in any file may refer to one in any other, in either direction:
version: "0.13.0"
doc: Drawing with shapes, measured in units.
imports:
- shapes.yml
records:
- name: Canvas
fields:
- { name: width, type: f64 }
- { name: shapes, type: "[Shape]" }
functions:
- name: area
params:
- { name: canvas, type: Canvas }
- { name: unit, type: Unit }
return: f64
throws: DrawError
drawing.yml uses Shape and throws DrawError from the file it imports:
version: "0.13.0"
imports:
- units.yml
enums:
- name: Shape
variants:
- name: Circle
fields:
- { name: radius, type: f64 }
- name: Rect
fields:
- { name: width, type: f64 }
- { name: height, type: f64 }
errors:
- name: DrawError
codes:
- { name: NegativeSize, code: 1, message: a shape has a negative size }
which in turn imports Unit, which drawing.yml uses too:
version: "0.13.0"
enums:
- name: Unit
variants:
- { name: Points }
- { name: Millimeters }
The rules:
- Every file declares the same
version. The library’sdocandimportsare the root document’s; an imported file’sdocis ignored. - Imports are recursive, and a file reached twice (here
units.yml, ifdrawing.ymlimported it too) is read once. An import chain that leads back to a file importing it is an error (import cycle). - Names are unique across all the files, exactly as in one document, and a diagnostic points into the file that declares the offending item.
weaveffi generate,validate, andgenerate --checkread the root document with every file it imports, so the bindings, the contract, and the drift check cover the whole API.
Names
A library is one namespace. Record, enum, error domain, interface,
callback interface, and free function names are unique across the whole
library, whichever file declares them (DuplicateName):
# rejected: DuplicateName
version: "0.13.0"
records:
- name: Stats
fields:
- { name: total, type: u64 }
functions:
- name: Stats
return: u64
Error code names are unique across every domain (DuplicateErrorCodeName).
Members are scoped to their owner: parameters to their callable, fields to
their record or variant, variants to their enum, constructors, methods, and
statics to their interface, and methods to their callback interface.
Because a name identifies one declaration, a type reference is always the
bare name. C symbols are the library’s prefix and the name: a function
get_contact is {p}_get_contact, a record Contact is {p}_Contact, and
a method get on Book is {p}_Book_get (see Naming and the
C ABI contract).
Documentation comments
doc: is accepted on the library, functions, parameters, records, fields,
enums, variants, error domains and codes, interfaces and their members, and
callback interfaces and their methods. Every generator emits it in the
target’s native doc-comment syntax (///, /** */, docstrings, XML docs);
multi-line YAML block strings (|) are preserved. An absent doc: emits
nothing.
Validation
weaveffi validate (and every generating command) runs every rule and
reports every violation in one pass, each with a message, a suggestion, and a
source span in the file that declares the offending item when one can be
found. --format json emits the same diagnostics, each with a code field
naming the error alongside its own fields; --warn adds advisory warnings.
The rules in brief:
- Names are identifiers (a letter or
_, then ASCII letters, digits, and_) and not one ofif,else,for,while,loop,match,type,return,async,await,break,continue,fn,struct,enum,mod, oruse(and no error domain is namedany). Generators escape other languages’ keywords themselves. - Declaration names and error code names are unique across the library; every other name is unique in its scope (see Names).
- Records, enums, interfaces, and callback interfaces aren’t empty, and no record or rich enum contains itself by value.
- Types resolve and appear only in the positions in the table above.
throwsnames an error domain (or isany);cancellableneedsasync.- Codes are positive and their values unique within a domain.
- No two declarations lower to the same C identifier. Every symbol is
the prefix plus the declaration’s name (
Owner_memberfor a member), so a free functionBook_getcollides with agetmethod onBook, a function namedBook_clonewithBook’s implicit_clone, and a function namedfoo_callbackwith the completion type of an asyncfoo. Names in a family the runtime and the C value-buffer helpers reserve ({p}_contract_*,{p}_reader_*,{p}_writer_*,{p}_str_*,{p}_bytes_*, the{p}_buf_*codec names, and the runtime’s own symbols) collide too. - No parameter is named after a slot the C ABI adds (
self,ctx,out_err,callback,context,cancel_token).
# rejected: SymbolCollision
version: "0.13.0"
interfaces:
- name: Store
methods:
- { name: get, params: [{ name: key, type: string }], return: bytes }
functions:
- name: Store_get
params:
- { name: key, type: string }
return: bytes
A document with an unsupported version reports only
UnsupportedSchemaVersion.
Error catalog
| Code | Reported when |
|---|---|
UnsupportedSchemaVersion | version isn’t 0.13.0 |
InvalidIdentifier | a name isn’t a valid identifier |
ReservedKeyword | a name is a reserved word, or an error domain is named any |
DuplicateName | two declarations of the library share a name |
DuplicateErrorCodeName | two codes anywhere in the library share a name |
SymbolCollision | two declarations lower to the same C identifier, or one falls in a reserved family |
SlotCollision | a parameter has the name of a slot the C ABI adds |
DuplicateParamName | two parameters of a callable share a name |
CancellableNotAsync | a synchronous callable is cancellable |
UnknownErrorDomain | throws names something that isn’t an error domain |
AsyncIteratorReturn | an async function returns iter<T> |
DuplicateErrorCode | two codes in one domain share a value |
InvalidErrorCode | a code is zero or negative |
EmptyRecord | a record has no fields |
DuplicateRecordField | two fields of a record share a name |
RecursiveType | a record or rich enum contains itself by value |
EmptyEnum | an enum has no variants |
DuplicateEnumVariant | two variants of an enum share a name |
DuplicateEnumVariantField | two fields of a rich-enum variant share a name |
DuplicateEnumValue | two variants of an enum share a value |
EmptyInterface | an interface has no members |
DuplicateInterfaceMember | two members of an interface share a name |
ConstructorHasReturn | a constructor declares return |
AsyncConstructor | a constructor is async |
EmptyCallbackInterface | a callback interface has no methods |
DuplicateCallbackMethod | two methods of a callback interface share a name |
InvalidCallbackMethod | a callback method is async or cancellable, or returns an iterator |
UnknownTypeRef | a reference names no declaration |
ErrorDomainAsType | an error domain is used as a value type |
UnsupportedPrimitive | a reference names usize, isize, u128, i128, or char |
InvalidMapKey | a map key isn’t an integer, bool, string, or C-style enum |
InterfaceInInvalidPosition | an interface is used as a map key |
CallbackInterfaceInInvalidPosition | a callback interface appears other than as a parameter (bare or Cb?) |
ObjectInErrorPayload | an error code’s field reaches an interface, directly or through a record or rich enum |
IteratorInInvalidPosition | iter<T> appears other than as an outermost return |
A file that can’t be read, has no IDL extension, fails to parse, declares another schema version than the root, or closes an import cycle is reported before validation, with the file’s name.
Warnings
Warnings never fail validation; --warn reports them.
| Code | Fires when |
|---|---|
Undocumented | a top-level declaration has no doc:, so its bindings have no doc comment |
DeepNesting | a type nests composites more than three levels deep |
LargeEnumVariantCount | an enum has more than 100 variants |
C ABI Contract
This page is the normative description of the WeaveFFI C ABI, revision 6. The producer macros implement it, the C generator renders it as a header, and every other generator consumes it. Where another page disagrees with this one, this one wins.
Vocabulary
- Producer: the native library implementing the symbols (a Rust cdylib built with the producer macros, or a C, C++, or Zig library implementing the header).
- Consumer: generated bindings, or C code calling the header directly.
{p}: the library’s C symbol prefix from its identity, a lower-snake identifier (kvstore).{P}is the same prefix uppercased, used for macros (KVSTORE).- Run: a contiguous allocation of bytes that crosses the boundary (a string, bytes, a typed array, a value buffer, an error message or payload).
A library is one namespace: every record, enum, error domain, interface,
callback interface, and free function has a name unique across the library,
and every identifier the ABI defines starts with {p}_ (functions, types,
constants) or {P}_ (macros). There are no fixed weaveffi_* symbols, so
any number of WeaveFFI libraries can link into one process, statically or
dynamically.
One value, one C value
Every value crosses as exactly one C value, in every position: a parameter, a return, an async result, an iterator item, and a callback method’s parameter and return. Which C value is decided by the value’s family:
| Family | IDL types | C type |
|---|---|---|
| Direct | integers, f32, f64, bool, C-style enums | the scalar (int32_t, double, bool, …); an enum’s {p}_{E} is typedef int32_t |
| OptDirect | T? where T is Direct | {p}_opt_{prim}: struct { bool has; T value; }; an optional enum is a {p}_opt_i32 |
| Run | string, bytes, [i8] … [f64] (typed arrays), records, rich enums, and every other optional, list, and map | {p}_run: struct { const uint8_t* ptr; size_t len; } |
| Object | interfaces and Interface? | const {p}_{I}* as a callable’s parameter, {p}_{I}* elsewhere |
A run holds, by type:
string: UTF-8, never NUL-terminated;bytes: raw bytes;[i8],[i16],[i32],[i64],[u16],[u32],[u64],[f32],[f64](a typed array): the packed native elements,lena multiple of the element size andptraligned for the element ([bool]and[u8]aren’t typed arrays:[u8]isbytes, and[bool]is a value buffer);- anything else: a value buffer.
len always counts bytes. Null with length 0 is the empty run, and a
null pointer with a non-zero length is malformed.
A bool (and an OptDirect’s has) is a C bool, one byte; the producer
rejects any byte but 0 and 1 as a marshalling failure (-3). An
OptDirect’s value is 0 when has is false.
Two more kinds aren’t value types:
- A callback-interface parameter (
CborCb?, legal only as a parameter of a function or interface member) is a{p}_{Cb}struct,struct { void* ctx; const {p}_{Cb}_vtable* vtable; }, passed by value; a nullvtableis none (Cb?). - An iterator return (
iter<T>, legal only as a return) is an opaque{p}_{Iter}*(see Iterators).
Signatures
A synchronous callable is
R {symbol}([const {p}_{I}* self,] <one slot per parameter>, {p}_error* out_err);
where R is the return’s C type (void for none), the receiver self is
an instance method’s, and each parameter’s slot is named after the
parameter. A parameter may not be named self, ctx, out_err,
callback, context, or cancel_token (validation reports
SlotCollision).
| Declaration | C identifier |
|---|---|
function f | {p}_f |
interface I | type {p}_I; members {p}_I_{member}; {p}_I_clone, {p}_I_destroy |
async function f | launcher {p}_f (no suffix); completion type {p}_f_callback |
iterator returned by f | type {p}_{Owner_}{PascalF}Iterator, plus {Iter}_next and {Iter}_destroy |
C-style enum E, variant V | type {p}_E (typedef int32_t), constant {p}_E_V |
rich enum E, variant V | tag type {p}_E_Tag (typedef int32_t), constant {p}_E_V; struct {p}_E and its codecs in the buffer header |
record S | struct {p}_S and its codecs in the buffer header |
error domain D, code C | type {p}_D (typedef int32_t), constant {p}_D_C; for a code with fields, struct {p}_D_C_payload and its codecs in the buffer header |
callback interface Cb | argument struct {p}_Cb, vtable type {p}_Cb_vtable |
| a declaration’s contract | {p}_contract_{id:016x} (see The contract) |
{Owner_} is empty for a free function and the interface name plus _ for
a member, and the function name is converted to PascalCase:
stream_items is kitchen_sink_StreamItemsIterator, and Store.keys is
kvstore_Store_KeysIterator.
Enum, tag, and error-code types are typedef int32_t with their constants
in an anonymous enum, never typedef enum: a C enum’s size is the
compiler’s choice, and these values always cross as int32_t.
typedef int32_t kvstore_Kind;
enum { kvstore_Kind_Hot = 0, kvstore_Kind_Cold = 1 };
All names are computed once by the model and recorded in one symbol table;
validation fails with SymbolCollision if two declarations would produce
the same identifier, or one falls in a reserved family ({p}_contract_*,
and the buffer header’s {p}_reader_*, {p}_writer_*, {p}_str_*, and
{p}_bytes_*). The buffer header names its optional, list, and map codecs
{p}_buf_{stem} ({p}_buf_list_i32); those exact names are reserved too.
IDL spellings are never re-cased in C.
Load-time checks
A consumer makes two checks once, when it loads the library, before any other call, and refuses to load if either fails (with the language’s load or import error, or a catchable check function where loading itself can’t fail, as in Swift and Go).
The revision. {P}_ABI_VERSION in the header and {p}_abi_version() in
the library must be equal. The revision changes only when the runtime
surface, the value-buffer encoding, or a calling convention changes
incompatibly; it’s independent of the crate version and the IDL schema
version.
Revision 6 is designed to grow without a revision 7: new declarations, new callback methods (appended), and new error codes are additive.
The contract
Every declaration has a contract function:
uint64_t {p}_contract_{id:016x}(void); /* returns the declaration's hash */
A declaration is a function, an interface, each interface member (constructor, method, or static), a record, an enum, a callback interface, each callback method, an error domain, or each error code. Its
- id is the 64-bit FNV-1a hash of its dotted path, the name then a
member, method, or code (
open_store,Store,Store.get,Listener,Listener.on_put,KvError,KvError.NotFound), written as 16 lower-case hex digits in the symbol; - hash is the 64-bit FNV-1a hash of its canonical signature string.
FNV-1a 64 starts from 0xcbf29ce484222325 and, for each byte, XORs the byte
in and multiplies by 0x100000001b3, wrapping.
The canonical signature is computed from resolved types, never from source
spelling: type aliases are substituted, a custom type is its repr, [u8] is
bytes, and each type is written in its IDL spelling (i32, string,
[Contact], {string:i64}, Store?, Listener?, iter<Item>).
Parameter names, field names, documentation, deprecation text, and error
messages are excluded.
| Declaration | Canonical signature |
|---|---|
| function or interface member | {kind} {name}({type}, ...) -> {type}, where kind is function, constructor, method, or static and a missing return is void, followed by throws {Domain} or throws any, then async, then cancellable, each when set (a constructor’s return is its interface) |
| interface | interface {name} (each member has its own entry) |
| record | record {name} {{type}, ...}: field types only, in order |
| enum | enum {name} {{Variant} = {value}, ...}, a variant with fields followed by {{type}, ...} |
| callback interface | callback {name} (each method has its own entry) |
| callback method | callback_method #{slot} {name}({type}, ...) -> {type}, where slot is the method’s zero-based position in the vtable and a missing return is void, followed by throws {Domain} or throws any when set |
| error domain | errors {name} (each code has its own entry) |
| error code | code {Code} = {value}, a code with fields followed by {{type}, ...} |
For example, fn get(&self, key: String) -> Result<Entry, KvError> on
interface Store has the path Store.get and the signature method get(string) -> Entry throws KvError.
A consumer checks every declaration it was generated with: it calls the
declaration’s contract function and compares the result with the hash it
was generated with. A missing function fails with “Store.get is missing
from the library”; a different hash fails with “Store.get changed since
these bindings were generated”. Declarations the library has and the
consumer doesn’t are fine, so adding a declaration (a function, a method, a
record, an error code, or a callback method at the end of its interface)
never breaks a deployed binding. A consumer that links the library (C, C++,
Swift, Go) calls the functions directly, so a missing declaration fails to
link; one that loads it at run time resolves each function by name.
Variant and code names stay in their signatures because they’re values a consumer sees; parameter and field names don’t affect the encoding, so renaming one is ABI-neutral. The flip side is that swapping two parameters or fields of the same type passes the check too; treat that as a breaking change even though the check can’t see it.
The header declares every contract function, commented with its path and canonical signature, a checker, and a macro a hand-written producer defines them all with:
KVSTORE_API uint64_t kvstore_contract_dc5ad183936cb6fc(void); /* Store.get: method get(string) -> Entry throws KvError */
static inline const char* kvstore_contract_check(void); /* the path of the first mismatch, or NULL */
#define KVSTORE_DEFINE_CONTRACT ... /* defines every contract function */
Runtime surface
Every producer exports these symbols (weaveffi::export_runtime!() emits
them for a Rust producer):
#define {P}_ABI_VERSION 6u
uint32_t {p}_abi_version(void);
typedef struct {p}_run { const uint8_t* ptr; size_t len; } {p}_run;
typedef struct {p}_opt_i32 { bool has; int32_t value; } {p}_opt_i32; /* and one per scalar */
typedef struct {p}_error {
int32_t code; /* 0 ok; >0 domain code; <0 runtime code */
const uint8_t* message_ptr; /* UTF-8, NOT NUL-terminated, producer-owned */
size_t message_len;
const uint8_t* payload_ptr; /* the code's fields as a value buffer, or NULL */
size_t payload_len;
} {p}_error;
void {p}_error_set({p}_error* err, int32_t code,
const uint8_t* message_ptr, size_t message_len); /* copies */
void {p}_error_set_payload({p}_error* err, const uint8_t* ptr, size_t len); /* copies */
void {p}_error_clear({p}_error* err); /* frees message and payload; code = 0 */
void {p}_error_free({p}_error* err); /* clear, then free a heap-boxed error */
uint8_t* {p}_alloc(size_t len); /* a zero-filled 8-aligned run, NULL for 0 */
void {p}_run_free({p}_run run); /* returned runs and {p}_alloc runs */
typedef struct {p}_cancel_token {p}_cancel_token;
{p}_cancel_token* {p}_cancel_token_create(void); /* refcount 1 */
void {p}_cancel_token_cancel({p}_cancel_token* token); /* idempotent */
bool {p}_cancel_token_is_cancelled(const {p}_cancel_token* token);
void {p}_cancel_token_destroy({p}_cancel_token* token); /* drops one reference */
#define {P}_VTABLE_THREAD_AFFINE 1u /* a callback vtable flag; see below */
uint64_t {p}_debug_live(int32_t kind); /* leak counters */
There is one {p}_opt_{prim} per scalar: bool, i8, i16, i32, i64,
u8, u16, u32, u64, f32, and f64.
Every function accepts null where a pointer is optional (error_set,
error_set_payload, error_clear, error_free, the token functions,
_clone, _destroy) and treats it as a no-op; a null token reads as never
cancelled. {p}_run_free of the empty run is a no-op. {p}_error_set with
a null message_ptr (whatever the length) sets an empty message, and a
producer never fails on message bytes that aren’t UTF-8 (the Rust runtime
replaces them with U+FFFD), so reporting a failure never fails.
Every run the producer hands out (a string, bytes, typed-array, or value
buffer return; an error’s message and payload) and every {p}_alloc(len)
run is allocated with alignment 8, so a run can be read in place as any
element type. The consumer releases a returned run with {p}_run_free,
passing it back exactly as it got it; it never frees a run with its own
allocator. A consumer allocates a run with {p}_alloc(len) when it hands
memory to the producer (a callback method’s string, bytes, typed-array,
or buffer return, which the producer adopts) or, on wasm32, when it
stages an argument in the module’s linear memory. An error’s message and
payload belong to the error struct and are released by {p}_error_clear
or {p}_error_free, never by {p}_run_free.
{p}_debug_live(kind) reports live resources for leak checks: 0 objects,
1 foreign callbacks, 2 iterators, 3 cancel tokens, 4 runs (returned
and allocated ones not yet freed or adopted). Kind -1 returns 1 when the
producer counts at all and 0 when it doesn’t, so a harness can tell
“nothing is live” from “nothing is counted”; an unknown kind returns 0. A
Rust producer counts only with the leak-check feature; without it every
kind but -1 returns 0.
Errors
Every synchronous API symbol (a function or interface member, an iterator
launcher, and an iterator’s _next) takes a trailing {p}_error* out_err
after all inputs; _clone, _destroy, an iterator’s _destroy, async
launchers, and the runtime surface don’t. The call overwrites the slot
without reading it: on failure it stores the code, message, and payload and
returns a zero value (0, false, NULL, the empty run, an absent
optional) the caller must not use; on success it stores a cleared error. So
the caller may pass uninitialized memory, and after reading a failure
releases its message and payload with {p}_error_clear (a struct reused for
many calls must be cleared after each failure, or its message leaks).
The message is message_len bytes of UTF-8 at message_ptr, without a NUL
terminator (a consumer that needs a C string copies it). An empty message is
a null message_ptr with length 0, even on failure.
| Code | Meaning |
|---|---|
0 | success; every pointer is null and every length 0 |
> 0 | a code of the error domain the callable throws; payload_ptr/payload_len hold the code’s fields, if any |
-1 | untyped: the failure of a throws: any callable, or an async call the executor couldn’t start |
-2 | the producer panicked |
-3 | marshalling failure: an argument couldn’t be lifted (a null run with a non-zero length, a null self or object where one is required, invalid UTF-8, a bool byte other than 0 or 1, an out-of-range enum value or integer conversion, a misaligned or ragged typed array, a malformed buffer, a map with a repeated key, an incomplete vtable header, an iterator advanced concurrently) |
-4 | a consumer’s callback-interface implementation failed, doesn’t implement the method called, or was called off its thread (see Callback interfaces) |
-5 | cancelled (async completions only) |
What a callable may report depends on its throws:
- No
throws. Only runtime codes. A non-zero code is a producer bug or a failed callback; consumers trap on it rather than report a typed error (see Errors and memory). throws: {Domain}. The domain’s positive codes plus runtime codes. Domains are open: a consumer that receives a positive code it wasn’t generated with (the producer gained a code since) maps it to the domain’s base error type with the code and message preserved, never to a crash or a generic failure. It discards that code’s payload without decoding it, which is why an error code’s fields never carry an object (validation reportsObjectInErrorPayload).throws: any. Code-1with a message, plus runtime codes; never a positive code.
A producer lifts every argument of a call before it reports the first
one that failed, so the inputs it adopts (a callback argument, the object
tokens in a value buffer) are adopted and released even when another
argument, or a null self, fails.
Objects
Objects are reference counted by the producer. A {p}_{I}* is one
strong reference. _clone returns another strong reference to the same
object (the pointer value is unchanged); _destroy releases one, and the
object is dropped with the last reference. A consumer may hold any number of
references and use them from any thread.
| Position | Rule |
|---|---|
parameter (const {p}_{I}*) | borrowed for the call; the producer takes its own reference if it retains the object |
| return, async result, iterator element | one strong reference moves to the consumer |
| callback method argument | one strong reference moves to the consumer |
| callback method return | one strong reference moves to the producer |
| object token inside a value buffer | carries one strong reference; the reader adopts it |
A consumer encoding an object into a buffer writes a fresh reference from
_clone. An in-flight async call holds its own reference, so releasing a
wrapper while a call is pending is safe.
Callback interfaces
typedef struct {p}_{Cb}_vtable {p}_{Cb}_vtable;
typedef struct {p}_{Cb} { void* ctx; const {p}_{Cb}_vtable* vtable; } {p}_{Cb};
struct {p}_{Cb}_vtable {
uint32_t size; /* sizeof the vtable, as the consumer compiled it */
uint32_t flags; /* 0, or {P}_VTABLE_THREAD_AFFINE */
void (*free)(void* ctx); /* always first, at a fixed offset */
/* one entry per method, in declaration order: */
R (*{method})(void* ctx, <one slot per parameter>, {p}_error* out_err);
};
A callback interface has no exported symbols; it lowers to an argument
struct and a vtable type. The consumer passes a ctx it owns and a pointer
to a vtable that outlives the producer’s use of it (in practice, one static
vtable per interface), with size set to sizeof the vtable.
Vtables are open. The producer accepts any vtable whose header is
complete (size at least the header’s), so a consumer generated before a
method was appended keeps working: when the producer calls a method that
lies past the consumer’s size, or whose entry is null, the call fails with
-4 and a message naming the method, without calling anything. A vtable
shorter than its header fails the call that passed it with -3. Methods are
only ever appended; reordering or inserting one moves slots and fails the
contract check.
The producer may call any entry, any number of times, from any thread, until
it calls free(ctx) exactly once, after which it never touches ctx again.
free may also run on any producer thread, and a null free is skipped.
Thread affinity. Bit 0 of flags is {P}_VTABLE_THREAD_AFFINE
(1u); every other bit is reserved and 0. With the flag set, a method
that returns a value may only be called on the thread that passed the
vtable to the producer. The producer records that thread when it adopts the
vtable and fails such a call from any other thread with -4 and the message
callback called off its thread, without calling the method. void
methods and free may still be called from any thread. The Dart target sets
the flag; every other target passes 0.
Arguments are lent for the duration of the call (runs are borrowed), except objects, which move one strong reference to the consumer.
Returns are the C return of the method. A run the consumer returns is one
it allocated with {p}_alloc(len), which the producer adopts and frees; an
object it returns is a fresh strong reference (_clone) the producer
adopts. The producer adopts whatever the method returned whether or not it
failed, so a consumer that fails after allocating doesn’t leak. A return it
can’t accept (a string that isn’t UTF-8, a null I, an out-of-range enum
value, a malformed buffer) fails the method with -3.
Errors. A consumer implementation that fails reports it with
{p}_error_set(out_err, code, message_ptr, message_len), which copies a
borrowed message with the producer’s allocator; it never writes the
message itself. What it reports follows the method’s throws:
throws: {Domain}: a positive code of that domain, attaching the code’s fields encoded as a value buffer with{p}_error_set_payload, which reaches the producer as that typed error; or-1with a message for any other failure.throws: any:-1with a message.- No
throws:-4with a message (any non-zero code is accepted).
Anything but a declared code with a payload that decodes reaches the
producer as a callback failure, -4 with the consumer’s message, so a
consumer bug can’t masquerade as a domain error. A Rust producer’s method
returns Result<T, E>, its E built from a typed code or, for a callback
failure, with From<weaveffi::ForeignError>.
Async functions
typedef void (*{p}_{f}_callback)(void* context, {p}_error* err, R result);
void {p}_{f}([self,] <one slot per parameter>, [{p}_cancel_token* cancel_token,]
{p}_{f}_callback callback, void* context);
result is the return’s one C value, as for a synchronous return, and is
absent for a function that returns nothing (the completion is then
void (*)(void* context, {p}_error* err)). err is NULL on success;
otherwise it’s heap-boxed, owned by the consumer, and released with
{p}_error_free, and result is the zero value. The launcher has no
out_err; every failure, including an input marshalling failure, is
delivered through the completion.
The runtime guarantees:
- The completion fires exactly once, from any thread, possibly before
the launcher returns. A null
callbackdiscards the result. - The launcher takes everything it needs before returning (it copies runs
and retains objects and
self), so the consumer may release its arguments as soon as it returns. - If the executor can’t take the call (it failed to start, or a custom
executor panicked), the completion fires with
-1and a message. - If the executor drops the future before it completes, the completion
fires with
-5. - For a
cancellablefunction, the producer takes its own reference on the token at launch; the consumer may cancel and destroy its reference at any time afterward. Cancelling wakes the future; the runtime then drops it and completes with-5and the messagecancelled, unless it already completed. Producer code may still poll the token for cooperative cleanup.
Which threads drive the futures is the producer’s business; see Async for the Rust runtime’s executors.
Iterators
{Iter}* launcher([self,] <one slot per parameter>, {p}_error* out_err);
int32_t {Iter}_next({Iter}* iter, T* out_item, {p}_error* out_err); /* 1 item, 0 done */
void {Iter}_destroy({Iter}* iter);
T is the element’s one C value, and each element follows the return rules
of its family. _next checks that out_item is non-null before it pulls an
element (failing with -3 otherwise), so a bad call never loses one.
_next never blocks on another _next: a call that arrives while the same
iterator is being advanced (from another thread, or re-entrantly from inside
the producer’s own next) fails with -3. The consumer calls _destroy
exactly once, after exhaustion or to abandon the iteration.
Value buffers
Buffers have one encoding, specified in Value Buffers:
little-endian, packed, u32 lengths and counts, object tokens as u64.
Error payloads use the same encoding, and so do optional scalars and
numeric lists nested inside a buffer (a record’s i64? field is a presence
byte and a value; its [f64] field is a count and packed elements).
Producers in other languages
A producer implementing a generated header exports:
- every function the header declares for the API;
- every contract function, which the header’s
{P}_DEFINE_CONTRACTdefines; - the runtime surface above, with
{p}_abi_versionreturning{P}_ABI_VERSION.
#define CALCULATOR_BUILD
#include "calculator.h"
CALCULATOR_DEFINE_CONTRACT
The producer owns every allocation it hands out and adopts every run a
consumer allocates, so error_clear, error_free, run_free, and the
adoption of a callback’s returned run must all use the allocator alloc
uses, with alignment 8. It honors {P}_VTABLE_THREAD_AFFINE and accepts
short vtables. When building the library, define {P}_BUILD so the
header’s {P}_API macro exports symbols on Windows.
conformance/c/producer.c is a complete example.
Value Buffers
Records, rich enums, optionals, lists, maps, and error payloads cross the C
ABI by value, serialized in one compact binary format. A buffered value is
one {p}_run however deeply it nests. This page is the normative wire
format every generator and the Rust runtime implement.
Which types are buffered
At a call boundary (a parameter, a return, an async result, an iterator item, a callback argument or return), these types cross as a value buffer in a run:
- a record;
- a rich enum (any variant has fields);
{K:V};[T], except[u8](which isbytes) and a list of a fixed-width number ([i8],[i16],[i32],[i64],[u16],[u32],[u64],[f32],[f64]), which is a typed array: a run of the packed elements;T?, except an optional scalar or C-style enum (a{p}_opt_*struct),Interface?(a nullable object pointer), andCb?(an optional callback parameter, whose null vtable means none).
Everything else keeps its own C value at the top level (see the
C ABI contract): scalars by value, strings,
bytes, and typed arrays as runs of their own bytes, objects as pointers. Any
of them may appear inside a buffer, and there they all use the encoding
below: a record’s i64? field is a flag byte and a value, and its [f64]
field is a count and packed elements. Iterators and callback interfaces
never appear inside a buffer; validation rejects them there.
Encoding
All multi-byte values are little-endian, packed back to back with no padding
or alignment. Lengths and counts are u32, so a single string, byte run, or
collection holds at most 232 − 1 entries; an
encoder refuses to write more rather than truncate.
| IDL type | Encoding |
|---|---|
bool | 1 byte: 0 or 1 |
i8, u8 | 1 byte |
i16, u16 | 2 bytes |
i32, u32 | 4 bytes |
i64, u64 | 8 bytes |
f32, f64 | 4 or 8 bytes of IEEE 754 bits (NaN payloads, infinities, and -0 round-trip) |
| C-style enum | i32 value |
| interface | u64 object token |
string | u32 byte length, then UTF-8 bytes (no terminator) |
bytes | u32 length, then raw bytes |
T? | 1 flag byte (0 absent, 1 present), then the value if present |
[T] | u32 count, then each element |
{K:V} | u32 count, then alternating key and value; no key appears twice |
| record | each field, in declaration order |
| rich enum | i32 tag (the variant’s value), then the variant’s fields in order |
| error payload | the code’s fields, in declaration order |
The format is compositional, so {string:[T?]}, records inside records, and
lists of rich enums need no special cases. A map’s encoding never repeats a
key, so no entry can silently disappear between the two sides. [u8] is
canonicalized to bytes at parse time; the two encode identically.
Example: a Point { x: f64, y: f64 } with x = 1.5, y = -2.0 is 16
bytes, 00 00 00 00 00 00 F8 3F 00 00 00 00 00 00 00 C0; a [string] of
["hi"] is 01 00 00 00 02 00 00 00 68 69.
Decoding
A decoder rejects a buffer that:
- ends in the middle of a value;
- holds a
boolor optional flag byte other than0or1; - holds invalid UTF-8 in a string;
- declares a string or byte length larger than the bytes remaining;
- holds an enum value or rich-enum tag that isn’t declared;
- repeats a key in a map;
- has bytes left over after the complete value.
A collection count is not checked against the bytes remaining, because an
element’s encoding can be empty; a decoder caps how much it preallocates
from a count instead, so a hostile count fails when the elements run out.
A malformed buffer is a contract violation between two sides generated from
one definition, so it’s reported as the marshalling code -3, never as a
domain error.
Objects
An interface value inside a buffer is an object token: the object
pointer widened to u64 (zero-extended on 32-bit targets). A token carries
exactly one strong reference, in either direction.
- Writing. The encoder owns the reference it writes. A consumer holding a
wrapper calls
_cloneand writes the returned pointer, keeping its own reference; a Rust producer writes a clonedArc. - Reading. The decoder adopts the reference: a consumer wraps it in a new
object wrapper, a Rust producer turns it back into an
Arc. - Failure. If decoding fails partway, the reader releases every token it already adopted; the writer has no further responsibility once the buffer is handed over.
- Single use. Because each token is one reference, a buffer holding objects is decoded exactly once. Bindings encode a fresh buffer per call.
A zero token is invalid in a non-optional position; Interface? inside a
buffer uses the optional flag byte followed by the token.
An error payload never carries object tokens: validation rejects an error
code whose fields reach an interface (ObjectInErrorPayload), because a
consumer that doesn’t know a code discards its payload undecoded, and a
Rust producer decodes a callback’s payload with a reader that refuses every
token.
Runs and ownership
A buffer the producer hands out (a return, an iterator item, an async
result) is a run allocated with alignment 8 and released with
{p}_run_free; an error payload belongs to the error and is released with
it. A buffer a consumer returns from a callback method is a run it allocates
with {p}_alloc(len), which the producer adopts. A buffer a consumer passes
as a parameter is its own memory, borrowed for the call, with no alignment
requirement: values inside a buffer are packed and read byte-wise.
| Position | C value | Owner |
|---|---|---|
| parameter | {p}_run | the caller; borrowed for the call |
| return | {p}_run | the consumer; release with {p}_run_free |
| iterator item | {p}_run written to *out_item | the consumer, per item |
| async result | the completion’s {p}_run result | the consumer |
| callback method argument | {p}_run | the producer; borrowed for the call |
| callback method return | {p}_run | a {p}_alloc run the producer adopts |
| error payload | payload_ptr, payload_len in {p}_error | released by {p}_error_clear or {p}_error_free |
Object tokens inside any of these move their reference to whoever decodes them, including the consumer decoding a callback argument.
What generators emit
Each binding ships a small private codec (a writer and a reader for the
table above) plus one encode and one decode routine per record and rich enum,
generated from the definition so field order is fixed at generation time.
Optionals, lists, and maps nested in buffers each get one codec per distinct
shape, named by one canonical stem shared by every target (list_i32,
opt_Item, map_string_list_i64); the C buffer header names them
{p}_buf_{stem}. Lists of bytes and of fixed-width numbers (every integer
and float type, but not bool, whose bytes must be validated) encode and
decode with a single copy where the platform is little-endian. The codec
sample’s conformance lane checks every binding’s codec against the Rust
runtime’s, in both directions.
Naming
Every name WeaveFFI emits derives from two things: the library’s identity (what the library is called) and the IDL names (what the API calls things). This page states both sets of rules.
Identity
The CLI resolves one identity per library from weaveffi.toml and, for a
Rust producer, Cargo.toml (the full rules are in
Project Configuration):
| Field | Meaning | Rust producer | IDL |
|---|---|---|---|
name | package name as published | [package] name, else the crate’s package name | [package] name, else the input file stem |
prefix | C symbol prefix | the crate’s library name | [package] c_prefix, else snake(name) |
library | native library base name | same as prefix | [package] library, else snake(name) |
version, description, license, authors, homepage, repository | metadata | [package], falling back to Cargo.toml | [package] |
Two conversions turn an arbitrary name into identifiers:
- snake: lowercase ASCII letters and digits, with every run of other
characters collapsed to one
_and leading and trailing_dropped; a leading digit gets alib_prefix.my-kv.storebecomesmy_kv_store,3d-enginebecomeslib_3d_engine. - PascalCase: each run of letters and digits starts a word whose first
letter is uppercased, and existing capitals are kept; a leading digit gets
an
Nprefix.my-kv.storebecomesMyKvStore.
{P} is the prefix uppercased. A c_prefix you set is itself passed
through snake. Setting c_prefix or library for a Rust producer is an
error, because the attributes derive the prefix from the crate. A library
read on its own with --library (no crate or IDL) takes its prefix from its
embedded metadata, its library from its file name, and its name from
[package] name, else the prefix.
Package names
Each target names its package, module, or namespace after the identity, and
a [generators.<target>] table can override it with name (see
Project Configuration). By default:
| Target | Default names |
|---|---|
| C | header {library}.h (and {library}_buffer.h); include guard {P}_H; export macro {P}_API |
| C++ | header {library}.hpp, which includes {library}.h; one namespace {library} |
| Swift | SwiftPM package, product, and module PascalCase(name) |
| Kotlin | package {prefix}; free functions on an object named PascalCase(name) |
| Node.js, WebAssembly | npm package {name} |
| Python | distribution {name}; import package {prefix} |
| .NET | namespace, assembly, and NuGet id PascalCase(name); free functions on the static class {Namespace}Library |
| Dart | package {prefix} |
| Go | module path {name}; package {prefix} without its underscores |
| Ruby | gem {name}; module PascalCase(name) |
Each language page is authoritative for its names and their overrides. For
the kvstore sample (crate kvstore) that’s kvstore.h, the Swift module
Kvstore, and import kvstore in Python.
Library loading. Every target finds the native library by its library
name using the platform’s file naming (lib{library}.dylib,
lib{library}.so, {library}.dll). The targets that load the library at
run time also accept an explicit path in the environment variable
{P}_LIBRARY (for example KVSTORE_LIBRARY), which wins over bundled and
system copies; the targets that link it when they’re built (C, C++, Swift,
and Go) find it through the platform linker.
Nothing a generator emits is named after WeaveFFI; the only mentions are
comments (the generated-file header and notes on regenerating or
packaging) and the file name of the Swift runtime source,
WeaveFFIRuntime.swift, which declares nothing named after WeaveFFI. Two libraries built with WeaveFFI therefore never collide in
symbols, packages, types, or environment variables.
One namespace
A library is one namespace. Record, enum, error domain, interface, callback
interface, and free-function names are unique across the whole library
(DuplicateName), and error-code names are unique across every domain
(DuplicateErrorCodeName). That holds however the definition is split: an
IDL across files with imports:, a Rust crate across modules and files. A
type reference is therefore always the bare name. Member names (parameters,
fields, variants, interface members, and callback methods) are scoped to
their owner.
C identifiers
C identifiers are the prefix and the IDL name, verbatim: kvstore_open_store
for a function, kvstore_Store_open for a member, kvstore_KvError_KeyNotFound
for an error code. IDL names are never re-cased in C, except that an
iterator type’s function part is PascalCase (kvstore_Store_KeysIterator
for Store.keys). The full table is in the
C ABI contract; validation rejects any API in which two
declarations produce the same identifier (SymbolCollision).
Identifiers in generated code
IDL names are expected in snake_case for functions, parameters, and
fields, and in PascalCase for types, variants, and error codes. The
validator only requires identifiers, so other styles are re-cased on a
best-effort basis.
Functions, methods, parameters, and fields follow each language’s convention:
| Target | Style | get_stats, created_at |
|---|---|---|
| C, C++, Python, Ruby | snake_case | get_stats, created_at |
| Swift, Kotlin, Node.js, WebAssembly, Dart | camelCase | getStats, createdAt |
| Go, .NET | PascalCase | GetStats, CreatedAt |
Types (records, enums, interfaces, callback interfaces, error domains)
keep their IDL names in every target, except where a language idiom adds a
prefix or suffix (an I on a .NET interface, for example). C-style enum
variants follow the target’s enum idiom (.volatile in Swift, say).
Constructors. A constructor named new becomes the language’s
constructor (init, __init__, initialize, a C++ or C# constructor);
other constructors become static factories (Store.open). Each language
page describes its layout.
Errors
Each target has a root error type and one type (or case) per error domain
and code, named from the IDL with at most one idiomatic suffix (Error or
Exception). The root is Error in C++, Python, Go, and Ruby (Python’s is
{PascalName}Error when the API declares its own Error),
{Module}RuntimeError in Swift, FfiException in Kotlin, and
NativeException in .NET and Dart. Node.js and WebAssembly name it after
the package (KvstoreError), or add Library when a declaration already
has that name (CodecLibraryError beside the codec sample’s CodecError
domain). Every target applies one shared
rule (weaveffi_model::errors::type_name): convert the name to PascalCase,
strip one trailing Exceptions, Exception, Errors, or Error, then add
the target’s suffix. So KvError stays KvError (or becomes
KvException), KitchenErrors becomes KitchenError, Failure becomes
FailureError, and a code KEY_NOT_FOUND becomes KeyNotFoundError. Write
code names without a suffix (KeyNotFound, not KeyNotFoundError) and let
the generator add it.
Reserved words
A name that’s a keyword in the target language gains a trailing _ (type
becomes type_), a rule that’s stable under repetition. (Ruby allows
keywords as method names, so its members keep them: entry.end.) An interface member
whose target spelling matches a member the generated object wrapper declares
or inherits (its release method, say) gains a trailing _ as well, so the
wrapper keeps working; each language page lists its reserved member names.
A free function whose name clashes with another name its target emits
gains a trailing _ too: in Go, a free function spelled like a type, a
constructor, or a static (the kvstore sample’s async open_store is
OpenStore_, because the constructor Store.open is OpenStore), and in
Node.js and WebAssembly a function named init, which the WebAssembly
package exports itself (init_).
In C, members are prefixed symbols, but a member named clone or destroy
lowers to the same symbol as the interface’s own _clone or _destroy, so
validation rejects it (SymbolCollision).
Target names
A target is named after what its consumer identifies with: the language when
the output is idiomatic to one language (swift, python, kotlin), and
the runtime when several languages consume it equally or two targets share a
language (dotnet serves C#, F#, and Visual Basic; node and wasm both
emit JavaScript). A deployment platform is never a target name: kotlin
covers Android and the desktop JVM. The same token names the --target
value, the [generators.<target>] table, the output directory, and the page
under Generators.
Generators
WeaveFFI ships eleven generators, one per target, and every one implements
the whole IDL surface of schema 0.13.0 on C ABI revision 6: records, C-style
and rich enums, reference-counted objects in every position, callback
interfaces, optionals, lists, maps, open error domains and throws: any,
async functions with cancellation, and lazy iterators. Each generator names
its output from the library’s identity, binds to
the native library {library}, checks the ABI revision and the contract of
every declaration it was generated with when it loads the library
(reporting a mismatch as a catchable error), and produces a tree under
{out}/{target}/ that builds with the language’s normal tooling.
No target needs compiled glue of its own: each binds the C ABI through its
language’s own foreign-function interface, so weaveffi build compiles
only the producer’s library. The targets that link the library when the
consumer builds them (C, C++, Swift, and Go) call its functions directly, so
a missing declaration fails to link; the others load it at run time, resolve
each function by name, and accept a full path to it in the {P}_LIBRARY
environment variable (KVSTORE_LIBRARY).
Tiers
Every target passes the same conformance lanes. Tier 1 targets (C, C++, Swift, Kotlin, Python, Node.js, and .NET) carry the stability promise and get ABI work first. Tier 2 targets (Go, Ruby, Dart, and WebAssembly) may lag a release behind on new ABI features. See Stability.
Capability matrix
| Target | Tier | Reaches the C ABI through | Finds the library | A failed load-time check |
|---|---|---|---|---|
| C | 1 | the header {library}.h (and {library}_buffer.h) | linked when built | {p}_contract_check() returns the first mismatch |
| C++ | 1 | a C++ API over the C header | linked when built | a catchable error |
| Swift | 1 | a SwiftPM package over the C header | linked when built | a check function that throws |
| Kotlin | 1 | JNA | loaded at run time | the load error |
| Node.js | 1 | koffi | loaded at run time | the load error |
| Python | 1 | ctypes, plus libffi closures for callback methods that return a structure | loaded at run time | the import error |
| .NET | 1 | P/Invoke ([LibraryImport]) | loaded at run time | the load error |
| Go | 2 | cgo | linked when built | a check function that returns an error |
| Ruby | 2 | the ffi gem | loaded at run time | the load error |
| Dart | 2 | dart:ffi, with thread-affine callback vtables | loaded at run time | the load error |
| WebAssembly | 2 | the wasm32 module’s exports | the .wasm module, loaded at run time | the load error |
The language pages are authoritative for each target’s package layout, type mapping, names, async and cancellation surface, and toolchain versions. Notes that apply across targets:
- Objects. Every wrapper owns one strong reference and keeps itself alive for the duration of each native call, so it can’t be released mid-call. Disposing twice is a no-op; using a disposed wrapper raises the target’s usage error.
- Errors. A callable that throws a domain raises that domain’s typed
error; a code the bindings don’t know (one a newer library added) raises
the domain’s base error with its code and message. A
throws: anycallable raises the target’s root error type with code-1. A non-zero code from a callable that declares no errors is a trap. - Callbacks. Callback methods may be invoked from any producer thread
(Dart’s value-returning methods excepted). An implementation that raises a
code of the method’s own domain reports it with its fields; any other
failure is reported as
-1with its message, or as-4from a method that declares no errors. An object passed to a callback is adopted by the implementation. Each binding sets its vtable’ssize, so a library that gained callback methods still accepts it. - Async. A cancelled call raises the language’s cancellation error. Go and Ruby block the calling goroutine or thread while the native work runs elsewhere. See Async and Cancellation.
Fixture compile checks
Snapshot tests pin the generated text; the fixture check proves it’s valid
code. scripts/check-fixtures.sh <target> generates every fixture in
crates/weaveffi-cli/tests/fixtures/ (kitchen_sink, edge_cases,
imports, docs_everywhere, shapes) together with the C header, then
runs scripts/fixtures/<target>.sh, which compiles or type-checks the
output with the target’s own toolchain. CI runs one job per target. A
missing tool is a printed skip locally and a failure when CI=true.
Conformance lanes
conformance/run.sh is the behavioral gate. It builds the three
sample producers with leak counting enabled, runs weaveffi generate on each sample crate, reading the API from that same build
(--library), and then runs conformance/<lang>/run.sh for every language.
Each language declares one lane per sample (python-calculator,
python-codec, python-kvstore, and so on); a lane compiles and runs that
sample’s consumer under a timeout. The consumer binds only through the
generated package, asserts concrete results, and checks that every
{p}_debug_live counter is zero at exit after forcing its garbage
collector:
- calculator: the getting-started surface (a call, typed and untyped errors, a string in and out, an optional scalar, and typed arrays).
- codec: the shared-vector loop. Fetch each of the producer’s test
vectors, decode it, pass it back to
check_vector, and echo each primitive through the matching family; then check a few vectors built from literals. - kvstore: every feature, including callbacks implemented in the consumer’s language, cancellation, and iterators.
The C lanes also implement a producer by hand (c-producer-exports) and
check that it exports every symbol the header requires.
bash conformance/run.sh # every lane
ONLY=python bash conformance/run.sh # one language
ONLY=c,go-kvstore SKIP_GEN=1 bash conformance/run.sh
SKIP excludes lanes, SKIP_GEN=1 reuses previously generated bindings,
and LANE_TIMEOUT sets the per-lane limit in seconds (default 300). A
missing toolchain skips its language with a note locally and fails it when
CI=true. CI runs every language on Linux and macOS.
C
The C target emits the canonical header for a library’s C ABI (revision 5). Every other target binds to the symbols it declares (the C++, Swift, and Go targets include it, and the Kotlin JNI shim and the Node.js addon compile against it), and a C or C++ producer implementing an IDL by hand implements exactly those symbols. Alongside it, the target emits a helper header with C structs and codecs for the API’s value buffers, so a C consumer never encodes the wire format by hand.
C is a Tier 1 target: it tracks every ABI revision as it lands and runs the full conformance suite in CI.
What gets generated
For the kvstore sample (library kvstore, prefix kvstore):
c/
├── kvstore.h # the ABI: runtime, types, and function prototypes
└── kvstore_buffer.h # C structs and static inline codecs for value buffers
The ABI header is {library}.h, with include guard {PREFIX}_H and the
visibility macro {PREFIX}_API. The helper is {library}_buffer.h; it’s
emitted only when some type crosses the ABI as a value buffer, and it can be
turned off:
[generators.c]
buffer_helpers = false
weaveffi package writes kvstore-{version}-c.tar.gz: the same headers
under include/, the library of every platform built under
lib/<platform>/ (with the import library on Windows), a README, and a
CMakeLists.txt (CMake 3.15 or later) that exposes the host’s library as
the imported target kvstore::kvstore (see
Packaging).
Build and load
Both headers are plain C11 that also compiles as C++. Point the compiler at
the c/ directory and link the producer’s library:
cc -std=c11 -I bindings/c app.c -L target/release -lkvstore -o app
C links the library at build time, so the platform loader finds it at run
time (LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PATH, or an rpath). The
{PREFIX}_LIBRARY override (KVSTORE_LIBRARY) applies to targets that load
the library dynamically; a C program that wants it calls dlopen itself.
Every C identifier starts with the prefix, so any number of WeaveFFI libraries link into one program. Before its first call, a consumer should check the ABI revision and the contract it was generated against:
if (kvstore_abi_version() != KVSTORE_ABI_VERSION) {
fprintf(stderr, "kvstore: library does not match kvstore.h's ABI revision\n");
exit(1);
}
if (kvstore_kv_contract_check() != 0) {
fprintf(stderr, "kvstore: library does not match kvstore.h (module kv)\n");
exit(1);
}
Each top-level module has a contract table: the library exports
{p}_{m}_contract(size_t* out_len), and the header defines the entries the
bindings were generated with as {P}_{M}_CONTRACT (each commented with its
declaration’s dotted path and canonical signature), their count as
{P}_{M}_CONTRACT_LEN, and a
static inline uint64_t {p}_{m}_contract_check(void). The checker returns
0 when every expected entry is in the library’s table with an equal hash,
and otherwise the id of the first one that’s missing or changed, which you
can look up in the macro to name the declaration. A library with extra
entries passes, so adding a declaration or an error code, or appending a
callback method, doesn’t break existing consumers.
See load-time checks.
Type mapping
| IDL type | Parameter x | Return | In {library}_buffer.h |
|---|---|---|---|
i8 to u64, f32, f64 | int8_t to uint64_t, float, double | same | same |
bool | bool | bool | bool |
| C-style enum | {p}_{path}_{Enum} (typedef int32_t) | same | same |
T? of one of those | bool has_x, T x | bool (present) + T* out_value | T* (NULL is absent) |
[i8] [i16] [i32] [i64] [u16] [u32] [u64] [f32] [f64] | const T* x_ptr, size_t x_len (element count) | T* + size_t* out_len (element count) | struct {p}_list_{T} |
string | const uint8_t* x_ptr, size_t x_len | const uint8_t* + size_t* out_len | {p}_str |
bytes | const uint8_t* x_ptr, size_t x_len | const uint8_t* + size_t* out_len | {p}_bytes |
| record, rich enum | value buffer (ptr, len) | value buffer + out_len | struct {p}_{path}_{Name} |
any other [T], {K:V} | value buffer | value buffer | structs {p}_list_{T}, {p}_map_{K}_{V} |
any other T? | value buffer | value buffer | T* (NULL is absent) |
interface I | const {p}_{path}_I* (borrowed) | {p}_{path}_I* (owned) | {p}_{path}_I* |
I? | const {p}_{path}_I* (NULL is absent) | {p}_{path}_I* | {p}_{path}_I* |
callback interface, Cb? | void* x_ctx, const {p}_{path}_{Cb}_vtable* x_vtable (NULL vtable is absent for Cb?) | not allowed | not allowed |
iter<T> | not allowed | iterator handle | not applicable |
Enums, rich-enum tags, and error-code types are typedef int32_t with their
constants in an anonymous enum, so their size never depends on the
compiler:
/** Task priority levels */
typedef int32_t kitchen_sink_kitchen_Priority;
enum {
/** Low priority */
kitchen_sink_kitchen_Priority_Low = 0,
/** Normal priority */
kitchen_sink_kitchen_Priority_Normal = 1,
/** High priority */
kitchen_sink_kitchen_Priority_High = 2
};
An optional scalar or enum (OptDirect) crosses directly: a parameter is a
presence flag plus the value (pass 0 when absent), and a return is a
bool C return with the value in a trailing out slot:
KITCHEN_SINK_API bool kitchen_sink_kitchen_opt_i32_id(bool has_x, int32_t x, int32_t* out_value, kitchen_sink_error* out_err);
int32_t value = 0;
if (kitchen_sink_kitchen_opt_i32_id(true, 42, &value, &err)) {
/* present: value == 42 */
}
A list of fixed-width numbers (Slice) crosses as a typed array: pass your
array and its element count, borrowed for the call and aligned for its
element type. A returned array is the producer’s run, released with
{p}_free_bytes and its size in bytes:
KITCHEN_SINK_API int32_t* kitchen_sink_kitchen_scale_i32(const int32_t* xs_ptr, size_t xs_len, int32_t factor, size_t* out_len, kitchen_sink_error* out_err);
int32_t xs[3] = {1, 2, 3};
size_t n = 0;
int32_t* scaled = kitchen_sink_kitchen_scale_i32(xs, 3, 10, &n, &err);
/* ... use scaled[0 .. n) ... */
kitchen_sink_free_bytes((uint8_t*)scaled, n * sizeof(int32_t));
Strings are UTF-8 without a NUL terminator and may contain NUL bytes. A
parameter’s pointer may be NULL when its length is 0; a NULL pointer
with a nonzero length, invalid UTF-8, or a misaligned typed array fails the
call with code -3. Every returned string, byte string, value buffer, and
typed array is owned by the consumer and released with
{p}_free_bytes(ptr, byte_len); NULL with length 0 is the empty value.
Every run the producer returns is 8-aligned.
Value buffers and {library}_buffer.h
Records, rich enums, maps, and the lists and optionals that don’t cross
directly are one serialized value buffer.
The helper header renders each record as a struct (from the kitchen_sink
fixture):
struct kitchen_sink_kitchen_Item {
/** Stable identifier */
int64_t id;
/** Display name */
kitchen_sink_str name;
/** Initial count */
int32_t count;
/** Whether the item is enabled */
bool enabled;
/** Scaling ratio */
double ratio;
uint32_t nick;
kitchen_sink_bytes payload;
kitchen_sink_list_string tags;
kitchen_sink_map_string_string attrs;
int64_t* parent;
/** Cross-module struct reference */
kitchen_sink_shared_Token token;
kitchen_sink_kitchen_Priority priority;
/** An optional object inside a record */
kitchen_sink_kitchen_Gadget* gadget;
};
A rich enum is a tag (its {p}_{path}_{Enum}_Tag constant) plus a union
as with one struct per variant that has fields. Inside a record, an
optional scalar is a pointer (int64_t* parent) and a numeric list is a
{p}_list_{T} struct: the direct OptDirect and Slice slots apply only at a
call boundary. Each of these types, and each optional shape, gets four
static inline functions:
static inline void kitchen_sink_kitchen_Item_write(kitchen_sink_writer* w, const kitchen_sink_kitchen_Item* v);
static inline void kitchen_sink_kitchen_Item_read(kitchen_sink_reader* r, kitchen_sink_kitchen_Item* out);
static inline bool kitchen_sink_kitchen_Item_decode(const uint8_t* ptr, size_t len, kitchen_sink_kitchen_Item* out);
static inline void kitchen_sink_kitchen_Item_free(kitchen_sink_kitchen_Item* v);
To pass a value, write it into a zeroed {p}_writer and pass ptr and
len. To read a returned buffer, decode it, release the buffer, and free
the decoded value when you’re done:
size_t len = 0;
const uint8_t* buf = kitchen_sink_kitchen_maybe_item(7, &len, &err);
kitchen_sink_kitchen_Item* item = NULL;
if (kitchen_sink_opt_Item_decode(buf, len, &item)) {
/* item is NULL when the producer returned none */
}
kitchen_sink_free_bytes((uint8_t*)buf, len);
kitchen_sink_opt_Item_free(&item);
A list, map, or optional codec is named by the shape’s canonical stem, the
same in every target: {p}_list_string, {p}_opt_Item,
{p}_map_string_list_i64. An optional’s _write takes the nullable pointer
itself. A value you build for writing may borrow your own memory
({p}_str_of("text") borrows a C string); only values produced by _read
or _decode are passed to _free. _decode rejects malformed or trailing
bytes and strings that aren’t well-formed UTF-8, frees what it built, and
returns false.
Objects and lifetime
An interface is an opaque, reference-counted pointer. Parameters borrow it
for the call; a returned pointer carries one strong reference that the
consumer releases with {p}_{path}_{I}_destroy. _clone returns a new
reference to the same object, and both functions treat NULL as a no-op.
Inside a value buffer an object is a token carrying one reference: the
helper’s _write stores a fresh _clone, _read adopts the token, and
_free destroys it.
Errors
Every synchronous function takes a trailing {p}_error* out_err:
typedef struct kitchen_sink_error {
int32_t code;
const uint8_t* message_ptr;
size_t message_len;
const uint8_t* payload_ptr;
size_t payload_len;
} kitchen_sink_error;
On failure code is nonzero and the message is message_len bytes of
UTF-8 at message_ptr, not NUL-terminated (print it with
printf("%.*s", (int)err.message_len, (const char*)err.message_ptr));
release the message and payload with {p}_error_clear. Negative codes are
runtime failures: -1 an untyped error (a throws: any function, or an
async call that couldn’t start), -2 panic, -3 marshalling failure, -4 a
callback implementation failed, and -5 cancelled. Positive codes belong to
the error domain the function throws, which its doc comment names:
/**
* Fails with the second domain
*
* Fails with a `kitchen_sink_kitchen_PantryError` code (and its fields as a
* payload when it declares any).
*/
KITCHEN_SINK_API int32_t kitchen_sink_kitchen_take_from_pantry(const uint8_t* item_ptr, size_t item_len, kitchen_sink_error* out_err);
Each domain is an int32_t type with its code constants
(kitchen_sink_kitchen_PantryError_OutOfStock). Domains are open: a newer
library may report a positive code your header doesn’t list, so treat an
unknown positive code as a failure of the domain with that code and
message. An error code with fields carries them in
payload_ptr/payload_len, which the helper decodes with
{code constant}_payload_decode.
Async and cancellation
An async function’s symbol is its launcher. It returns at once and later calls the completion exactly once, from any thread:
typedef void (*kitchen_sink_kitchen_do_cancellable_callback)(void* context, kitchen_sink_error* err, const uint8_t* result_ptr, size_t result_len);
KITCHEN_SINK_API void kitchen_sink_kitchen_do_cancellable(const uint8_t* input_ptr, size_t input_len, kitchen_sink_cancel_token* cancel_token, kitchen_sink_kitchen_do_cancellable_callback callback, void* context);
err is NULL on success; otherwise it’s heap-allocated and the consumer
releases it with {p}_error_free. Result slots follow the result’s family:
bool has_result, T result for an optional scalar, const T* result_ptr, size_t result_len for a typed array, const uint8_t* result_ptr, size_t result_len for a string, bytes, or buffer. A run is owned by the consumer
(release it with {p}_free_bytes), and an object result carries one
reference. Inputs are copied before the launcher returns.
A cancellable function takes a {p}_cancel_token* (or NULL). Create one
with {p}_cancel_token_create, cancel it with {p}_cancel_token_cancel,
and release your reference with {p}_cancel_token_destroy whenever you
like: the call holds its own reference. Cancelling completes a pending call
with code -5, even if it was cancelled before launch.
Callback interfaces
A callback interface is a vtable the consumer fills in, passed with a
context pointer. The vtable starts with a header (size, flags, and the
free hook), followed by one entry per method in declaration order:
typedef struct kitchen_sink_kitchen_ReadyListener_vtable {
uint32_t size;
uint32_t flags;
void (*free)(void* ctx);
/** Fires when an item is ready */
void (*on_ready)(void* ctx, int32_t code, const uint8_t* msg_ptr, size_t msg_len, kitchen_sink_error* out_err);
/** Receives the item itself and says whether to keep listening */
bool (*on_item)(void* ctx, const uint8_t* item_ptr, size_t item_len, kitchen_sink_kitchen_Gadget* gadget, kitchen_sink_error* out_err);
/**
* A display label, failing with a kitchen error
*
* May fail with a `kitchen_sink_kitchen_KitchenErrors` code (attaching its
* fields with `kitchen_sink_error_set_payload` when it declares any).
*/
void (*label)(void* ctx, uint8_t** out_ptr, size_t* out_len, kitchen_sink_error* out_err);
/** The most recent item the listener kept, if any */
void (*latest)(void* ctx, uint8_t** out_ptr, size_t* out_len, kitchen_sink_error* out_err);
/** The listener's favorite gadget */
kitchen_sink_kitchen_Gadget* (*favorite)(void* ctx, kitchen_sink_error* out_err);
} kitchen_sink_kitchen_ReadyListener_vtable;
Define one static vtable per interface, with size set to sizeof the
vtable and flags to 0 (or {P}_VTABLE_THREAD_AFFINE; see below). The
producer rejects a vtable smaller than its own with -3 (calling
free(ctx) first), so a consumer built from an older header can’t make it
call a missing entry:
static const kitchen_sink_kitchen_ReadyListener_vtable LISTENER = {
sizeof(kitchen_sink_kitchen_ReadyListener_vtable),
0,
listener_free,
listener_on_ready,
listener_on_item,
listener_label,
listener_latest,
listener_favorite,
};
The producer may call any entry from any thread, so the context must be
thread-safe, and it calls free(ctx) exactly once, from any thread, when it
drops its last reference. A consumer whose methods can only run on one
thread sets flags to {P}_VTABLE_THREAD_AFFINE: the producer then calls
the methods that return a value only on the thread that passed the vtable,
failing a call from any other thread with -4 instead. For an optional
parameter (ReadyListener?), pass a NULL vtable for none.
String and buffer arguments are borrowed for the call; an object argument carries one reference the method adopts. Returns go the other way:
- A direct value is the C return.
- An optional scalar is a
boolC return (present) with the value written to the trailingout_valueslot. - An object (
favorite) is the C return, one strong reference the producer adopts: return a fresh_clone, neverNULLfor a non-optional type. - A string, bytes, or buffer (
label,latest) is written to the trailingout_ptrandout_lenslots as a run allocated with{p}_alloc, which the producer adopts and frees. Leave themNULLand0for an empty value. - A typed array is the same, with
out_lencounting elements and the run allocated with{p}_alloc(len * sizeof(T)).
A method reports failure with {p}_error_set(out_err, code, message_ptr, message_len), which copies the message. A method declared throws: Domain
(label) may use a code of that domain and attach the code’s fields,
encoded as a value buffer, with {p}_error_set_payload(out_err, ptr, len),
and the producer receives the typed error. Any other failure is reported as
-1 with a message (-4 from a method that declares no errors) and reaches
the producer as a callback failure (-4):
static void listener_label(void* ctx, uint8_t** out_ptr, size_t* out_len,
kitchen_sink_error* out_err) {
const char* label = ((listener*)ctx)->label;
if (label == NULL) {
static const char msg[] = "no label";
kitchen_sink_error_set(out_err, kitchen_sink_kitchen_KitchenErrors_NotFound,
(const uint8_t*)msg, sizeof msg - 1);
return;
}
size_t n = strlen(label);
uint8_t* run = kitchen_sink_alloc(n);
if (n > 0) memcpy(run, label, n);
*out_ptr = run;
*out_len = n;
}
The producer adopts whatever the out slots hold even when the method fails, so a method that fails after allocating doesn’t leak.
Iterators
A function returning iter<T> returns an iterator handle. _next writes
one item and returns 1, or returns 0 when it’s done; _destroy
releases the handle, even mid-stream:
KITCHEN_SINK_API int32_t kitchen_sink_kitchen_StreamItemsIterator_next(kitchen_sink_kitchen_StreamItemsIterator* iter, const uint8_t** out_item, size_t* out_len, kitchen_sink_error* out_err);
KITCHEN_SINK_API void kitchen_sink_kitchen_StreamItemsIterator_destroy(kitchen_sink_kitchen_StreamItemsIterator* iter);
An optional scalar item is written to bool* out_has_item, T* out_item, a
typed-array item to T** out_item, size_t* out_len. String, bytes, buffer,
and typed-array items are owned (release each with {p}_free_bytes);
object items carry one reference.
Implementing an IDL in C
A hand-written producer defines every function the header declares, including the runtime and one contract function per top-level module, which returns the header’s table. For the calculator sample that’s:
uint32_t calculator_abi_version(void) { return CALCULATOR_ABI_VERSION; }
const calculator_contract_entry* calculator_calculator_contract(size_t* out_len) {
static const calculator_contract_entry table[] = CALCULATOR_CALCULATOR_CONTRACT;
*out_len = CALCULATOR_CALCULATOR_CONTRACT_LEN;
return table;
}
void calculator_error_set(calculator_error* err, int32_t code, const uint8_t* message_ptr, size_t message_len);
void calculator_error_set_payload(calculator_error* err, const uint8_t* ptr, size_t len);
void calculator_error_clear(calculator_error* err);
void calculator_error_free(calculator_error* err);
uint8_t* calculator_alloc(size_t len);
void calculator_free_bytes(uint8_t* ptr, size_t len);
calculator_cancel_token* calculator_cancel_token_create(void);
void calculator_cancel_token_cancel(calculator_cancel_token* token);
bool calculator_cancel_token_is_cancelled(const calculator_cancel_token* token);
void calculator_cancel_token_destroy(calculator_cancel_token* token);
uint64_t calculator_debug_live(int32_t kind); /* may return 0 for every kind */
{p}_alloc returns a zero-filled, 8-aligned run (NULL for 0), and
{p}_free_bytes must release both the runs the producer returns and the
runs {p}_alloc hands out, so both use one allocator. A producer that
accepts callback interfaces honors {P}_VTABLE_THREAD_AFFINE. {p}_debug_live(-1) returns 1 when
the producer counts live resources and 0 when it doesn’t. Every prototype
carries {PREFIX}_API, so the definitions stay exported under
-fvisibility=hidden; on Windows, define {PREFIX}_BUILD while building
the producer. conformance/c/producer.c is a complete example.
Known limitations
- The C target emits declarations and helpers only; there’s no runtime
loader, so
{PREFIX}_LIBRARYisn’t consulted, and the load-time checks are calls the consumer makes itself. - Nothing maps an error code to a type: a C consumer switches on
codeitself, including the unknown-positive-code case. - The helper’s writers don’t validate the UTF-8 of strings you encode; the
producer rejects a malformed one with
-3.
C++
The C++ target emits a header-only C++17 library over the
C ABI. Records become aggregates with memberwise
equality, rich enums become std::variant-backed sum types, interfaces
become copyable RAII classes, callback interfaces become abstract classes you
subclass, error domains become exception hierarchies rooted in one Error
class, async functions return std::future, and iter<T> returns a lazy
Range<T>.
C++ is a Tier 1 target: it tracks every ABI
revision as it lands and runs the full conformance suite in CI. The header
compiles warning-free with -Wall -Wextra -Werror as C++17 (with
-Wpedantic) and as C++20.
What gets generated
cpp/
├── {library}.h the C header (identical to the c target's)
├── {library}.hpp the wrapper; includes {library}.h
├── CMakeLists.txt INTERFACE target {library}::cpp
└── README.md
For the kvstore sample that’s kvstore.h, kvstore.hpp, CMakeLists.txt,
and README.md. A library is one namespace, so everything in the wrapper
lives in one C++ namespace, named after the library (kvstore): free
functions (kvstore::open_store), types, and exceptions alike. Machinery
the wrapper uses internally lives in {namespace}::detail.
[generators.cpp] key | Default | Meaning |
|---|---|---|
name | the library name | Namespace holding every declaration (may be nested, as in acme::kv) |
header_name | {library}.hpp | Wrapper header file name |
standard | 17 | C++ standard the CMake target requires |
Build and link
Add the generated directory to a CMake build (3.14 or later) and link the INTERFACE target:
add_subdirectory(path/to/cpp)
target_link_libraries(app PRIVATE kvstore::cpp)
The target adds the directory to the include path, requires C++17, and links
the producer library. Set the KVSTORE_LIBRARY CMake cache variable or
environment variable (in general {PREFIX}_LIBRARY) to a full path to link
that file; otherwise the target links kvstore by name, which resolves to a
CMake target of that name or libkvstore on the linker search path. Without
CMake, add cpp/ to the include path and link -lkvstore.
Both headers can be included in one translation unit, in either order.
weaveffi package writes kvstore-{version}-cpp.tar.gz: both headers under
include/, each desktop platform’s library under lib/<platform>/, a
README, and a CMakeLists.txt that links the host’s library into
kvstore::cpp, so the packaged build ignores KVSTORE_LIBRARY (see
Packaging).
The library check
check_library() verifies that the linked library implements the C ABI
revision the header was generated against and every declaration the header
was generated with, and throws LoadError naming the first mismatch. The
header embeds one contract row per declaration: the library’s contract
function for it, the hash of its canonical signature, and its path, with
the signature as a comment:
inline const ContractRow contract_rows[] = {
{&kvstore_contract_dc5ad183936cb6fc, 0x1898683461a88009ull, "Store.get"}, // method get(string) -> Entry throws KvError
...
};
The check calls each contract function once and compares what it returns
with the row’s hash. A declaration whose signature differs fails with
kvstore: Store.get changed since these bindings were generated. A C++
binary links its library rather than loading it, so a declaration the library
lacks fails to link instead. There’s one row per function and member, type,
error domain, error code, callback interface, and callback method.
Declarations the library has and the header doesn’t are fine, so a library
that adds functions, error codes, or callback methods keeps working with
older bindings.
An exception thrown during static initialization can’t be caught, so the
check runs on first use instead: every free function, constructor, and
static member calls check_library() before its first native call. The
result is cached in a function-local static, so the cost after the first
call is one guard-variable read. Call it at startup to fail early;
LoadError derives from Error (with code 0), so one catch handles it
with everything else.
Type mapping
| IDL type | C++ type | Parameter |
|---|---|---|
i8 … u64, f32, f64, bool | int8_t … uint64_t, float, double, bool | by value |
string | std::string | std::string_view |
bytes | std::vector<uint8_t> | const std::vector<uint8_t>& |
| C-style enum | enum class E : int32_t | by value |
| record | struct R (aggregate) | const R& |
| rich enum | struct E with std::variant<...> value | const E& |
| interface | RAII class | const I& (borrowed) |
I? | std::optional<I> | const std::optional<I>& |
callback interface, Cb? | abstract class | std::shared_ptr<Cb> (empty for none when optional) |
T? of a scalar, bool, or C-style enum | std::optional<T> | by value |
[P] of a numeric primitive | std::vector<P> | const std::vector<P>& |
other T?, [T], {K: V} | std::optional<T>, std::vector<T>, std::unordered_map<K, V> | by const reference |
iter<T> | Range<T> (returns only) | n/a |
Every value crosses the ABI as one C value, in every position (a parameter, a return, an async result, an iterator item, and a callback argument or return):
- A string, bytes, a typed array (a list of a numeric primitive other than
u8, such as[i32]or[f64]), and a value buffer cross as one{prefix}_run, a pointer and a byte length. An argument’s run points at the argument’s own storage (a string’s UTF-8 without a terminator, so interior NULs survive, or a vector’s elements), so nothing is copied. A returned run is copied into astd::stringorstd::vectorand released with{prefix}_run_free. - An optional scalar,
bool, or C-style enum (i64?,Mode?) crosses as its{prefix}_opt_*struct of a presence flag and a value, never through a buffer. - Records, rich enums, and every other optional, list, and map cross as one
value buffer. The header has one
detail::writeand onedetail::readoverload per record and rich enum; optionals, vectors, and maps are encoded by generic templates in the runtime, so a new composite shape never adds code. - An object crosses as a pointer, and a callback interface as its
{prefix}_{Cb}struct of a context and a vtable (see Callback interfaces).
Records are aggregates: build one with braces (Entry{"key", value}), and
every member not given takes its default member initializer (zero for
scalars and enums, empty otherwise), so a partial initializer compiles
without -Wmissing-field-initializers warnings. An interface wrapper has no
empty state, so a member holding one by value (or holding a record that
does) has no default, and a record with such a member has no default
constructor. An optional holding a type defined later (two types can hold
each other) also has no default member initializer, because C++20 needs the
type complete for one; it still starts empty, but a partial initializer that
skips it can warn. Records and rich enums compare with == and != memberwise:
floating-point members as IEEE values (a NaN member is unequal to itself),
and interface members by identity.
Objects and lifetime
An interface class holds one strong reference to a reference-counted
producer object through a detail::Handle, so the class itself follows the
Rule of Zero:
class Store {
public:
using raw_type = kvstore_Store;
explicit Store(adopt_t, raw_type* raw) noexcept : raw_(raw) {}
...
private:
struct traits {
using raw_type = kvstore_Store;
static raw_type* clone(const raw_type* raw) noexcept { return kvstore_Store_clone(raw); }
static void destroy(raw_type* raw) noexcept { kvstore_Store_destroy(raw); }
};
detail::Handle<traits> raw_;
};
- The destructor releases the reference with
_destroy; copying takes a new one with_clone, so copies share the object; moving transfers it. - The constructor named
newbecomes a C++ constructor (explicitwhen it takes arguments); any other constructor becomes a static factory (Store::open(path)). Nothing converts implicitly into an object, and adopting a raw pointer requires theadopttag. - A parameter borrows the caller’s reference for the call. A returned object, an async result, an iterator element, and an object argument handed to a callback are adopted.
- An object inside a record, list, map, or optional crosses as a token
minted with
_clone, so a record can be copied and destroyed freely. ==and!=compare identity: two wrappers are equal when they share one producer object.handle()borrows the C pointer;clone_handle()returns a new reference the caller owns. An interface member namedhandle,clone_handle,raw_type, ortraitsgains a trailing_, and so does a free function or parameter namedadopt,adopt_t,check_library,detail, orstd(reserved member names).
The C++ object model makes lifetimes the caller’s responsibility: a wrapper must outlive the calls made through it, and destroying a wrapper on one thread while another thread calls through it is a data race, as for any C++ object. A moved-from wrapper holds null.
Errors
Every exception the library throws derives from {namespace}::Error, which
derives from std::runtime_error and carries code(). Which class a failed
call throws depends on what it declares:
throws: SomeDomain: each error domain gets a class (KvError : Error) and one subclass per code (KeyNotFoundError : KvError). The names come from the shared naming rule, which appendsErrorunless the IDL name already ends in it (theKitchenErrorsdomain isKitchenError). A code with payload fields exposes them as public members (e.key); a field namedcodeorwhatgains a trailing_so it doesn’t hidecode()orwhat(). A declared code throws its class. Domains are open: a positive code these bindings don’t know (a newer producer added it) throws the domain class itself, with the code and message intact. A library may declare several domains, and each call throws only its own, so two domains can reuse a code value.throws: any: a failure throwsErroritself, with code -1 and the producer’s message.- Nothing declared: the call can still fail, but only through a producer
bug, so it follows the
trap policy and throws
InternalError(anError) with the runtime code and message.
On a call that declares errors, a runtime code throws the root Error with
that code (-2 producer panic, -3 marshalling failure, -4 a callback
implementation that failed); under every policy, -5 throws Cancelled. A
value buffer the wrapper can’t decode is an InternalError with code -3, and
a required callback interface passed as an empty std::shared_ptr is an
Error with code -3, refused before the call. LoadError reports a library
that doesn’t match the headers. Wrappers are never noexcept.
Error messages cross the ABI as a pointer and a length, so they keep any byte
the producer sent; an empty message is "". The wrapper releases a failed
call’s message and payload once it has built the exception.
try {
store.get("missing");
} catch (const kvstore::KeyNotFoundError& e) {
std::cerr << e.what() << " (" << e.key << ")\n";
} catch (const kvstore::KvError& e) {
// Any other KvError code, known or not.
} catch (const kvstore::Error& e) {
// A runtime failure (e.code() < 0).
}
Async and cancellation
An async function returns std::future<T>, settled from a producer thread.
A cancellable function also takes a trailing const CancelToken&:
std::future<uint32_t> compact(uint32_t pause_ms, const CancelToken& cancel_token = CancelToken::none()) const;
CancelToken is a move-only RAII wrapper over the native token. Pass one
token to any number of calls and call cancel() from any thread; every call
still in flight completes with Cancelled. Each call takes its own native
reference, so the token can be destroyed at any time without affecting the
calls. Omitting the argument passes CancelToken::none(), which never
cancels.
kvstore::CancelToken token;
std::future<uint32_t> pending = store.compact(60000, token);
token.cancel();
try {
pending.get();
} catch (const kvstore::Cancelled&) {
// The runtime dropped the work.
}
An async result crosses like a return of its type: an optional scalar as its
{prefix}_opt_* struct, a typed array as a run. std::future has no
cancellation of its own, so destroying a future doesn’t cancel the call;
cancel its token instead.
Callback interfaces
A callback interface is an abstract class with one pure virtual method per IDL method:
class Policy {
public:
virtual ~Policy() = default;
virtual std::optional<int64_t> ttl_for(std::string_view key, std::optional<int64_t> requested) = 0;
virtual Entry admit(const Entry& entry) = 0;
virtual Store route(std::string_view key, Store home) = 0;
};
Pass an implementation as std::shared_ptr. The wrapper boxes the pointer
as the context of the {prefix}_{Cb} struct and pairs it with a static
vtable (from detail::Callbacks<Policy>) whose size is its own sizeof
and whose free deletes the box when the producer releases the
implementation, which runs your destructor if nothing else holds it. For an
optional callback parameter (Loader?), an empty std::shared_ptr (or
nullptr) passes a null vtable, which is none. The producer may call
methods, and release the implementation, from any thread, so
implementations must be thread-safe; the vtable never sets the thread-affine
flag. Vtables are open, so a library that appends a method keeps working
with an implementation generated before it: calling the method it lacks
fails in the producer with -4.
Arguments follow the parameter rules seen from your side: a string is a
std::string_view valid for the call, a typed array, bytes, or a buffered
value arrives by const reference to a copy, an optional scalar as
std::optional<T>, and an object by value as a wrapper you own.
A method can return any type. A scalar is returned as is and an optional
scalar as its {prefix}_opt_* struct; an object (Store,
std::optional<Store>) hands the producer a fresh reference; a string,
bytes, typed array, or buffered value is copied into a run allocated with
{prefix}_alloc, which the producer adopts. A required object return that’s
null (a moved-from wrapper) and a value the producer can’t decode are
refused by the producer with -3.
Each method reports an exception according to what it declares, and nothing unwinds through the C frame:
throws: SomeDomain: throw the domain’s class or one of its codes’ classes. The code, the message (what()), and the code’s fields reach the producer, which decodes them into its own error type. Any other exception is a plain failure (code -1 with itswhat()).throws: any: any exception is a failure, code -1 with itswhat().- Nothing declared: any exception is a callback failure, -4.
Entry admit(const Entry& entry) override {
if (entry.key == "secret") throw kvstore::RejectedError("not stored", entry.key, "no secrets");
return entry;
}
Whether the original call then fails is the producer’s decision. A Rust
producer that propagates a typed failure with ? makes the call throw the
same RejectedError, with the message the producer renders for it; the
kvstore sample turns any other callback failure into CallbackFailedError
carrying your exception’s message.
Iterators
An iter<T> function returns Range<T>, a lazy, single-pass, move-only
range:
for (const std::string& key : store.keys(std::nullopt)) {
// One producer call per step.
}
Each step pulls one element; an element crosses like a return of its type,
so iter<i64?> yields std::optional<int64_t> (an absent element isn’t the
end) and iter<[i32]> yields std::vector<int32_t>. The range releases the
producer iterator exactly once: when it’s exhausted, when a step throws, on
close(), or from the destructor, so abandoning a loop early leaks nothing.
next() returns std::optional<T> for manual iteration. The iterator type
models an input iterator with a sentinel end, so under C++20 a Range<T> is
a std::ranges::input_range.
Known limitations
- Ranges are single-pass input ranges; copy them into a
std::vectorfor random access. - A typed array argument is a
const std::vector<T>&; C++17 has nostd::span, so other contiguous storage must be copied into a vector first. - A callback interface must be a
std::shared_ptrto a subclass; there’s no lambda overload. - C++ implementations don’t declare their vtables thread-affine, so the producer may call any method from any thread.
- Exceptions not derived from
std::exceptionare reported to the producer with a generic message. - The library check runs on first use, not at load time (see above).
Swift
The Swift target emits a standalone SwiftPM package that wraps the
C ABI (revision 6) in idiomatic Swift: throws with
typed Error enums for declared errors, plain Hashable structs and enums
for values, ARC-managed final class wrappers for objects, class-bound
protocols for callback interfaces, async functions with task cancellation
for async callables, and lazy Sequences for iterators.
Swift is a Tier 1 target: it tracks every ABI revision as it lands and runs the full conformance suite in CI.
What gets generated
For a package named kvstore:
swift/
Package.swift
Sources/
CKvstore/
kvstore.h # copy of the C header
module.modulemap # system library: links `kvstore`
Kvstore/
Kvstore.swift # the wrapper API
WeaveFFIRuntime.swift # runtime support: load check, codec, errors
The package, product, and Swift module are the package name in PascalCase
(key-store becomes KeyStore); set [generators.swift] name to
override it. The C module is always the Swift module’s name with a C prefix.
The C symbol prefix and the native library name come from the package
identity. WeaveFFIRuntime.swift depends only on those names, so it changes
only when they do.
A library is one namespace, and so is its Swift module. Records, enums,
error domains, interfaces, and callback protocols sit at file scope, and
each free function is a top-level public func. A consumer calls one
unqualified, or qualified with the module name when another module declares
the same name:
import Kvstore
let store = try await Kvstore.openStore(path: "/data")
let stats = try summarize(store: store, prefix: nil)
Parameters, methods, record fields, and enum cases are lowerCamelCase
(expiresAt, .keyNotFound), and every argument is labeled
(summarize(store: store, prefix: nil)). Doc comments carry over, with
backticked API names in their Swift spelling (`new_op` becomes
`newOp`), and deprecated declarations get
@available(*, deprecated, message:).
[generators.swift] key | Default | Meaning |
|---|---|---|
name | PascalCase(name) | Package, product, and module name |
min_macos, min_ios | "11.0", "13.0" | The manifest’s platforms: |
xcframework_url | a placeholder | Where the packaged binary target downloads C{Module}.xcframework.zip; {version} and {file} are substituted |
Build and link
The package builds as-is with SwiftPM 5.9 or later (its manifest declares
swift-tools-version:5.9, so it compiles in the Swift 5 language mode); the
sources also compile without warnings in the Swift 6 language mode, with
complete concurrency checking. Depend on it by path or from a repository,
and tell the linker where libkvstore lives:
dependencies: [.package(path: "bindings/swift")],
targets: [
.executableTarget(name: "App", dependencies: [.product(name: "Kvstore", package: "swift")]),
]
swift build -Xlinker -L/path/to/lib
Swift binds the library at link time, so at run time the dynamic loader finds
it the usual way (its install name, an rpath, or DYLD_LIBRARY_PATH and
LD_LIBRARY_PATH). The {PREFIX}_LIBRARY variable other targets honor
doesn’t apply. There’s no generated glue: the Swift module calls the C
header’s functions directly.
When a CKvstore.xcframework sits next to Package.swift, the manifest uses
it as a binary target instead of the system library, so apps link without
flags.
weaveffi package (on macOS) fuses the static libraries of every Apple
platform built (macOS, iOS, the iOS simulator) into
CKvstore.xcframework.zip, writes its SHA-256 checksum, and writes the
package swift/Kvstore/, whose manifest declares CKvstore as
.binaryTarget(url:checksum:) at xcframework_url. Upload the archive there
and publish the package; apps on any Apple platform then link with no flags
(see Packaging).
Load-time checks
Before the first call (the first constructor, static, or free function), the bindings check, once per process, that the library implements C ABI revision 6 and that every declaration they were generated with has the same contract: each declaration’s contract function must return the hash of the signature the bindings saw. The rows are embedded in the wrapper, one per function, interface, member, record, enum, callback interface, callback method, error domain, and error code:
func wvCheckContracts() -> KvstoreLibrary.LoadError? {
wvCheckContract([
(kvstore_contract_7b4181d5fd2958e8, 0x8d469dd20baca093, "Store.open"),
// ...one row per declaration
])
}
The contract functions are linked like every other symbol, so a library
that lacks a declaration fails to link. Declarations, error codes, and
callback methods the library adds are fine. To handle a mismatch, call
{Module}Library.check() at startup. It runs the checks (or returns their
cached result) and throws a LoadError naming the first mismatch:
do {
try KvstoreLibrary.check()
} catch let error as KvstoreLibrary.LoadError {
// .abiMismatch(found:expected:) or .changed(declaration:)
print(error.localizedDescription)
}
Kvstore: the native library 'kvstore' implements C ABI revision 5, but these bindings need revision 6
Kvstore: Store.put changed since these bindings were generated; regenerate the bindings or rebuild the library 'kvstore'
A call made while the library doesn’t match stops the process with the same
message, whether or not check() ran, since a stale binding would otherwise
corrupt memory. KvstoreLibrary.abiVersion is the revision the bindings
need.
Type mapping
Every value crosses the C ABI as one C value, by value, in every position: a parameter, a return, an async result, an iterator item, and a callback method’s argument and return.
| IDL type | Swift type | At the ABI |
|---|---|---|
i8 to i64, u8 to u64 | Int8 to Int64, UInt8 to UInt64 | The scalar |
f32, f64 | Float, Double | The scalar |
bool | Bool | C bool |
string | String | A run of UTF-8 |
bytes | Data | A run of bytes |
| C-style enum | enum E: Int32, CaseIterable, Sendable | int32_t |
| Record | struct, Hashable and Sendable | A run holding a value buffer |
| Rich enum | enum with associated values, Hashable and Sendable | A run holding a value buffer |
T? of a number, bool, or C-style enum | T? | A {prefix}_opt_{prim} struct |
[T] of a number other than u8 | [T] | A run holding the packed elements (a typed array) |
Any other T?, [T], {K: V} | T?, [T], [K: V] | A run holding a value buffer |
| Interface | final class, Hashable by identity, @unchecked Sendable | Object pointer |
Interface? | optional wrapper | Nullable pointer |
| Callback interface | any P, where protocol P: AnyObject, Sendable | A {prefix}_{P} struct of a context and a vtable |
Callback? | (any P)? | The same struct, with a null vtable for nil |
iter<T> | NativeSequence<T> | Iterator handle |
A run is the C header’s {prefix}_run, { ptr, len } with len in bytes,
which the runtime calls WvRun. A parameter lends the Swift value’s own
storage for the call (withUTF8, withUnsafeBytes), or its encoding for a
value buffer, with no copy; a returned run is copied once (or decoded in
place) and then released with {prefix}_run_free. Strings cross as their
UTF-8 bytes with a length, so interior NULs survive. An optional scalar
(Int64?, Bool?, Priority?) crosses as its {prefix}_opt_{prim}
struct (has and value) in every position, never through a buffer.
Floats round-trip bit for bit, including NaN and -0.0. usize and
isize in a Rust producer are u64 and i64 (UInt64, Int64); a
char and a custom type cross as their IDL type (usually String).
public func get(key: String) throws -> Entry {
var err = WvError()
let rv: WvRun = wvWithUTF8(key) { key_run in
kvstore_Store_get(self.ptr, key_run, &err)
}
try wvCheck(&err, KvError.self)
return wvTakeBuffer(rv, as: Entry.self)
}
Every type that crosses inside a value buffer conforms to the internal
WvCodable protocol: the primitives in the runtime, Optional, Array, and
Dictionary generically, and each record, enum, and interface where it’s
declared. A composite type such as [String: [Entry?]] therefore has one
encoder and one decoder, the generic ones, rather than a loop at each use:
extension Entry: WvCodable {
static func wvRead(_ r: inout WvReader) -> Entry {
Entry(key: r.read(), value: r.read(), kind: r.read(), version: r.read(), expiresAt: r.read(), tags: r.read(), metadata: r.read())
}
func wvWrite(_ w: inout WvWriter) {
w.write(self.key)
w.write(self.value)
// ...
}
}
Objects and lifetime
An interface becomes a final class holding one strong reference. deinit
releases it, a constructor named new becomes init, and other constructors
and statics become static funcs:
public final class Gadget: WvObject, Hashable, @unchecked Sendable {
let ptr: OpaquePointer
init(ptr: OpaquePointer) {
self.ptr = ptr
}
deinit {
kitchen_sink_Gadget_destroy(ptr)
}
func clonePtr() -> OpaquePointer {
wvNonNull(kitchen_sink_Gadget_clone(ptr))
}
/// Whether two wrappers hold the same native object.
public static func == (lhs: Gadget, rhs: Gadget) -> Bool {
lhs.ptr == rhs.ptr
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ptr)
}
/// Create a gadget with the given id
public init(id: Int64) {
wvLoad()
var err = WvError()
let rv = kitchen_sink_Gadget_new(id, &err)
wvTrap(&err)
self.ptr = wvNonNull(rv)
}
/// Render the gadget as a human-readable string
public func describe() -> String {
var err = WvError()
let rv = kitchen_sink_Gadget_describe(self.ptr, &err)
wvTrap(&err)
return wvTakeString(rv)
}
}
Swift keeps every argument and the receiver alive for the whole call, so a
wrapper can’t be freed mid-call. Writing an object into a value buffer or
returning it from a callback method clones its reference, and reading one
adopts the reference into a new wrapper, so two wrappers can share one native
object. Wrappers are Equatable and Hashable by that native identity: two
wrappers are == exactly when they hold the same object (_clone keeps the
pointer value), whatever its state. So a record or enum carrying objects is
Hashable too, and store.share() == store. There’s no close(): release
happens when the last Swift reference goes away. An interface member spelled
like one the class declares (ptr, clonePtr, wvRead, wvWrite) gains a
trailing _ (reserved member
names).
Errors
Each error domain becomes an enum conforming to Error, LocalizedError,
Hashable, and Sendable, named through the shared naming rule: the
domain’s name with one Error suffix (KvError stays KvError,
KitchenErrors becomes KitchenError, Failure becomes FailureError).
Each code is a case carrying the message (the code’s documented message when
the library sends none) and the code’s fields; errorCode and message
read them back:
public enum KvError: Error, LocalizedError, Hashable, Sendable {
/// key not found
case keyNotFound(message: String, key: String)
/// entry expired
case expired(message: String, key: String, expiredAt: Int64)
// ...
/// A code these bindings don't declare, from a newer library.
case unknown(code: Int32, message: String)
}
Domains are open: a code the producer added after the bindings were
generated arrives as .unknown with its code and message, never as a crash,
so a switch over a domain needs that case (or a default). A field named
message gains a trailing _ (case callbackFailed(message: String, message_: String)), and so does a code spelled like a member of the enum
(errorCode, message, errorDescription) or like unknown (the
catch-all case then becomes unknown_).
A function declared throws: KvError raises that enum for the domain’s codes
and {SwiftModule}RuntimeError (KvstoreRuntimeError, with errorCode and
message) for runtime failures: -2 panic, -3 marshalling, and -4 when a
callback implementation failed. A function declared throws: any raises the
runtime error with code -1 (KvstoreRuntimeError.untypedCode) and the
producer’s message:
do {
_ = try store.importLines(text: "c=3\nbroken")
} catch let error as KvstoreRuntimeError {
print(error.errorCode, error.message) // -1 line 2: expected key=value
}
Swift has no unchecked errors, so a function that doesn’t declare throws
follows the trap policy:
it stops the process with fatalError when the library reports a failure,
naming the function, the code, and the message:
Kvstore.count() failed with code -2: <the producer's panic message>
Async and cancellation
An async function becomes an async function over a checked continuation;
the library’s completion callback resumes it exactly once, from any thread,
with the result as one C value. It’s marked throws only when the IDL
function declares errors or is cancellable; otherwise a failure follows the
trap policy (summarizeAll(stores:) is async -> Stats). Optional scalars
and typed arrays arrive the same way as from a synchronous call
(versionOf(key:) async -> UInt32?, versions(keys:) async -> [UInt32]). A
cancellable function runs inside withTaskCancellationHandler: it creates a
native cancel token, passes it to the launch, and cancels it when the calling
task is cancelled. A cancelled call (code -5) throws CancellationError,
even when the task was cancelled before the call started:
public func doCancellable(input: String) async throws -> String {
wvLoad()
let token = WvCancelToken()
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<String, Error>) in
let context = Unmanaged.passRetained(WvContinuation(continuation)).toOpaque()
wvWithUTF8(input) { input_run in
kitchen_sink_do_cancellable(input_run, token.raw, { context, err, result in
let cont = Unmanaged<WvContinuation<String, Error>>.fromOpaque(context!).takeRetainedValue().value
if let err = err {
cont.resume(throwing: wvTakeCancellation(err))
return
}
cont.resume(returning: wvTakeString(result))
}, context)
}
}
} onCancel: {
token.cancel()
}
}
The launcher copies its arguments before it returns, so lending them for the launch is enough. The token is released when the wrapper returns; the library holds its own reference for the call’s duration.
Callback interfaces
A callback interface becomes a class-bound protocol. A requirement is
throws when the IDL method declares errors (throws: Domain or
throws: any), and plain otherwise:
public protocol Loader: AnyObject, Sendable {
/// The loader's name, recorded in a loaded entry's metadata under
/// `source`.
///
/// - Throws: Any error, which fails the library's call with the error's
/// description.
func name() throws -> String
/// A store that may already hold `key`, consulted first, if any.
///
/// - Throws: Any error, which fails the library's call with the error's
/// description.
func fallback(key: String) throws -> Store?
/// The value for `key`. Fail with `keyNotFound` naming
/// `key` when there's none.
///
/// - Throws: ``KvError`` to fail the library's call with that error and
/// its fields; any other error fails it with the error's description.
func load(key: String) throws -> Data
}
Implement it with a class and pass an instance (any Loader) where the API
expects one. The library may call it from any thread, which is why the
protocol requires Sendable; a class guarding its own state can declare
@unchecked Sendable.
The argument crosses as the {prefix}_{Loader} struct: a context that
retains the implementation until the library calls the vtable’s free
(which may happen on any library thread), and a pointer to one process-wide
vtable per protocol. An optional parameter (loader: (any Loader)?) passes
the zero struct, whose null vtable means none, for nil. The vtable sets
size to its own size, so a newer library that appended a method knows this
binding lacks it (that call fails with -4), and leaves the thread-affine
flag clear. Each entry is a @convention(c) trampoline:
enum WvLoaderVtable {
static let shared = WvVtable(kvstore_Loader_vtable(
size: UInt32(MemoryLayout<kvstore_Loader_vtable>.size),
flags: 0,
free: { ctx in wvRelease(ctx, as: (any Loader).self) },
// ...
load: { ctx, a0, outErr in
wvInvoke(ctx, outErr, as: (any Loader).self, throwing: KvError.self, fallback: WvRun()) { wvImpl in
try wvHandOverBytes(wvImpl.load(key: wvBorrowString(a0)))
}
}
))
}
Arguments and returns follow the ABI:
- Strings, bytes, typed arrays, and value buffers arrive as copies of the
library’s borrowed runs; an optional scalar arrives as
T?; an object argument arrives as a wrapper that adopted the reference the library passed, which the implementation may keep. - A returned number,
Bool, or C-style enum crosses by value, and an optional one as its{prefix}_opt_{prim}struct; a returned object (StoreorStore?) as a fresh reference the library adopts; and a returned string,Data, typed array, or value buffer (a record, a rich enum, an optional, a list, or a map) as a run allocated with{prefix}_alloc, which the library adopts. - A requirement declared
throws: KvErrormay throw that enum: the library receives its code, message, and fields as the payload, exactly as if the producer had raised it (a Rust producer then renders the message from the fields; a thrown.unknownsends its own code, which the producer treats as any other failure). Any other error, from any throwing requirement, reaches the library as an untyped failure (-1) with the error’serrorDescription(or itsString(describing:)). Nothing unwinds through C.
final class FileLoader: Loader, @unchecked Sendable {
func name() throws -> String { "files" }
func fallback(key: String) throws -> Store? { nil }
func load(key: String) throws -> Data {
guard let data = FileManager.default.contents(atPath: "/data/\(key)") else {
throw KvError.keyNotFound(message: "no file for \(key)", key: key)
}
return data
}
}
let entry = try store.getOrLoad(key: "settings", loader: FileLoader())
Iterators
An iter<T> return is a NativeSequence<T>, one generic class (a
Sequence and its own IteratorProtocol) for every iterator in the API.
Each next() pulls exactly one element from the library, received as one C
value like a return of the same type; the native iterator is released as
soon as the stream ends, or from deinit when iteration stops early. The
sequence is single-pass. next() can’t throw, so for a throwing function an
error reported mid-stream ends iteration and is kept in the sequence’s
error property; collect() pulls the rest and throws it instead:
for key in try store.keys(prefix: "user.") { print(key) }
let expirations: [Int64?] = try store.expirations().collect()
Known limitations
- The library is linked at build time, so
{PREFIX}_LIBRARYisn’t honored and library paths come from the linker and loader. A library the dynamic loader can’t find, or one that lacks a declaration, stops the process beforemain, beforecheck()can report anything. - Calls made while the library doesn’t match (whether or not
check()ran), malformed value buffers, and failures of non-throwing calls stop the process instead of throwing. - The runtime declares the public types
{Module}Library,{Module}RuntimeError, andNativeSequence; an IDL type with one of those names doesn’t compile. Qualifying a free function with the module name (Kvstore.openStore) works only while no type in scope shares the module’s name. - The manifest stays at
swift-tools-version:5.9for Xcode 15 users, so SwiftPM compiles the package in the Swift 5 language mode even under a Swift 6 toolchain.
Kotlin
The Kotlin target emits a Gradle library module: Kotlin sources that call
the producer’s C ABI (revision 6) directly through
JNA. There’s no generated C,
no JNI shim, and no CMake build; the only native code a consumer ships is
the producer library itself. The default flavor is an Android library; the
jvm flavor is a plain Kotlin/JVM library for desktop and server JVMs.
Records become data classes, interfaces AutoCloseable wrappers, async
functions suspend functions, callback interfaces Kotlin interfaces, and
the free functions members of one object named after the library, whose
functions are @JvmStatic, so Java calls them as static methods.
Kotlin is a Tier 1 target: it tracks every ABI revision as it lands and runs the full conformance suite in CI.
What gets generated
For a library whose C prefix and library name are kitchen_sink:
kotlin/
settings.gradle.kts repositories and the root project name
build.gradle.kts Android library (or Kotlin/JVM), JNA, maven-publish
consumer-rules.pro R8 keep rules (Android flavor only)
src/main/kotlin/kitchen_sink/
KitchenSink.kt every public declaration and the KitchenSink object
CLibrary.kt internal: the JNA binding, contract rows, vtables
Runtime.kt FfiException, NativeBugException, NativeSequence, NativeLibrary, lifetime
Abi.kt internal: the C structs JNA maps and the runtime surface
Buffers.kt value-buffer reader and writer, content equality (when the API needs them)
Codecs.kt one codec per composite type (when the API has any)
Async.kt coroutine bridge (when the API has async)
The package defaults to the identity’s C prefix (kitchen_sink), the
Gradle group to the package, and the root project and artifact ID to the
[package] name. Nothing outside the generated-file headers carries WeaveFFI
branding.
Configuration
[generators.kotlin]
name = "com.example.kitchen" # the Kotlin package; default: the C prefix
flavor = "jvm" # "android" (default) or "jvm"
min_sdk = 21 # Android minSdk (default 21)
compile_sdk = 35 # Android compileSdk (default 35)
Building and loading
The tree builds with Gradle as is (no wrapper is generated), and
gradle publishToMavenLocal publishes the module. settings.gradle.kts
declares mavenCentral() and the Gradle plugin portal, plus google() for
the Android flavor. The Android flavor uses the Android Gradle plugin 8.7.3
and Kotlin 2.0.21 and compiles to Java 8 bytecode; the JVM flavor uses
Kotlin 2.0.21. Both depend on JNA 5.18.1 (net.java.dev.jna:jna, as its
@aar on Android, which carries JNA’s own native library for every ABI),
and an API with async functions also depends on kotlinx-coroutines-core
1.9.0.
- Android. Put the producer library for each ABI in
src/main/jniLibs/<abi>/libkitchen_sink.so, and the AAR packages it. - JVM. Put the producer library for each desktop platform under
src/main/resources/<os>-<arch>/, the classpath prefix JNA looks in (darwin-aarch64,darwin-x86-64,linux-x86-64,linux-aarch64,win32-x86-64), or anywhere on the system’s library search path or JNA’sjna.library.path.
weaveffi package writes the Gradle project, plus a README, to
kotlin/{name}/ with both layouts filled in from the per-platform builds,
so building the AAR or JAR needs only Gradle (gradle assembleRelease,
gradle jar); see Packaging.
At first use the bindings load the producer with JNA’s Native.load, from
the absolute path in KITCHEN_SINK_LIBRARY when it’s set, else wherever JNA
finds kitchen_sink. Then they make the two
load-time checks: the producer’s
kitchen_sink_abi_version() must return 6, and every
contract function the bindings were
generated with must exist and return its hash. If either check fails,
loading fails with an UnsatisfiedLinkError that names the problem:
`Gadget.describe` is missing from the kitchen_sink library (/path/to/libkitchen_sink.dylib)
`Item` changed since these bindings were generated (/path/to/libkitchen_sink.dylib)
A producer that adds declarations, error codes, or callback methods still loads: only the rows the bindings know about are checked.
A failed load is catchable. NativeLibrary.load() loads and checks the
library eagerly and throws the UnsatisfiedLinkError that names the
problem, the same one on every later call, so an app can probe for the
library at startup and fall back gracefully:
try {
NativeLibrary.load()
} catch (e: UnsatisfiedLinkError) {
// The library is missing, or it doesn't match these bindings.
}
Without that call, the first use of the bindings throws the same
UnsatisfiedLinkError; every later use throws NoClassDefFoundError. Both
are LinkageErrors, so catch (e: LinkageError) covers either.
How values cross
CLibrary.kt declares one JNA Library interface, CLibrary, with a
method per C function, named after its symbol and typed after the header,
so each value crosses as the one C value the
ABI gives it:
internal interface CLibrary : CRuntime {
fun kitchen_sink_Gadget_readings(self: Pointer?, limit: OptU32.ByValue, out_err: NativeError?): Run.ByValue
fun kitchen_sink_subscribe(listener: CallbackArg, out_err: NativeError?): Int
...
}
| IDL type | Kotlin type | Crosses JNA as |
|---|---|---|
i8, i16, i32, i64 | Byte, Short, Int, Long | the same |
u8, u16, u32, u64 | UByte, UShort, UInt, ULong | the signed type of the same width |
f32, f64 | Float, Double | the same |
bool | Boolean | Byte (a C bool is one byte; JNA’s boolean is four) |
string | String | Run.ByValue of UTF-8 |
bytes | ByteArray | Run.ByValue |
| enum | enum class with value | Int |
| record | data class | Run.ByValue holding a value buffer |
| rich enum | sealed class | Run.ByValue holding a value buffer |
T? of a scalar or enum | Int?, Priority?, … | OptI32.ByValue and the like, {has, value} |
[T] of i8…f64 (not bool, u8) | List<Int>, List<ULong>, … | Run.ByValue of the packed elements |
other T?, [T], {K:V} | T?, List<T>, Map<K, V> | Run.ByValue holding a value buffer |
interface, Iface? | wrapper class, nullable wrapper | Pointer? (null is none) |
callback interface, Cb? | Kotlin interface, nullable | CallbackArg by value (a null vtable is none) |
iter<T> | NativeSequence<T> | Pointer? |
Run, NativeError, CallbackArg, and the eleven Opt* classes are JNA
Structures whose ByValue forms cross by value, as the header’s structs
do. A run the bindings pass in is staged in JNA Memory the call borrows; a
run the library returns is copied out and released with
kitchen_sink_run_free. Strings cross as UTF-8 with an explicit length, so
interior NULs and supplementary characters round-trip exactly. Unsigned
integers are Kotlin’s unsigned types everywhere: parameters, returns, record
and variant fields, error payload fields, collection elements and map keys,
iterator elements, async results, and callback parameters and returns. Each
crosses in the signed type of the same width, converted bit for bit
(toUInt(), toInt()), so u64 max is ULong.MAX_VALUE.
An optional scalar or C-style enum (i64?, Priority?) and a list of
fixed-width numbers ([f64], [u64]) never go through a value buffer at a
call boundary. The same types nested in a record or a collection do.
Value buffers are encoded and decoded by generated functions: one pack_
and unpack_ pair per record and rich enum (next to its declaration) and
one per distinct composite type in Codecs.kt, named with the composite’s
canonical stem (pack_list_Entry, unpack_map_string_Store,
pack_opt_StoreInfo), so every call site calls a function instead of
inlining a loop.
Records holding bytes compare by content: a data class with a ByteArray
field (or one inside a list, map, or optional) overrides equals,
hashCode, and toString to use the array’s content, since a
ByteArray’s own equals is identity. Other data classes keep the
generated members.
Naming
User types and the object holding the free functions live at the top level
of the package. The object is named after the library in UpperCamelCase
(kitchen_sink is KitchenSink, kvstore is Kvstore). Two rules keep
the generated names valid:
- A user type named like a Kotlin keyword, a type Kotlin or Java imports by
default (
Unit,String,UInt,Result, …), a JNA type the generated sources import (Pointer,Structure,Callback, …), or a runtime declaration (FfiException,NativeSequence,Run, …) gains a trailing underscore:UnitbecomesUnit_. - The object, when its name equals a type’s or a generated file’s
(
Runtime,Abi,Buffers,Codecs,Async,CLibrary), gains aLibrarysuffix: astorelibrary with aStoreinterface puts its functions onStoreLibrary.
Functions, methods, parameters, record fields, variant fields, and error
payload fields are lowerCamelCase (expires_at is expiresAt). Keywords
gain a trailing underscore (class_), as does a method named like a member
every wrapper already declares or inherits (close, handle, toString,
wait, …; see reserved member names),
and an error payload field named like a property every exception has
(message, code, cause, …): CallbackFailed.message_. Identifiers in
backticks in IDL docs and deprecation messages are rewritten to these
spellings (Use `new_op` instead reads Use `newOp` instead).
Objects and lifetime
An interface wrapper owns one strong reference:
class Gadget private constructor(pointer: Pointer) : AutoCloseable {
internal val handle: NativeHandle = NativeCleaner.register(this, NativeHandle(pointer, Lib.c::kitchen_sink_Gadget_destroy))
...
/** Render the gadget as a human-readable string */
fun describe(): String {
return handle.borrow { _self ->
take(callNative(0) { _err -> Lib.c.kitchen_sink_Gadget_describe(_self, _err) }) { _run -> _run.string() }
}
}
Every call borrows the receiver and every object argument for its whole
duration. close() (or use { }) releases the reference; if a call is in
flight, the release waits until the call returns, and if the wrapper becomes
unreachable mid-call, its handle is still borrowed, so the object is never
freed under native code. Using a closed wrapper throws
IllegalStateException; closing twice is safe. Wrappers that are never
closed are released by a daemon thread draining a PhantomReference queue,
which works on every Android API level.
Objects inside records and collections cross as new strong references: the encoder clones each one (and releases the clones again if encoding fails), and the decoder adopts each one into a new wrapper.
Errors
Every error is an FfiException with a code and the producer’s message.
Each error domain becomes a subclass named with the shared Exception
spelling (KvError becomes KvException; KitchenErrors becomes
KitchenException), with one nested class per code whose payload fields are
properties and whose message defaults to the IDL’s:
open class KitchenException internal constructor(code: Int, message: String) : FfiException(code, message) {
class NotFound(message: String = "Item not found") : KitchenException(1, message)
A callable declared throws: KitchenErrors raises that domain’s
exceptions. Domains are open: a code the bindings don’t declare (one a newer
library added) raises a plain KitchenException carrying that code and
the library’s message, so an app catches it with the rest of its domain.
Codes are unique only within a domain, so each call maps its codes through
its own domain: code 1 is CalcException.DivisionByZero from divide and
ParseException.NotANumber from parse.
A callable declared throws: any fails with code -1 and a message,
raised as the root FfiException. A runtime failure of any throwing call is
the root FfiException too, with its negative code: -1 a generic
producer error, -2 a producer panic, -3 a marshalling failure, and -4
a callback implementation that failed. Every throwing function carries
@Throws for its exception class, so Java callers can catch it as the
checked exception it is.
A callable that isn’t throws can’t report an error, so any failure is a
bug in the library, and the binding raises the unchecked
NativeBugException (an IllegalStateException) instead, following the
trap policy. Its code
and message name the runtime code and the producer’s message, as in
native call failed with code -2: {the panic message}.
A malformed value buffer or an undeclared enum value read from the producer
raises NativeBugException with code -3 as well.
Async and cancellation
Async functions are suspend functions. A cancellable one creates a native
cancel token for the call, and cancelling the awaiting coroutine (directly,
by its scope, or through withTimeout) cancels the token, so the producer
drops the pending work:
@JvmStatic
suspend fun doCancellable(input: String): String {
val input_ = runOf(encodeUtf8(input))
return awaitNative(true, 0, { _raw -> take(_raw as Run) { _run -> _run.string() } }) { _token, _context ->
Lib.c.kitchen_sink_do_cancellable(input_, _token, Completions.runDone, _context)
}
}
The completion callback the launcher gets is one static JNA callback per
result type (Completions.runDone), so it stays reachable for as long as the
library can call it; the context names the pending call it completes. The
coroutine resumes with CancellationException when it’s cancelled or when
the producer completes the call with code -5. Completions arrive on
producer threads, which JNA attaches to the JVM for the call; the token is
destroyed once the call completes. The coroutines runtime
(kotlinx-coroutines-core) is a dependency only when the API has async
functions.
Callbacks
A callback interface is a plain Kotlin interface (a fun interface when
it has one method, so a lambda implements it), and an optional callback
parameter (Cb?) takes null for none, which passes a null vtable. Each
callback interface has one static vtable whose entries are static JNA
callbacks; passing an implementation registers it under a fresh context
pointer until the producer calls the vtable’s free, and each entry looks
the implementation up by its context. So every JNA callback the library can
call stays reachable for good, and an implementation stays reachable exactly
as long as the library holds it. Every vtable’s flags is 0: the JVM can
run a method on any thread.
interface Policy {
/**
* Admit an entry about to be stored, returning it as it should be
* stored. ...
*
* Throw a [KvException] to report a typed error to the library; anything else
* thrown reaches it as an untyped failure with its message.
*/
@Throws(KvException::class)
fun admit(entry: Entry): Entry
...
}
fun interface Scorer {
@Throws(Exception::class)
fun scores(sizes: List<ULong>): List<Double>
}
val ranked = store.rank { sizes -> sizes.map { it.toDouble() } }
- Parameters. Strings, bytes, typed arrays, and value buffers are decoded from the borrowed runs before the method runs. An object parameter arrives as a new wrapper that owns the reference the producer handed over; close it, or let the cleaner release it.
- Returns. A method may return any type but an iterator or a callback
interface. A scalar or enum is returned by value, and an optional one as
its
Opt*struct. An object is returned as a new strong reference (the wrapper keeps its own). A string, bytes, value buffer, or typed array is copied into a run allocated withkitchen_sink_alloc(8-aligned), which the producer adopts. - Failures. Whatever a method throws is caught in its vtable entry;
nothing unwinds through native frames. A method declared
throws: KvErrormay throw that domain’s exceptions (KvException.Rejected, say), which reach the producer with their code and payload fields, so a producer that propagates one hands the original caller the same typed error (with the message the producer renders from the fields). Anything else it throws, and anything athrows: anymethod throws, reaches the producer as code-1with the exception’s message. A method that doesn’t throw reports any failure as code-4.
Iterators
An iter<T> return is a NativeSequence<T>, a Sequence that’s also
AutoCloseable, so toList(), for, and the rest of the sequence
operations work on it. It can be iterated once. Each hasNext() pulls at
most one element. The native iterator is released when the sequence is
exhausted, on close(), or by the cleaner. A NativeSequence isn’t
thread-safe: iterate it from one thread at a time.
Known limitations
- Gradle builds aren’t exercised by the conformance suite, which compiles
the same sources with
kotlincagainst the JNA jar. - Every call goes through JNA’s reflective dispatch, which costs more per
call than a hand-written JNI binding. A typed-array argument is copied
twice (the
Listinto a primitive array, then into native memory). - Kotlin’s type system can’t express a callback return the producer would
reject (a null object for a non-optional
I, or a malformed record), so those-3paths aren’t reachable from Kotlin.
Node.js
The Node.js target generates an npm package: an ES module with TypeScript declarations that loads the producer’s shared library with koffi and calls its C ABI (revision 6) directly. There’s no generated C, no addon, and nothing to compile at install time. The JavaScript API is shared with the WebAssembly target; only the transport underneath differs, so code written against one runs against the other.
Node.js is a Tier 1 target: it tracks every ABI revision as it lands and runs the full conformance suite in CI.
What gets generated
For a library named kvstore (the snapshot fixtures use kitchen_sink):
node/
├── package.json ES module manifest, depending on a pinned koffi release
├── index.js the C signatures, the load-time checks, and the API
├── index.d.ts TypeScript declarations
├── runtime.js the shared runtime (codec, checks, errors, wrappers, load-time checks)
├── native.js the transport: loading the library with koffi and binding its symbols
├── debug.js the `./debug` export: leak counters for tests
├── debug.d.ts
└── README.md
The package name defaults to the package identity’s name; set name under
[generators.node] in weaveffi.toml to override it, and node_engine to
change engines.node (default >=18). The package’s one dependency is
koffi, pinned to an exact release (3.3.2).
Install and load
The generated directory is a complete package. Install it like any other, and npm fetches koffi (which ships prebuilt binaries for every platform it supports):
npm install ./node
Importing the package loads the library. The first of these that exists wins:
- the path in the
{PREFIX}_LIBRARYenvironment variable (KVSTORE_LIBRARY), the library file or the directory holding it; - the copy in the
{package}-{os}-{cpu}package npm installed for this platform (see Packaging); - a copy next to
index.js, whereweaveffi generate --devputs it; - the bare file name (
libkvstore.so,libkvstore.dylib,kvstore.dll), which the system’s library search resolves (LD_LIBRARY_PATH,DYLD_LIBRARY_PATH,PATH).
import { Store, EntryKind, KvstoreError } from 'kvstore';
const store = Store.open('/tmp/data');
store.put('greeting', new TextEncoder().encode('hi'), EntryKind.Volatile, null);
store.close();
If no candidate loads, the import throws an Error that lists the paths it
tried and names the environment variable.
Load-time checks
Before any other call, the import checks that the library matches the
bindings (see Load-time checks): the
library must implement ABI revision 6, and it must export every
declaration’s contract function, returning the hash the bindings were
generated with. index.js embeds one row per declaration, error code, and
callback method, each with its canonical signature:
const $contract = [
['kitchen_sink_contract_784cfd093415f2b5', 0xffcf2bd3b04aa002n, 'Gadget.new'], // constructor new(i64) -> Gadget
// ...
];
$verify($m, 'kitchen_sink', 6, $contract);
If a check fails, the import throws an Error naming the declaration:
kvstore: Store.put is missing from the library or kvstore: Store.put changed since these bindings were generated. Declarations the library has
and the bindings don’t are fine, so a library that only adds to its API
(declarations, error codes, callback methods) keeps working with older
bindings. Since the import fails the same way when the library can’t be
found, await import(...) in a try can fall back.
Names
A library is one namespace, and every declaration is a named export of the package: classes for interfaces and errors, frozen objects for C-style enums, functions, and types for records, rich enums, and callback interfaces.
import * as kitchen from 'kitchen_sink';
const gadget = new kitchen.Gadget(1n);
kitchen.optI32Id(null);
Functions, methods, and parameters are camelCase. A free function or
parameter whose name is a JavaScript reserved word gains a trailing
underscore (a function delete becomes delete_), and so does a free
function named init, which the WebAssembly target exports, so the two
APIs stay the same. Methods keep reserved words, which are legal property
names (store.delete(key)), except that an instance method named close or
constructor, and a static named name, length, prototype, or
caller, gains one too
(reserved member names).
Record fields keep their IDL spelling. Doc comments in index.d.ts name
declarations in this spelling too: an IDL doc or deprecation message that
says `new_op` reads `newOp` there.
Inside index.js, each declaration is bound under its public name plus $
(Gadget$) and exported under the public name, so no declaration can
shadow a global the generated code uses, such as Map or TypeError.
Type mapping
| IDL type | TypeScript type | Notes |
|---|---|---|
i8, i16, i32, u8, u16, u32 | number | A fractional, non-finite, or out-of-range argument throws a RangeError; nothing wraps |
i64, u64 | bigint | Integral numbers in range are accepted as arguments; anything else throws a RangeError |
f32, f64 | number | NaN, the infinities, and -0 round-trip; an f32 argument rounds as Float32Array does |
bool | boolean | |
string | string | UTF-8 in a run, so interior NULs survive |
bytes | Uint8Array | |
| record | interface | A plain object; fields keep their IDL names |
| C-style enum | enum | A frozen object with forward and reverse mappings (negative values too) |
| rich enum | tagged union | { tag: 'Circle', radius: 2.5 } |
| interface | class | See Objects and lifetime |
| callback interface | interface | Any object with the methods; see Callback interfaces |
T? | T | null | undefined is accepted as null. An optional scalar or C-style enum crosses directly as a {prefix}_opt_* struct, with no buffer |
[T] | T[] | A list of i8, i16, i32, i64, u16, u32, u64, f32, or f64 crosses as a typed array: an argument may be an array (checked element by element) or the matching typed array (Float64Array for [f64], passed as is), and a result is a plain array |
{K: V} | Record<string, V> | Record<number, V> for integer keys of 32 bits or fewer, Partial<Record<E, V>> for C-style enum keys; keys are property names (strings) at run time, and a Map is accepted as an argument |
iter<T> | NativeIterator<T> | Lazy; an IterableIterator<T> with close() and [Symbol.dispose]() |
Arguments are checked before the native call: a value of the wrong type
throws a TypeError, and an integer that is fractional or out of its type’s
range a RangeError, whether it’s an argument, an element of a list, a
field of a record, or a callback’s return value.
Value buffers are encoded and decoded by one function per type: each record
and rich enum ($w$Entry, $r$Entry), each interface carried as an object
token, and each distinct optional, list, and map type in the API, named by
its canonical stem ($w_list_opt_Entry writes [Entry?]). Call sites name
these functions.
How values cross
index.js lists the C signature of every function it calls ($sigs), one
slot kind per C value: a scalar (i32, bool, …), an optional scalar
(opt_i64), a run (run), a pointer (ptr), a callback-interface argument
(cb), and the slots the transport fills in itself (the error slot err,
an iterator’s item slot out:<kind>, and an async launcher’s completion
done:<kind> and context ctx):
const $sigs = {
kitchen_sink_opt_mixed: ['opt_u16', ['f64', 'opt_f32', 'opt_i64', 'run', 'err']],
kitchen_sink_do_cancellable: ['void', ['run', 'ptr', 'done:run', 'ctx']],
kitchen_sink_StreamItemsIterator_next: ['i32', ['ptr', 'out:run', 'err']],
// ...
};
native.js declares the C structs ({prefix}_run, the {prefix}_opt_*
structs, {prefix}_error, and the callback-interface argument) with koffi’s
type syntax and binds each function by value, exactly as the header declares
it. A bound function takes and returns one JavaScript value per C value: a
Uint8Array for a run (lent for a parameter, and a copy for a return, whose
run it then releases with {prefix}_run_free), the value or null for an
optional scalar, a bigint handle or null for an object. After a
synchronous call it reads the error slot, and on a failure it clears the
slot and throws. The generated API above it does the rest: it encodes
strings as UTF-8, checks and copies typed arrays, encodes and decodes
buffers, and lends, adopts, and clones objects.
poke(times) {
const $self = $lend(this, Gadget$);
try {
const $a0 = $check.I32(times, 'times');
return $f.kitchen_sink_Gadget_poke($self, $a0);
} catch ($e) {
throw $from$KitchenErrors($e);
} finally {
$unlend(this);
}
}
A typed-array argument is lent to the library in place: its elements are aligned for their type, since a typed array’s offset is always a multiple of its element size.
Objects and lifetime
An interface is a class whose instances each own one strong reference to the
native object. close() releases it, and so does [Symbol.dispose]() (for
using declarations); both are idempotent, and a wrapper that is garbage
collected unclosed is released by a FinalizationRegistry. Every call lends
the wrapper to the native side for its duration, so a close() that races
the call (from a callback, or while an async method is pending) waits for it
to return. Using a closed wrapper throws a code -3 error.
The synchronous constructor named new is the class constructor; other
constructors are static factories, and a class without one can’t be
constructed directly. Objects returned, awaited, iterated, decoded from a
record, or passed to a callback method are new wrappers the receiver owns.
Two wrappers may share one native object.
Errors
Every error extends the package’s root class, named after the package
(here KitchenSinkError), which carries the ABI code. When the package’s
own name is also a declaration’s (the codec sample’s error domain is
CodecError), the root class adds Library (CodecLibraryError).
- Each error domain is a class, named by the shared rule (a domain
KitchenErrorsisKitchenError,KvErrorstaysKvError, andFailurebecomesFailureError), and each of its codes a subclass (NotFoundError) with a staticCODEand the IDL message as its default message. Codes of different domains may share a value. Payload fields become properties. A code without fields is constructed asnew InvalidPathError(message?); a code with fields takes them first:new RejectedError({ key, reason }, message?). A code whose class would take a name another export has gains its domain’s name first. - A function declared
throws: SomeDomainfails with that domain’s classes. Domains are open: a positive code the bindings don’t know (the library added it later) is an instance of the domain class itself, with itscodeand message. - A function declared
throws: anyfails with the root class, code -1, and the library’s message. - A cancelled call rejects with
CancelledError(code -5). - Other runtime failures throw the root class itself: -2 producer panic, -3 marshalling failure, -4 a callback implementation failed.
A failure of a function that doesn’t declare throws is a producer bug, and
the binding throws the root class with the code and the producer’s message
(see the trap policy).
Async and cancellation
An async function returns a Promise. Its completion is a JavaScript
function koffi registered once per result type, and it may arrive on any
producer thread; koffi runs it on the JavaScript thread, and it settles the
promise. While any call is pending, the transport keeps the event loop
alive, so a script that awaits nothing else still waits for it. A
cancellable function takes an optional last argument with an AbortSignal:
export declare function doCancellable(input: string, options?: { signal?: AbortSignal }): Promise<string>;
Aborting the signal cancels the native token, and the call rejects with
CancelledError. An already-aborted signal cancels the call before it
starts.
Callback interfaces
Any object with the interface’s methods implements it; the methods are
camelCase. Arguments arrive converted: strings and bytes as string and
Uint8Array, records decoded, and objects as new wrappers the
implementation owns (close them, or let the garbage collector release
them). A parameter of an optional callback interface (Cb?) takes null
for none.
An implementation crosses as the {prefix}_{Cb} struct: a context, an
integer the package maps back to the implementation, and the interface’s
static vtable. The vtable is built once per interface, the first time an
implementation is passed, from JavaScript functions registered with koffi
(free first, then one per method); it lives as long as the process, so the
number of registered callbacks stays small however many implementations are
live. The library’s call to free releases the implementation.
A method’s return value is checked and handed to the library in its family’s form:
| IDL return | Return from JavaScript | What the library receives |
|---|---|---|
direct (numbers, bool, C-style enums) | the value | the value (integers range-checked) |
optional scalar (i32?, Mode?, …) | the value, or null | a {prefix}_opt_* struct |
numeric list ([f64], …) | an array or the matching typed array | a copy in a run from {prefix}_alloc, which the library adopts |
string, bytes | a string, a Uint8Array | a copy in a run the library adopts |
record, rich enum, other T?, [T], {K:V} | the value | its encoding, in a run the library adopts |
I | a wrapper (never null) | a new strong reference to its object |
I? | a wrapper or null | a new strong reference, or null |
Nothing unwinds through native code; how a failure reaches the library
follows the method’s throws:
- A method declared
throws: SomeDomainmay throw one of that domain’s errors, and the library receives its code and fields. (A Rust producer re-renders the message from the fields.) Any other exception is reported as code -1 with its message. - A method declared
throws: anyreports any exception as code -1 with its message. - A method that doesn’t declare
throwsreports an exception, or a return value of the wrong type, as code -4 with its message.
const policy = {
ttlFor(key, requested) {
return key.startsWith('tmp/') ? 60n : requested;
},
admit(entry) {
if (entry.key.startsWith('secret')) {
throw new RejectedError({ key: entry.key, reason: 'no secrets' });
}
return { ...entry, tags: ['admitted'] };
},
route(key, home) {
return home;
},
};
store.setPolicy(policy);
Threading
The producer may call back from any thread, and every JavaScript call runs on the JavaScript thread:
- A call made on the JavaScript thread (because the JavaScript thread is inside a call into the library) runs directly, nested inside that call.
- A call made on any other thread is queued by koffi for the JavaScript thread and runs from its event loop, while the producer thread waits for it to return. Nothing runs while the JavaScript thread is busy, so such calls are delivered only once the current JavaScript task returns to the event loop.
- The library’s release of an implementation (its vtable’s
free) may come from any thread and follows the same rules.
The waiting in the second rule can deadlock: if the JavaScript thread is inside a synchronous call into the library that itself waits for the thread making the callback (joins it, or waits on a lock it holds), neither thread can proceed. So:
- Make calls that wait for callbacks from other threads
async, or have the producer call back on the calling thread. - Return to the event loop regularly while callbacks from other threads are expected: a long-running JavaScript task delays them.
Iterators
An iter<T> result is a lazy NativeIterator<T>: each next() makes one
native call. The native iterator is destroyed when it’s exhausted, when it
fails, on return() (which for...of calls on break), on close() or a
using declaration, or when the iterator is garbage collected.
using chunks = kitchen.streamChunks();
const first = chunks.next(); // released when the block exits
Packaging
weaveffi package writes npm tarballs in the esbuild-style layout: one
{package}-{os}-{cpu} package per desktop platform, gated by npm os and
cpu and carrying only that platform’s library, plus the main package,
which lists them in optionalDependencies. npm install then fetches the
main package, koffi, and the one platform package that matches, and the
import loads the library from it. See Packaging.
Leak counters
The package’s ./debug export reads the library’s live-resource counters,
for tests of code that uses the bindings. It isn’t part of the API:
import { debugLive } from 'kvstore/debug';
debugLive(0); // live objects, as a bigint (1 callbacks, 2 iterators, 3 cancel tokens, 4 runs)
Kind -1 is 1n when the library counts at all (built with weaveffi’s
leak-check feature); otherwise every counter is 0n.
Known limitations
- A callback from another thread waits for the JavaScript thread, so a synchronous call that waits for that callback’s thread deadlocks (see Threading).
- A callback implementation that holds a wrapper of the object retaining it forms a cycle the garbage collector can’t see; close the wrapper or release the callback explicitly.
- The package runs on the platforms koffi supports, which ships prebuilt binaries for the desktop and server platforms Node.js runs on.
- A numeric list result is copied into a plain array. As an argument, the matching typed array is lent to the library without a copy, while a plain array is checked and copied first.
- The package is ESM only, and its declarations need TypeScript 5.2 or
later (for
Symbol.dispose).
WebAssembly
The WebAssembly target generates an npm package for a wasm32-unknown-unknown
build of the library: an ES module with TypeScript declarations over a
transport that stages values in the module’s linear memory and calls its
C ABI (revision 6). The JavaScript API is the
Node.js target’s, so the sections there on names, types, objects,
errors, callbacks, and iterators apply here unchanged; this page covers what
differs.
WebAssembly is a Tier 2 target: it may lag behind a new ABI revision, but it passes the same conformance suite before a release.
What gets generated
For a library named kvstore (the snapshot fixtures use kitchen_sink):
wasm/
├── package.json ES module manifest
├── index.js the C signatures, `init()`, and the API
├── index.d.ts TypeScript declarations
├── runtime.js the shared runtime (codec, checks, errors, wrappers)
├── debug.js the `./debug` export: leak counters for tests
├── debug.d.ts
├── linear.js the transport: loading, staging, table functions
└── README.md
The package name defaults to the package identity’s name; set name under
[generators.wasm] to override it. The package has no dependencies.
weaveffi package writes the npm tarball wasm/{package}-{version}.tgz with
the module weaveffi build linked for wasm32 as {library}.wasm.
Build the module
The transport installs async completions and callback-interface methods in the module’s function table, so link the module with an exported, growable table:
RUSTFLAGS="-C link-arg=--export-table -C link-arg=--growable-table" \
cargo build --release --target wasm32-unknown-unknown
weaveffi build --platforms wasm32 passes those flags itself and writes the
module to target/weaveffi/wasm32/{library}.wasm.
Load
init() loads the module and checks it before any other export works: the
module must implement ABI revision 6 and export every declaration’s contract
function with the hash the bindings were generated with (see the
Node.js page). A failed check rejects with an
Error naming the declaration (kvstore: Store.put changed since these bindings were generated). Until the promise resolves, every other call
throws.
import { init, Store } from 'kvstore';
await init();
const store = Store.open('/tmp/data');
Without an argument, init() reads the file named by the {PREFIX}_LIBRARY
environment variable (KVSTORE_LIBRARY) when it’s set on Node.js, and
otherwise loads {library}.wasm from next to index.js (by fetch in a
browser, from disk on Node.js). It also takes a URL, a path (resolved
against index.js), bytes, a Response, or a compiled
WebAssembly.Module:
export declare function init(
source?: string | URL | BufferSource | WebAssembly.Module | Response,
): Promise<void>;
init() may be called more than once; later calls return the same promise,
and a failed load can be retried.
Transport
linear.js binds the same C signatures ($sigs) the Node.js transport
does, so the API above it is identical. Each bound function lowers its
arguments to the module’s C calling convention for wasm32, which Rust’s
extern "C" follows: integers of 32 bits or fewer, bool, size_t, and
pointers are i32; int64_t and uint64_t are i64; float and
double are f32 and f64. A struct (a {prefix}_run, a
{prefix}_opt_*, or a callback-interface argument) is passed indirectly, as
the i32 address of a copy the caller owns, and a struct return comes back
through a hidden first i32 parameter, the address the callee writes it to,
with the function returning nothing. None of the ABI’s structs is a single
scalar, so none is passed directly. These are the export types a build of
the samples has:
kvstore_Store_tick (i32 self, i64 seconds, i32 out_err) -> i64
kvstore_Store_open (i32 path*, i32 out_err) -> i32
kvstore_Store_put (i32 ret*, i32 self, i32 key*, i32 value*, i32 kind, i32 ttl_seconds*, i32 out_err) -> ()
kvstore_Store_expires_at (i32 ret*, i32 self, i32 key*, i32 out_err) -> ()
kvstore_Store_subscribe (i32 self, i32 listener*, i32 out_err) -> i32
kvstore_run_free (i32 run*) -> ()
codec_echo_opt_bool (i32 ret*, i32 value*, i32 out_err) -> ()
The copies live on a small stack the transport carves from linear memory,
popped as each call returns. A run argument is staged in a run from
{prefix}_alloc (8-aligned, so a typed array’s elements are aligned for
their type) and released with {prefix}_run_free once the call returns; a
returned run is copied out and released the same way. The transport reads
and writes multi-byte values through a DataView. One error slot and one
iterator item slot are reused by every call; they, the stack, and the
callback vtables live in 8-byte-aligned blocks carved from arenas the
transport allocates once and never frees. The ./debug export’s
debugLive(4) leaves those arenas out of its count of runs. Object handles
are linear-memory addresses.
Async completions and callback-interface methods are JavaScript functions
installed in the module’s function table, with the same lowering in
reverse (a method returning a run or an optional scalar writes it through
its hidden first parameter). The transport uses WebAssembly.Function where
the engine provides it and otherwise compiles a tiny module that imports the
function with the needed signature and re-exports it, so no experimental
flag is needed.
Type mapping
The mapping is the Node.js target’s: 64-bit integers are bigint, bytes is
Uint8Array, records are plain objects, rich enums are tagged unions,
C-style enums are frozen objects, interfaces are classes with close() and
[Symbol.dispose](), optionals are T | null, lists are arrays (a numeric
list argument may also be the matching typed array), maps are Record
objects (a Map is accepted as an argument), and iter<T> is a lazy
NativeIterator<T> with close(). Integer arguments are range-checked the
same way, so a value that throws a RangeError on one target throws it on
the other. A usize is 32 bits on wasm32, so a wider value fails the
producer’s conversion with code -3.
Async and cancellation
Async functions return a Promise, and cancellable ones take an optional
{ signal } last argument, exactly as on Node.js. The module is
single-threaded, and on wasm32 the default executor polls a future inline
until it completes, inside its launcher, so an async call has completed by
the time the Promise is returned; only a signal aborted before the call
can cancel it. A future that’s still pending once nothing can wake it (it
awaits something only another thread or a reactor would complete) fails
with code -1 instead (async function suspended with no executor on wasm32). A cancelled call rejects with CancelledError (code -5).
Callbacks and errors
Callback interfaces work as on Node.js: returns of every family (a string,
bytes, buffer, or typed-array return is copied into a run from
{prefix}_alloc that the producer adopts, an optional scalar is a
{prefix}_opt_* struct, and an object return is a new reference), errors
reported by each method’s throws (a domain’s codes with their fields, -1
for throws: any, -4 for a method that doesn’t throw), and null for an
optional callback (Cb?), which passes a null vtable. The vtable starts
with its size, flags (0), and free entries, like any consumer’s.
There are no threads, so a callback runs only while a call into the module is on the stack, on the calling thread, and the Node.js target’s threading rules don’t arise.
Traps
Because wasm32-unknown-unknown aborts on a panic, a producer panic traps
the module. The call that trapped fails with the package’s root error, code
-2 (the native library trapped: unreachable). A trap can leave the
module’s memory inconsistent, so it also poisons the instance: every later
call fails with code -2 (kvstore: the WebAssembly instance trapped earlier (...) and can't be used anymore) without running, while releases (closing
a wrapper or an iterator, a garbage-collected wrapper, a cancel token) do
nothing, so no finalizer throws. Load the module again in a new process or
page to recover.
Known limitations
- The module must export its function table and allow it to grow.
- An async call can’t be cancelled once launched, since it completes before its launcher returns, and a future that waits on another thread or an external event fails with code -1.
- A producer panic traps rather than unwinding, and the instance is unusable afterward (see Traps).
- Calls nested more than a few hundred deep (callbacks that call back into
the module) exhaust the transport’s 16 KiB stack of struct copies and
throw a
RangeError. - Only
wasm32-unknown-unknownbuilds are supported.
Python
The Python target produces a pip-installable package of pure-Python
ctypes bindings over the C ABI (revision 6). There’s no compilation step,
no native extension, and no third-party runtime dependency; the package
works on any Python 3.10+ interpreter that can load the producer library.
The implementation module is fully annotated and the package ships
py.typed, so type checkers read the bindings themselves (there’s no
separate stub to drift out of date), and the generated code is written to
pass mypy --strict.
Every value crosses the boundary as one C value. Records and rich enums
are frozen dataclasses that cross as value buffers. Interfaces are
reference-counted wrapper classes with a context manager. Error domains
are exception classes. Callback interfaces are abstract base classes the
consumer subclasses. Async functions are coroutines whose cancellation
cancels the native call, and iter<T> returns are lazy
NativeIterator[T] objects.
Python is a Tier 1 target: it tracks every ABI revision as it lands and runs the full conformance suite in CI.
What gets generated
For the kvstore sample (package name kvstore, C prefix kvstore):
python/
├── pyproject.toml # PEP 621 metadata, built with setuptools
├── README.md
└── kvstore/ # the import package, named after the C prefix
├── __init__.py # re-exports the module's __all__
├── kvstore.py # runtime, prototypes, and wrappers
└── py.typed # PEP 561 marker
The distribution name is the package identity’s name and the import
package is its C prefix, so a crate named key-store installs as
key-store and imports as key_store. Both are configurable:
[generators.python]
name = "kvstore-python" # distribution name (default: package name)
import_name = "kvstore_py" # import package (default: C prefix)
requires_python = ">=3.12" # default ">=3.10"
A library is one namespace, and so is the package: every record, enum,
error class, interface, callback interface, and free function is exported
from the package itself under its IDL name (functions in snake case). The
module lists its public names in __all__ (the error classes,
LibraryLoadError, NativeIterator, every type, and the free functions),
so from kvstore import * and the package’s __init__.py export the API
and none of the runtime’s helpers. Annotations use builtin generics and
X | None.
Install and load
weaveffi generate -o bindings --target python # in the producer crate
pip install bindings/python
At import, the module loads the producer library from the first of:
- the path in
{PREFIX}_LIBRARY(for exampleKVSTORE_LIBRARY), - a library bundled inside the package directory (what
weaveffi packageproduces, and whereweaveffi generate --devcopies the debug build), and - the system loader’s search path, by platform file name
(
libkvstore.dylib,libkvstore.so, orkvstore.dll).
It then makes the two load-time checks
before binding anything else. kvstore_abi_version() must report revision
6, and every declaration the bindings were generated with (every function,
interface member, type, error code, and callback method) must have its
contract function in the library, returning the hash the bindings embed.
The module holds one row per declaration: the contract function, the
hash, and the declaration’s path, with its canonical signature:
_CONTRACT: list[tuple[str, int, str]] = [
("kvstore_contract_c6c5d9ee1b7cfa9e", 0x36b344095a0f5bf9, "Store.rank"), # method rank(Scorer) -> [string] throws KvError
...
]
When the library can’t be loaded, or a check fails, the import raises
LibraryLoadError, an ImportError subclass whose message says what went
wrong and whose path names the library:
kvstore.kvstore.LibraryLoadError: Store.put changed since these bindings were generated (/opt/lib/libkvstore.dylib)
The other messages are Store.put is missing from the library, a C ABI
mismatch naming both revisions, a library that doesn’t export
kvstore_abi_version, and the loader’s own error with a hint to set
KVSTORE_LIBRARY. A stale binding never misreads a buffer at runtime.
Declarations the library has and the bindings don’t are fine, so a library
that grew new functions, error codes, or callback methods still loads.
Since the failure happens during the import, catch it as ImportError
around the import statement.
Every C prototype is then bound once, in a module-level table:
_c_Store_count = _bind("kvstore_Store_count", ctypes.c_uint64, ctypes.c_void_p, ctypes.POINTER(_ErrorStruct))
On macOS, the system python3 strips DYLD_LIBRARY_PATH, so prefer
{PREFIX}_LIBRARY there.
Type mapping
Parameters accept abstract containers (any Sequence or Mapping) and
returns hand out concrete ones (list, dict). Every value is one C value
in every position (a parameter, a return, an async result, an iterator
item, and a callback method’s arguments and return), and the runtime
mirrors the C structures as ctypes.Structure subclasses passed and
returned by value: _Run for {prefix}_run (a pointer and a byte length)
and _OptI32, _OptF64, and so on for each {prefix}_opt_{prim} (a
presence flag and a value).
| IDL type | Python type | Crosses the ABI as |
|---|---|---|
i8 to u64 | int | c_int8 to c_uint64, range-checked |
f32, f64 | float | c_float, c_double |
bool | bool | c_bool |
| C-style enum | IntEnum subclass | c_int32 |
scalar or enum T? | T | None | _Opt{Prim} (an enum’s is _OptI32) |
string | str | _Run of UTF-8 |
bytes | bytes | _Run of the bytes |
[i8] to [u64], [f32], [f64] | Sequence[int] or Sequence[float] in, list out | _Run of the packed elements (a typed array) |
| record | frozen @dataclass | _Run holding a value buffer |
| rich enum | base class plus one frozen @dataclass per variant | _Run holding a value buffer |
other T?, [T], {K:V} | T | None, Sequence[T], Mapping[K, V] in; T | None, list[T], dict[K, V] out | _Run holding a value buffer |
| interface | wrapper class | c_void_p |
interface ? | ... | None | c_void_p, null for None |
| callback interface | subclass of the generated ABC | _{Name}Arg (a context and a vtable) |
callback interface ? | ... | None | _{Name}Arg with a null vtable for None |
iter<T> | NativeIterator[T] | iterator handle |
ctypes truncates an out-of-range integer to the parameter’s C width
without a word, so every integer argument is checked first: a value out of
range raises OverflowError naming the parameter
(a: 2147483648 is out of range for i32), and a non-integer raises
TypeError. The checks run before anything is lent or registered for the
call, so a failed check leaks nothing.
An optional scalar (i64?, bool?, Priority?) never touches a value
buffer: None passes an absent _Opt{Prim}, and a returned one becomes
the value or None. A numeric list parameter accepts any sequence or
iterable of numbers (a list, a tuple, a range, a generator); it’s
packed into an array.array with range checks, whose buffer Python aligns
for every element type, and lent to the call. An array.array of the
matching type code is lent as is, without a copy. A str or bytes
argument is refused rather than reinterpreted. Returned typed arrays are
copied into a list and released.
Strings and bytes pass without per-byte loops: a str is encoded once and
its bytes are lent to the call as a run, so interior NUL characters
survive. Returned strings, bytes, typed arrays, and buffers are copied with
ctypes.string_at and released with {prefix}_run_free.
Every record and rich enum has one writer and one reader function
(_write_Entry, _read_Entry), and so does every distinct composite type
the API uses, named by the composite’s canonical stem
(_write_list_string, _read_map_string_Store, _read_opt_Entry); a call
site makes one call instead of inlining a loop. Lists of a fixed-width
number type inside a buffer are packed and unpacked with one struct call.
A value out of range for its field raises OverflowError while encoding. A
decoded buffer that’s truncated, has trailing bytes, an invalid flag,
invalid UTF-8, an undeclared enum value, or a repeated map key raises
InternalError with code -3.
Records are @dataclass(frozen=True, slots=True): they compare and hash
by value (a record holding a list or dict field compares by value but
can’t be hashed), and a changed copy comes from dataclasses.replace:
entry = store.get("alpha")
renamed = dataclasses.replace(entry, tags=["archived"])
Rich-enum variants work with isinstance and with match:
match change:
case kvstore.ChangePut(entry=entry, replaced=True):
print("replaced", entry.key)
case kvstore.ChangeRemoved(key=key):
print("removed", key)
The module starts with from __future__ import annotations, so
annotations name types declared later in the file without quotes.
Backticked identifiers in IDL docs and deprecation messages are rewritten
to their Python spellings in docstrings and DeprecationWarnings.
Objects and lifetime
An interface wrapper holds one strong reference and releases it exactly
once: from close(), the with statement, or the __del__ backstop.
close() is idempotent, and using a closed wrapper raises ValueError.
Each call lends the pointer for its duration, so close() from another
thread while a call is in flight defers the release until the call
returns. Two wrappers compare equal (and hash alike) when they hold the
same native object, so store.share() == store and a record holding a
Store compares by identity. An interface member named close is
close_, so it never replaces the wrapper’s own (reserved member
names).
A constructor named new becomes __init__; other constructors are
@classmethod factories:
@classmethod
def open(cls, path: str) -> Store:
_err = _ErrorStruct()
_ret = _c_Store_open(_run_in(path.encode("utf-8")), ctypes.byref(_err))
if _err.code:
raise _kv_error_from(*_read_error(_err))
return cls._adopt(_required(_ret))
Objects returned by the producer, decoded from a buffer, or passed to a callback are adopted into new wrappers. Writing an object into a value buffer (a record field or a list element) mints a new reference only after the whole argument list has encoded, so a failed encoding leaks nothing.
Errors
Every declared error derives from the package’s root Error (named
{PascalName}Error if the API declares its own Error type), which
carries code and message. Each error domain is a subclass named by the
shared rule (KvError stays KvError, KitchenErrors becomes
KitchenError, Failure becomes FailureError). Each code is a subclass
of its domain named {Code}Error (KeyNotFoundError), also reachable as
KvError.KeyNotFound, carrying its stable CODE. When {Code}Error would
shadow a Python builtin (TimeoutError) or another declaration, it’s
qualified with the domain’s stem (KvTimeoutError). A code’s payload
fields are constructor arguments and attributes; a field named like an
exception attribute (message, code, args) gets a trailing _:
try:
store.get("nope")
except kvstore.KvError.KeyNotFound as e:
print(e.code, e.key, e.message) # 1001 nope key not found: nope
What a failed call raises follows its throws:
throws: SomeDomain: the code’s class. Codes are matched within the callable’s domain, so two domains may reuse a value. Domains are open: a positive code these bindings don’t know (from a newer library) raises the domain’s base class with its code and message.throws: any: the rootErrorwith code -1 and the producer’s message.- A negative code on a throwing call (a panic, a marshalling failure, or a
failed callback) raises the root
Errorwith that code; the constants areGENERIC_ERROR_CODE(-1),PANIC_ERROR_CODE(-2),MARSHAL_ERROR_CODE(-3), andFOREIGN_ERROR_CODE(-4).
A call that declares no errors can only fail through a bug, so it follows
the trap policy: it
raises InternalError, a RuntimeError subclass outside the Error
hierarchy whose message names the code and the producer’s message
(InternalError: (-3) ...). A cancelled async call (-5) raises
asyncio.CancelledError instead.
Each call passes a fresh error slot, which the producer overwrites. Error
messages cross as UTF-8 bytes plus a length, so they may contain any
character; an empty message is "".
Async and cancellation
An async function is an async def that must run on an asyncio event
loop. The launcher receives a static completion trampoline and an integer
key; the trampoline takes ownership of the result (one C value, like a
sync return) on the producer’s thread and settles the future through
call_soon_threadsafe:
async def open_store(path: str) -> Store:
_call, _future = _async_begin()
try:
_c_open_store(_run_in(path.encode("utf-8")), _open_store_completion, _call)
except BaseException:
_async_abandon(_call)
raise
_result: Store = await _future
return _result
The launcher copies everything it needs before it returns, so the arguments’ memory needn’t outlive the call.
For a cancellable function, each call owns a native cancel token.
Cancelling the awaiting task (directly, through asyncio.wait_for, or by
cancelling a gather) cancels the token, waits for the producer’s
cancelled completion, and raises asyncio.CancelledError. Cancelling the
task awaiting a function that isn’t cancellable stops the wait only; the
native call runs to completion and its result is dropped.
Callbacks
A callback interface is an abc.ABC with one abstract method per IDL
method. Passing an instance registers it in a handle table under an integer
key, and the call passes the producer a _{Name}Arg structure holding that
key as ctx and the address of the interface’s one vtable; None for an
optional callback parameter passes a null vtable. The vtable is built the
first time an implementation is passed and kept for the process lifetime.
It starts with the header (its size, flags, and the shared free
entry), and the producer’s free(ctx) removes the table entry, so an
implementation lives exactly as long as the producer holds it. flags is
0: the producer may call any method from any thread.
Each method’s vtable entry is a trampoline that takes the method’s C
arguments and returns its one C value. A ctypes callback can’t return a
structure, so a method returning a _Run (a string, bytes, typed array, or
buffered value) or an _Opt{Prim} is a libffi closure the runtime builds
directly, through the libffi ctypes itself runs on; every other method is
a plain ctypes callback.
Trampolines run on whichever thread the producer calls from; ctypes
acquires the GIL first. A trampoline adopts the object arguments first,
converts the rest (an optional scalar arrives as T | None, a typed array
as a list, and a run is copied, since it’s only lent), calls the method,
and returns:
- a number,
bool, or enum, checked for its type and range inside the trampoline (so a wrong return is reported as a failure rather than truncated); - an optional scalar as its
_Opt{Prim}; - an object as a fresh strong reference the producer adopts (
Noneis allowed only forI?); - a
str,bytes, typed array, record, or other buffered value as a run allocated with{prefix}_alloc, which the producer adopts and frees.
def _Loader_load(ctx: int | None, key: _Run, out_err: int | None) -> _Run:
try:
_ret = _callback_get(ctx).load(_peek_str(key))
return _alloc_run(bytes(_ret))
except BaseException as exc:
_callback_fail(out_err, exc, _GENERIC, KvError)
return _Run()
Nothing unwinds through C. A method that throws a domain may raise that
domain’s codes, which reach the producer as that code with the fields as
the error payload ({prefix}_error_set and {prefix}_error_set_payload):
class EmptyLoader(kvstore.Loader):
def name(self) -> str:
return "empty"
def fallback(self, key: str) -> kvstore.Store | None:
return None
def load(self, key: str) -> bytes:
raise kvstore.KeyNotFoundError(key=key)
A Rust producer decodes such a code into its typed error, so the caller of
the original function sees the domain’s own message rendered from the
fields. Any other exception, or a return of the wrong type, reaches the
producer as code -1 with the exception’s message (-4 for a method that
declares no errors); a Rust producer receives it as a ForeignError, which
the kvstore sample turns into KvError.CallbackFailed.
Iterators
An iter<T> return is a NativeIterator[T], a lazy iterator: each
next() makes one native next call through the pre-bound function,
receiving the item in one out slot of its C type, and the handle is
released on exhaustion, close(), the end of a with block, or garbage
collection. A closed iterator is exhausted.
for key in store.keys(None):
print(key)
with store.entries("user.") as entries:
first = next(entries) # the rest is released when the block ends
Packaging
weaveffi package --target python writes one wheel per desktop platform
built, python/{name}-{version}-py3-none-{platform}.whl (the distribution
name escaped for a wheel file name, so Key-Store becomes key_store),
with the producer library inside the import package. The platform tag
matches the build: the [build] macOS deployment target
(macosx_11_0_arm64), the newest glibc the library links against on Linux
(manylinux_2_17_x86_64 or later), or win_amd64. The wheels install
with pip and upload with twine; Android, iOS, and wasm32 builds have
no wheel platform and are skipped. See Packaging.
Known limitations
ctypesdispatch costs more per call than a compiled extension; hot loops that cross the boundary per element will feel it. The bindings keep the per-call work small (prototypes and vtable addresses are resolved once, and the error check is inline), but each call still allocates its error slot, and each integer argument costs a range check.- A callback method that returns a structure needs libffi, which the
runtime finds through the
_ctypesextension or by name (ctypes.util.find_library("ffi")). A Python whosectypeslinks libffi statically and hides its symbols, with no libffi installed, raisesOSErrorthe first time an implementation of such an interface is passed. The closures are built for the 64-bit platforms wheels target. - A typed-array parameter is copied into an
array.arrayunless it already is one of the matching type code; a NumPy array is copied element by element. - The package’s namespace also holds the typing names the module imports
(
Any,Callable,ClassVar,Iterable,Iterator,Mapping,Sequence): a declared type with one of those names still works at run time, but type checkers reject the module. - A long-running callback stalls the producer thread that called it, and a callback that waits for the thread blocked in the calling Python code deadlocks.
LibraryLoadErroris raised during the import, so it can only be caught asImportError(the package isn’t importable to name the class).
.NET
The .NET target emits a standalone C# class library over the C ABI
(revision 6). Native calls go through source-generated
[LibraryImport]
declarations whose slots are all blittable, with runtime marshalling
disabled for the assembly ([assembly: DisableRuntimeMarshalling]), and
callbacks go through [UnmanagedCallersOnly] function pointers, so the
bindings are trim- and AOT-friendly. The project targets net8.0 and builds
with any newer SDK.
.NET is a Tier 1 target: it tracks every ABI revision as it lands and runs the full conformance suite in CI.
What gets generated
For a package named kvstore:
dotnet/
Kvstore.cs generated API: types, wrappers, native imports, contract
Runtime.cs fixed runtime: exceptions, loader, codec, async and iterator helpers
Kvstore.csproj SDK-style project with the NuGet metadata
README.md
The namespace, assembly name, and NuGet id are the package name in
PascalCase (my-kv becomes MyKv). Set name to override all three:
[generators.dotnet]
name = "Acme.Storage"
The whole library is one namespace. Records, enums, interfaces, callback
interfaces, and exceptions sit directly in it, and the free functions are
static methods of the library class, {Namespace}Library (from the
namespace’s last segment), which also holds Check() and AbiVersion:
using Kvstore;
using var store = await KvstoreLibrary.OpenStore("/data");
var stats = KvstoreLibrary.Summarize(store, null);
using static Kvstore.KvstoreLibrary; brings the functions into scope
unqualified. A function spelled like a member the class already has
(Check, AbiVersion, Equals, ReferenceEquals) or like the class
itself gains a trailing _. The project generates an XML documentation
file, so the IDL’s docs show up in IntelliSense; backticked identifiers in
them (`new_op`) are rewritten to their C# spelling (NewOp).
Build and load
Reference the generated project from yours, or pack it:
dotnet add reference bindings/dotnet/Kvstore.csproj
dotnet pack bindings/dotnet/Kvstore.csproj -c Release
The bindings load the native library by its base name (kvstore), so .NET
probes libkvstore.dylib, libkvstore.so, or kvstore.dll next to the
app and on the platform’s library path. Set KVSTORE_LIBRARY (the
{PREFIX}_LIBRARY variable) to a full path to load that file instead (and
only that file). The loader is a DllImportResolver on the generated
assembly.
weaveffi package writes the project to dotnet/Kvstore/ with each desktop
platform’s library under runtimes/<rid>/native/, where NuGet resolves it
at restore time, and runs dotnet pack on it to produce
dotnet/Kvstore.{version}.nupkg (so it needs the .NET SDK; without it the
package is skipped with a warning). See Packaging.
Load-time checks
Every import resolves through the generated resolver, which loads the
library once, checks {prefix}_abi_version() against 6, and then checks
the contract: for every declaration the
bindings were generated with (each function, interface, member, record,
enum, callback interface and method, error domain, and error code), it
resolves the declaration’s contract function by name, calls it, and
compares the hash it returns with the embedded one:
static partial void VerifyContracts(IntPtr library)
{
VerifyContract(library, new (string, ulong, string)[]
{
("kvstore_contract_2bef5883c0f5eed1", 0xe3faf8ccf74791cfUL, "Store.put"), // method put(string, bytes, EntryKind, i64?) -> Entry throws KvError
// ... one row per declaration
});
}
Declarations the library has and the bindings don’t are fine, so a library that only adds declarations (new functions, error codes, or callback methods) keeps working with older bindings.
A library that can’t be found or loaded, or that doesn’t match, throws
NativeLoadException, a catchable exception naming the problem (couldn't find the kvstore native library ..., Store.put is missing from the library kvstore, Store.put changed since these bindings were generated). The failure is remembered: every later call throws the same
exception, before any call can misread memory. To check at startup instead
of on the first call, call the library class:
try
{
KvstoreLibrary.Check();
}
catch (NativeLoadException e)
{
Console.Error.WriteLine($"can't use kvstore: {e.Message}");
}
Type mapping
Every value crosses as one C value in every position: a parameter, a return, an async result, an iterator item, and a callback method’s argument and return.
| IDL type | C# type | Crosses the ABI as |
|---|---|---|
i8 … u64, f32, f64 | sbyte … ulong, float, double | by value |
bool | bool | one byte, 0 or 1 (never the four-byte Win32 BOOL) |
string | string | an FfiRun ({prefix}_run) of UTF-8, encoded into a pooled buffer; interior NULs survive |
bytes | ReadOnlySpan<byte> as a parameter, byte[] otherwise | an FfiRun, a parameter pinned in place |
| C-style enum | enum with the IDL discriminants | int32_t |
| record | positional sealed record | an FfiRun holding a value buffer |
| rich enum | abstract record with one nested sealed record per variant | an FfiRun holding a value buffer |
T? of a scalar, bool, or C-style enum | T? (int?, Color?) | an FfiOpt* struct ({prefix}_opt_{prim}): a presence byte and the value |
other T? | T? | a value buffer (Iface? is a nullable pointer, Cb? a null vtable) |
[P] of i8 … u64 (not u8), f32, f64 | ReadOnlySpan<P> as a parameter, P[] otherwise | an FfiRun of packed elements, its length in bytes; a parameter is pinned in place, a result is copied once |
other [T] | IReadOnlyList<T> | a value buffer |
{K: V} | IReadOnlyDictionary<K, V> | a value buffer |
| interface | sealed class : IDisposable | object pointer |
| callback interface | interface I{Name} | an FfiCallback ({prefix}_{Cb}): the ctx and a static vtable, by value |
iter<T> | IEnumerable<T> | iterator handle |
The runtime declares these structs once, all blittable and passed by value
([StructLayout(LayoutKind.Sequential)]): FfiRun (byte* Ptr; nuint Len), one FfiOpt* per scalar (byte Has then the value, a byte again
for FfiOptBool), and FfiCallback (IntPtr Ctx; IntPtr Vtable). No
native signature mentions C#’s bool, so nothing depends on how the runtime
would marshal one.
A typed-array or bytes parameter is a span, so an array, a slice of one
(values.AsSpan(1, 3)), or stack memory passes without a copy; it must be
aligned for its element type (managed arrays always are), or the producer
rejects it as a marshalling failure (-3). Inside a value buffer (a record
field, a list element) the same types are ordinary lists:
IReadOnlyList<double>.
Returned strings, bytes, typed arrays, and buffers are copied and released
with {prefix}_run_free. Records and rich enums encode themselves
(WriteTo and ReadFrom); optionals, lists, and maps go through the
runtime’s generic codec (WriteList, ReadMap, …), handed a static lambda
per element, so no code is generated per collection shape.
Records
A record is a positional record, so it has value equality, with
expressions, deconstruction, and a readable ToString:
public sealed record Entry(string Key, byte[] Value, EntryKind Kind, uint Version, long? ExpiresAt,
IReadOnlyList<string> Tags, IReadOnlyDictionary<string, string> Metadata)
A record with a byte array, list, or map field overrides Equals and
GetHashCode to compare those fields by content, so two decodes of the same
entry are equal, and entry with { Tags = new[] { "x" } } isn’t. Any
IReadOnlyList<T> or IReadOnlyDictionary<K, V> works as a field value
(an array, a List<T>, an immutable collection). A field spelled like the
record itself or like a member every record has (ToString, Equals) gains
a trailing _.
A rich enum is a closed hierarchy you can switch on:
switch (change)
{
case Change.Put put: Console.WriteLine(put.Entry.Key); break;
case Change.Removed { Expired: true } removed: Console.WriteLine($"{removed.Key} expired"); break;
}
Objects and lifetime
An interface wrapper holds one strong reference in a nested SafeHandle
subclass whose ReleaseHandle calls _destroy. Every import takes that
handle, not a raw pointer, so the interop stub adds a reference for the
duration of the call: a wrapper that’s disposed on another thread or
collected mid-call can’t free the object under it. Dispose releases the
reference (an in-flight call finishes first); the SafeHandle’s finalizer
covers wrappers that are never disposed. Calling a disposed wrapper, or
passing one as an argument, throws ObjectDisposedException.
Returned objects, object fields of decoded records, and objects handed to
a callback each arrive as a new wrapper that owns its reference. Two
wrappers are equal (Equals, GetHashCode) when they reference the same
native object. Writing an object into a value buffer clones its reference
first, so the producer can keep it.
An interface member spelled like a member the wrapper declares or inherits
(Dispose, Handle, Equals, ToString, …) or like the interface
itself gains a trailing _: an IDL method dispose is Dispose_()
(reserved member names).
Errors
What a failed call throws follows its throws clause
(the trap policy):
throws: SomeDomainthrows the domain’s exception. Each error domain becomes a class deriving fromNativeException, named with oneExceptionsuffix (KvErrorisKvException,KitchenErrorsisKitchenException), with one nested sealed class per code whose fields are typed properties; catch the nested class for one code or the domain class for any of them. Domains are open: a positive code the bindings don’t know (one the library added later) throws the domain class itself, with thatCodeand the producer’s message. Codes are only unique within a domain, so a call’s own domain decides the type.throws: anythrowsNativeExceptionitself withCode-1 (GenericErrorCode) and the producer’s message.- A runtime code of a throwing call (-2 panic, -3 marshalling failure,
-4 a failed callback) throws
NativeExceptionwith thatCode; its constants name them (PanicErrorCode,MarshalErrorCode,ForeignErrorCode). - A call that can’t fail (no
throws) failing anyway is a producer bug: it throwsNativeBugException, anInvalidOperationExceptionwhoseCodeis the runtime code and whose message names the code and the producer’s message. - Cancellation (-5) always throws
OperationCanceledException.
For the kvstore sample’s KvError domain:
public class KvException : NativeException
{
/// <summary>key not found</summary>
public sealed class KeyNotFound : KvException
{
/// <summary>The domain code, <c>1001</c>.</summary>
public const int ErrorCode = 1001;
public string Key { get; }
public KeyNotFound(string key, string? message = null) : base(ErrorCode, message ?? $"key not found: {key}")
{
Key = key;
}
}
// ... Expired, StoreFull, InvalidPath, Rejected, CallbackFailed
}
try
{
store.Get("nope");
}
catch (KvException.KeyNotFound e)
{
Console.WriteLine($"{e.Code} {e.Key}: {e.Message}"); // 1001 nope: key not found: nope
}
The message is the producer’s (a Rust producer’s Display output, empty
messages arriving as the IDL default); a code class constructed in C#
defaults to the IDL message, with the code’s fields filled in where the
message names them (key not found: {key}). A code field named message
(or code) is Message_ (or Code_), since Exception already has the
property. If the API declares a type named like a runtime class
(NativeException, NativeBugException, NativeLoadException), the
runtime class takes the namespace’s last segment as a prefix
(KvstoreNativeException), and a type named like the library class moves
it to {Namespace}NativeLibrary.
Async and cancellation
An async function returns Task or Task<T>, and every one takes an
optional CancellationToken. The launcher receives an
[UnmanagedCallersOnly] completion and a GCHandle to the pending call;
the completion runs on a producer thread, receives the result as its one C
value, decodes it, releases everything the call owned, and completes the
task (continuations run asynchronously).
public Task<uint?> VersionOf(string key, CancellationToken cancellationToken = default)
- For a
cancellablefunction the token cancels the native call through the native cancel token; when the producer completes with -5 the task becomes canceled, soawaitthrowsTaskCanceledException(anOperationCanceledException). - For any other function, cancelling stops waiting: the task becomes canceled at once, and the native call, which can’t be stopped, finishes in the background. Its result is released then (a returned object wrapper is disposed right away).
- An already-cancelled token returns a canceled task without launching.
The consumer’s native cancel token is destroyed after completion, and a registration racing the completion never touches a destroyed token.
Callbacks
A callback interface becomes a C# interface the consumer implements, with the same types as the rest of the API:
public interface IPolicy
{
/// <exception cref="KvException">Reported to the library with its code and fields.</exception>
long? TtlFor(string key, long? requested);
/// <exception cref="KvException">Reported to the library with its code and fields.</exception>
Entry Admit(Entry entry);
Store Route(string key, Store home);
}
public interface IScorer
{
double[] Scores(ReadOnlySpan<ulong> sizes);
}
Passing an implementation pins it in a GCHandle (the ctx) and hands the
producer an FfiCallback of that ctx and one process-wide vtable of
[UnmanagedCallersOnly] trampolines, by value. The vtable is allocated once
in native memory and never freed, so it outlives every use; it starts with
the {size, flags, free} header (size is the vtable’s real size as C#
lays it out, flags is 0: methods may run on any thread), then one function
pointer per method in declaration order. The free entry releases the
handle when the producer drops its last reference, possibly on another
thread; the producer takes over the registration as soon as the call
reaches it, even when the call then fails. An optional callback parameter
(ILoader? loader) passes a null vtable for null.
Trampolines run on whatever thread the producer calls from. Each argument
is one C value: string and buffer arguments are decoded, typed-array and
bytes arguments are ReadOnlySpan<T>s over the producer’s memory, valid
only during the call (copy with ToArray() to keep them), and object
arguments are adopted, each a new wrapper the implementation owns. The
return is one C value too:
- a scalar,
bool(one byte), or C-style enum is returned as is, and an optional one as itsFfiOpt*struct; - an object is a fresh reference the producer adopts (
CloneHandle()); anullfor a required object reaches the producer as null, which it rejects as a marshalling failure; - a string, bytes, typed array, record, rich enum, optional, list, or map is
written into a run allocated with
{prefix}_allocand returned as anFfiRun, which the producer adopts and frees.
An exception thrown by an implementation never unwinds into native code.
A method declared throws: SomeDomain that throws that domain’s exception
reports the code, the message, and the code’s fields (encoded as the error
payload with {prefix}_error_set_payload), so the producer sees exactly
that domain error:
public Entry Admit(Entry entry)
{
if (entry.Key.StartsWith("secret"))
{
throw new KvException.Rejected(entry.Key, "no secrets");
}
return entry with { Kind = EntryKind.Encrypted };
}
Any other exception is reported with code -1 and its message (-4 from a
method that can’t fail). What the failure means for the call in progress is
the producer’s decision; the kvstore sample turns it into
KvException.CallbackFailed carrying the message.
Iterators
An iter<T> function returns an IEnumerable<T> that streams lazily, one
native call per item, each item arriving as its one C value. It’s
re-enumerable: each enumeration (each GetEnumerator, so each foreach or
LINQ pass) launches a new native iterator, so a failure to start throws
from GetEnumerator, at the start of the loop, rather than from the call.
The enumerator owns its native iterator as a SafeHandle, destroyed when
enumeration ends, when the enumerator is disposed (foreach does this on
early exit), or by its finalizer. Span parameters of an iterator function
are copied once, since the sequence outlives the call.
Known limitations
- Only one
DllImportResolvercan exist per assembly. If you compile the generated sources into an assembly that already has one, the{PREFIX}_LIBRARYoverride and the implicit load-time check are skipped; call{Namespace}Library.Check()yourself. - Object references cloned into a value buffer leak if encoding a later field throws before the call (for example a disposed wrapper in the same list).
- C# can name an undeclared enum value (
(Color)3); the producer rejects it as a marshalling failure (-3), also inside an optional (Color?). - A record’s hash code of a list or map field uses its count, so records that differ only in collection contents share a hash (equality still tells them apart).
Dart
The Dart target generates a standalone Dart package that calls the
producer’s C ABI (revision 6) through dart:ffi. It
works in Dart command-line apps and in Flutter apps on the desktop, Android,
and iOS. Records become value classes, rich enums sealed class hierarchies,
interfaces disposable wrapper classes, async functions Futures, iterators
lazy Iterables, and callback interfaces abstract classes you implement.
Dart is a Tier 2 target: it may lag behind new ABI work, but it’s held to the same conformance suite as every other target.
What gets generated
dart/
pubspec.yaml package `{package}`, depends on `ffi`
README.md
lib/{package}.dart the library: its imports and parts
lib/src/runtime/*.dart the runtime (loader, errors, codecs, ...) and contract rows
lib/src/api.dart every declaration of the library
The whole binding is one Dart library split into parts, so you import a
single file. A library is one namespace, and so is its Dart package: every
type and function is a top-level name. The package name defaults to the
library’s C prefix (kvstore for the kvstore sample), so consumers write
import 'package:kvstore/kvstore.dart';. Runtime sections the API doesn’t
use (async, callbacks, typed arrays, optional scalars, …) aren’t emitted.
Configuration
[generators.dart]
name = "kvstore" # package name and library file (default: the C prefix)
sdk = ">=3.10.0 <4.0.0" # the pubspec's SDK constraint (this is the default)
The package needs Dart 3.10 or newer, the first release with
NativeCallable.isolateGroupBound, which delivers void callback methods from
any thread (see Threading), and the ffi package (2.1 or
newer), which supplies Arena and calloc.
Install, build, and load
Add the generated package as a dependency, for example with a path:
dependency, and run dart pub get:
dependencies:
kvstore:
path: bindings/dart
The bindings open the native library on first use: libkvstore.dylib on
macOS, libkvstore.so on Linux and Android, and kvstore.dll on Windows,
found through the platform’s normal search. Set KVSTORE_LIBRARY (the
identity’s {PREFIX}_LIBRARY variable) to a full path to load a specific
build. On iOS, and on macOS when the file isn’t found, the bindings look the
symbols up in the running executable, which is how a statically linked or
embedded library is found.
weaveffi package writes the pub package dart/{package}/ with each desktop
platform’s library under native/<platform>/. The packaged loader picks the
running platform’s library (by Abi.current()) and looks for it in the
package itself, resolved with Isolate.resolvePackageUriSync, then under the
working directory (for a compiled app that copied native/ next to itself),
and only then on the system search path. {PREFIX}_LIBRARY still wins over
all of them. See Packaging.
Load-time checks
Before any other call, the bindings check the library and throw a
NativeLibraryException if it can’t be opened or doesn’t match:
kvstore_abi_version()must report revision 6.- The bindings embed one contract row per declaration they were generated with (each function, interface, interface member, record, enum, callback interface, callback method, error domain, and error code): the declaration’s contract function, the hash of its canonical signature, and its path, with the signature as a comment. Each row’s function must exist and return the row’s hash. A missing one fails with “kvstore: Store.put is missing from the library”; a different hash with “kvstore: Store.put changed since these bindings were generated”. Declarations the library has and the bindings don’t are fine, so adding a function, an error code, or a callback method never breaks a deployed binding.
NativeLibraryException is an Exception, thrown from whichever call into
the library comes first, so an app can catch it and report a broken install.
The load isn’t cached when it fails: the next call tries again.
Type mapping
Every value crosses the C ABI as one C value, in every position (a parameter, a return, an async result, an iterator element, and a callback method’s arguments and return):
| IDL type | Dart type | Crosses the C ABI as |
|---|---|---|
i8 to i64, u8 to u64 | int | by value (u64 as its two’s-complement bit pattern) |
f32, f64 | double | by value |
bool | bool | C bool |
| Plain enum | an enhanced enum with value and fromValue | int32_t |
T? of a scalar or plain enum | T? | a {p}_opt_{prim} struct ({has, value}) by value |
string | String | a {p}_run of UTF-8, so interior NULs survive |
bytes | Uint8List; a parameter takes any List<int> | a {p}_run of the bytes |
[T] of a number (i8 to i64, u16 to u64, f32, f64) | List<int> or List<double> | a {p}_run of the packed elements |
| Record | a final class with final fields, named constructor arguments, and value equality | a {p}_run holding a value buffer |
| Rich enum | a sealed class with one final subclass per variant | a {p}_run holding a value buffer |
Any other T?, [T], {K:V} | T?, List<T>, Map<K, V> | a {p}_run holding a value buffer |
| Interface | a final class wrapper | object pointer (Interface? is a nullable pointer) |
iter<T> | Iterable<T> | native iterator |
| Callback interface | an abstract class you implement | a {p}_{Cb} struct ({ctx, vtable}) by value; Cb? passes a null vtable for none |
The runtime mirrors each C struct with a private dart:ffi Struct
(_Run, _OptI32, _CallbackArg), passed and returned by value, so the
generated lookupFunction signatures match the header slot for slot.
A run argument (a string, bytes, a numeric list, or a value buffer) is
copied into native memory for the call (a typed list such as Int32List is
copied as is; any other list is converted first). A returned run is copied
into Dart memory and released with {p}_run_free. A returned numeric list is
a fixed-length typed list behind the List<int> or List<double> type
(Int32List, Float64List, and so on). A bytes value the bindings return,
decode, or pass to a callback is always a Uint8List; a bytes parameter
(or a callback’s bytes return) takes any List<int>, so a list literal
works too. Inside records and other value buffers, optionals and lists keep
the value-buffer encoding.
Records and rich-enum variants implement ==, hashCode, and toString:
lists, maps, and byte arrays compare element by element, and interface
wrappers by identity. Wrapper functions and members use lowerCamelCase;
types use UpperCamelCase. A name that collides with a Dart keyword or a type
the bindings use gains a trailing _ (class_, String_, Int32List_), as
does an interface member named like a member every wrapper declares or
inherits (dispose, hashCode, toString, runtimeType, noSuchMethod):
a method dispose is dispose_(). A record field named like one of those
Object members, and an error-code field named code or message, gains
the _ too (kvstore’s CallbackFailed { message } has a message_
field). See Naming.
Each distinct optional, list, or map type that crosses inside a value buffer
gets one private codec pair named by its canonical shape (_pack_list_Entry,
_unpack_map_string_string), built on the runtime’s generic
writeList/readList helpers, so no call site inlines a loop.
Objects and lifetime
Each wrapper holds one strong reference. Call dispose() when you’re done;
an undisposed wrapper is released by a NativeFinalizer when it’s
collected. Disposing twice is harmless, and using a disposed wrapper throws a
StateError.
final store = Store.open('/tmp/data'); // factory constructor
store.put('key', [1, 2, 3], EntryKind.persistent, null);
final copy = store.share(); // a second reference
store.dispose();
copy.count(); // still valid
copy.dispose();
Every call borrows the wrapper’s pointer for its duration. If a callback
disposes a wrapper that a call in progress is using, the release waits until
that call returns, so the native object never disappears mid-call. Wrappers
are Finalizable, so Dart keeps them alive until the end of any call that
uses them. An object written into a value buffer (a record field, a list
element) is encoded as a fresh reference, so the wrapper stays usable.
Errors
Each error domain becomes an exception class extending NativeException,
named by the shared rule (KvError is KvException, KitchenErrors is
KitchenException), with one final subclass per code (KeyNotFound is
KeyNotFoundException). Payload fields are typed properties, and the
code’s documented message is the default for the optional trailing
message argument:
try {
store.get('missing');
} on KeyNotFoundException catch (e) {
print('${e.code}: ${e.message} (${e.key})'); // 1001: key not found: missing (missing)
} on KvException catch (e) {
// any other KvError code, including ones these bindings don't know
}
A library may declare several domains, and a function names the one it
throws; codes are only unique within a domain, so the bindings decode a
failure by the function’s domain (calculator’s CalcError.DivisionByZero
and ParseError.NotANumber are both code 1).
Domains are open. A positive code the bindings don’t declare (from a newer
library that added a code) arrives as the domain class itself
(KvException) with its code and message, never as a crash, so catch the
domain class to stay forward compatible. A negative runtime code becomes a
plain NativeException with that code. The runtime codes are constants on
NativeException: genericCode (-1), panicCode (-2), marshalCode
(-3), foreignCode (-4, a callback implementation failed), and
cancelledCode (-5, raised as CancelledException).
A function declared throws: any fails with a plain NativeException
carrying genericCode and the producer’s message (kvstore’s importLines
fails with “line 2: expected key=value”).
A failure of a function that isn’t declared to throw is a bug in the
producer, so it follows the trap policy:
the binding throws a NativeError, an Error (not an Exception) carrying
the runtime code and the producer’s message. A marshalling failure of
such a function (codec’s echoChar('ab')) is a NativeError with
marshalCode. Cancellation always surfaces as CancelledException.
Async and cancellation
An async function returns a Future. The producer completes it exactly
once, from any thread, through a NativeCallable.listener that stays open
until then; the result (which the bindings own) is decoded on the event
loop.
A cancellable function takes an optional named CancelToken:
final token = CancelToken();
final pending = store.compact(60000, cancelToken: token);
token.cancel();
try {
await pending;
} on CancelledException {
// completed with code -5 without waiting for the work
}
One token can serve any number of calls, a token that’s already cancelled
cancels a call at launch, and cancelling after completion does nothing. The
bindings create a native token for each call, cancel it when the
CancelToken is cancelled, and destroy their reference when the call
completes.
Callbacks
Implement the generated abstract class and pass an instance. The bindings
keep it in a table until the producer releases it through the vtable’s
free, so you don’t need to hold another reference. An optional callback
parameter (Policy?) takes null for none, which passes a null vtable.
class AdmitAll implements Policy {
@override
int? ttlFor(String key, int? requested) => requested;
@override
Entry admit(Entry entry) {
if (entry.key.startsWith('secret')) {
throw RejectedException(entry.key, 'no secrets');
}
return entry;
}
@override
Store route(String key, Store home) => home;
}
store.setPolicy(AdmitAll());
A method that returns a value returns it as one C value: a scalar by value,
an optional scalar as its {p}_opt_{prim} struct, an object as a fresh
strong reference the producer adopts, and a string, bytes, numeric list, or
record as a run the bindings allocate with {p}_alloc and the producer
frees. Arguments are copied before the method runs (a numeric list into a
typed list), and object arguments are owned by the implementation; call
dispose() on them when you’re done (or let the finalizer release them). A
method may call back into the library: every call has its own error and out
slots, so a call made from inside a callback never disturbs the call that’s
waiting on it.
Exceptions never unwind into the producer. In a method declared to throw a
domain, throwing that domain’s exception (here a KvException subclass)
reports its code and its fields, encoded as a value buffer, so the producer
sees exactly that error: put above fails with the same
RejectedException (with the message the producer renders from its
fields). Any other exception, and any exception from a throws: any
method, reports genericCode (-1) with the exception’s text (a
NativeException’s message); from a method that isn’t declared to throw,
it reports foreignCode (-4).
Threading
How a method runs depends on its return type:
- A method that returns a value is a
NativeCallable.isolateLocaltrampoline. It runs synchronously, so it can only run on the isolate’s thread while a call from Dart is in progress, as a policy or a filter consulted during the call is. - A void method is a
NativeCallable.isolateGroupBoundforwarder. The producer may call it from any thread; the forwarder copies its arguments and returns at once, and the method runs later on the event loop, in the zone that passed the instance. An exception there is an uncaught error of that zone, and a void method can’t fail the producer’s call even when it’s declared to throw. The vtable’sfreeis forwarded the same way, after every call made before it.
Every vtable the bindings pass is flagged thread-affine
({PREFIX}_VTABLE_THREAD_AFFINE; see
Callback interfaces). The producer
records the thread that passed it and refuses to call a value-returning
method from any other thread: the method doesn’t run, and the producer sees
it fail with foreignCode (-4) and the message “callback called off its
thread”. Without the flag, the Dart VM would abort the process, since only
an isolateLocal callable can run the isolate’s code synchronously, and the
VM aborts before any Dart code runs when one is called from a thread that
isn’t running the isolate. In the kvstore sample, compact tells listeners
from a worker thread: a Dart Listener’s accepts is refused there, so the
listener is detached, and compaction carries on.
The vtables are static and sized as the bindings were generated, so a library that later appends a callback method keeps working with them: the producer fails a call to the method the bindings lack with -4.
Iterators
An iter<T> return is a lazy Iterable<T>: each step pulls one element from
the native iterator, and iterating again starts a new one. The native
iterator is destroyed when iteration finishes or fails, or by a finalizer
when an iteration is abandoned (first, take, a break) and collected.
for (final key in store.keys('user.')) {
print(key);
}
Performance notes
Every call takes a frame from a per-isolate pool: the native error slot, an
out slot for an iterator’s element, and an Arena for staged arguments. A
call made from a callback takes a frame of its own, and a frame goes back to
the pool when its call returns, so steady-state calls allocate no native
memory for their slots. Optional scalars cross as small structs and numeric
lists as packed runs, skipping the value buffer entirely. When the API
declares no callback interfaces, synchronous calls are bound as leaf calls
(isLeaf: true), which skips the VM’s safepoint transition; a leaf call
blocks this isolate group’s garbage collector until it returns, so it suits
fast functions.
Known limitations
- A value-returning callback method can only run on the isolate’s thread, during a call from Dart. A producer that calls one from its own threads (a worker thread, an async executor) gets a -4 failure instead of a result; void methods are safe from any thread (see Threading).
- The producer pins a vtable to the OS thread that passed it. The main
isolate of a Dart program, and Flutter’s root isolate, stay on one
thread, but the VM may move another isolate (one started with
Isolate.spawnorIsolate.run) to a different thread between event-loop turns. In such an isolate, pass an implementation and use it within one synchronous stretch of code, or expect its value-returning methods to fail with -4 after anawait. - Void callback methods are always delivered asynchronously, even when the producer calls them on the isolate’s thread, so their exceptions can’t fail the producer’s call.
NativeCallable.isolateGroupBound, which callback interfaces rely on, is marked experimental in the Dart SDK (“may change in the future”), so a future SDK release could change how it’s enabled.- Library loading uses
DynamicLibrary; Flutter’s native-assets build hooks aren’t generated.
Go
The Go target emits a self-contained cgo module that binds the library’s
C ABI. Records and rich enums are plain Go values,
interfaces are reference-counted wrappers with Close, calls that declare
errors return error values you match with errors.As, async functions
block on a context.Context, and iter<T> returns standard-library
iter.Seq sequences. The module requires Go 1.24 or later.
Go is a Tier 2 target: it may lag behind a new ABI revision for a while, but it runs the same conformance suite as every other target before a release.
What’s generated
For a library whose identity is kvstore:
go/
go.mod module path (the package name, or `name`), go 1.24
README.md
kvstore.h a copy of the C header
bindings.go the API: types, wrappers, trampolines, load-time checks
runtime.go Check, errors, runs, optional scalars, objects, callbacks,
iterators, async
codec.go the value-buffer writer and reader
Every Go file carries the standard // Code generated ... DO NOT EDIT.
line before its package clause, so linters skip it and editors warn before
you change it.
Every name comes from the package identity:
| Name | Default | Override |
|---|---|---|
| Module path | the package name | [generators.go] name |
| Package name | the C prefix without underscores (kitchen_sink is kitchensink) | [generators.go] package |
| Linked library | -l{library} | none |
| Header | {library}.h | none |
[generators.go]
name = "github.com/example/kvstore"
package = "kvstore"
A package name that’s a Go keyword gains a trailing underscore.
A library is one namespace, so it renders into one Go package, and Go
spells every exported name in PascalCase with Go’s initialisms (user_id
is UserID, ttl_seconds is TTLSeconds):
| Declaration | Go name |
|---|---|
function summarize | Summarize |
interface Store | *Store |
constructor Store.open | OpenStore (and new is NewStore) |
method Store.get_or_load | (*Store).GetOrLoad |
static Store.default_capacity | StoreDefaultCapacity |
C-style enum EntryKind, variant Volatile | EntryKind, EntryKindVolatile |
rich enum Change, variant Put | Change, ChangePut |
error domain KvError, code KeyNotFound | KvError, *KeyNotFoundError |
error domain KitchenErrors | KitchenError (one Error suffix, never doubled) |
A free function whose name would clash with a type, an enum constant, a
constructor, a static, an error type, or the runtime’s Check, Error,
or DebugLive gains a trailing underscore: the kvstore sample’s async
open_store sits beside the OpenStore constructor, so it’s OpenStore_,
and the codec sample’s vector function sits beside its Vector type, so
it’s Vector_. Methods never clash this way, since each lives on its own
type.
Doc comments are the IDL’s docs. A package-level declaration’s comment
starts with its name, as Go convention asks, so a doc that doesn’t is
prefixed with Name: . Backticked API names become Go doc links
(`new_op` is [NewOp], a method [Store.Get]) or their Go spelling
(a field ExpiresAt, a parameter ttlSeconds), and a deprecation becomes
the final Deprecated: paragraph that Go tools recognize.
Build and load
The bindings include the bundled header and link with
#cgo LDFLAGS: -l{library}, so a consumer supplies only the library’s
directory:
export CGO_LDFLAGS="-L/path/to/lib"
export LD_LIBRARY_PATH="/path/to/lib" # DYLD_LIBRARY_PATH on macOS
go build ./...
cgo links the library into the program when it’s built, and the
platform’s dynamic loader finds it when the program starts. The bindings
never open the library themselves, so the {PREFIX}_LIBRARY override the
other targets read at load time doesn’t exist for Go; to choose the library
at run time, set the loader’s search path (LD_LIBRARY_PATH,
DYLD_LIBRARY_PATH, or PATH on Windows). To record the directory in the
binary instead, add an rpath when building:
export CGO_LDFLAGS="-L/path/to/lib -Wl,-rpath,/path/to/lib"
weaveffi package writes the module to go/{package}/ with each desktop
platform’s library under lib/<platform>/ and replaces the single link
line with one per GOOS and GOARCH, so cgo picks the right library with no
CGO_LDFLAGS:
/*
#cgo darwin,arm64 LDFLAGS: -L${SRCDIR}/lib/darwin-arm64 -Wl,-rpath,${SRCDIR}/lib/darwin-arm64
#cgo linux,amd64 LDFLAGS: -L${SRCDIR}/lib/linux-x64 -Wl,-rpath,${SRCDIR}/lib/linux-x64
#cgo windows,amd64 LDFLAGS: -L${SRCDIR}/lib/windows-x64
#cgo LDFLAGS: -lkvstore
*/
${SRCDIR} expands to the module’s directory (in the module cache, for a
dependency), so a program built on a machine runs there without a loader
path. A binary you ship elsewhere still needs the library beside it or on
the loader’s path: copy it and link with an rpath such as
-Wl,-rpath,$ORIGIN (@executable_path on macOS). Windows has no rpath;
put the DLL next to the executable or on PATH. Android, iOS, and
wasm32 libraries aren’t bundled. Publish the module by pushing the
directory to the module path’s repository; see
Packaging.
Load-time checks
Check() error checks the library’s ABI revision and then
the contract of every declaration the
bindings were generated with, including each error code and callback
method: it calls the declaration’s {p}_contract_{id} function and compares
the hash with the one embedded in bindings.go.
if err := kvstore.Check(); err != nil {
log.Fatal(err) // kvstore: Store.put changed since these bindings were generated
}
The checks run once, on the first call to Check or to any function of the
package, and Check returns the same result from then on. Importing the
package never panics. A function called after a failed check panics with
the error Check returns, so call Check at startup when you’d rather
handle a mismatched library as an error. The error names the first
declaration whose hash differs. Because the bindings link the library, one
that lacks a declaration fails to link (or, with a shared library swapped
in later, to start) rather than failing the check. Declarations the library
has and the bindings don’t are fine, so a library that only adds functions,
error codes, or callback methods keeps working with older bindings.
Type mapping
Every value crosses as one C value, whatever its position:
| IDL type | Go type | Crosses the ABI as |
|---|---|---|
i8 to i64, u8 to u64 | int8 to int64, uint8 to uint64 | the C integer |
f32, f64 | float32, float64 | float, double |
bool | bool | C bool |
string | string | a {p}_run of UTF-8 |
bytes | []byte | a {p}_run of the bytes |
| C-style enum | type E int32 plus E{Variant} constants | int32_t |
| rich enum | sealed interface plus one struct per variant | a value buffer in a {p}_run |
| record | plain struct with exported fields | a value buffer in a {p}_run |
scalar T? (integer, float, bool, C-style enum) | *T | a {p}_opt_{prim} struct ({p}_opt_i32 for an enum) |
other T? | *T; a slice, map, rich enum, []byte, or wrapper stays as it is and nil is none | a value buffer in a {p}_run |
numeric [T] (i8 to i64, u16 to u64, f32, f64) | []T | a {p}_run of the packed elements |
other [T], {K: V} | []T, map[K]V | a value buffer in a {p}_run |
| interface | *Iface | object pointer |
Iface? | *Iface (nil is none) | object pointer or null |
| callback interface | a Go interface you implement | a {p}_{Cb} struct of a handle and a static vtable |
Cb? | the same interface (nil is none) | the same struct with a null vtable for none |
iter<T> | iter.Seq[T] or iter.Seq2[T, error] | iterator handle |
A string, byte slice, or numeric slice parameter lends its own memory for
the call, with no copy and no encoding: the run points into the Go string
or the slice’s backing array (a sub-slice passes its own window), cgo keeps
it in place until the call returns, and the library only reads it. Strings
carry no NUL terminator, so they may contain \x00. A Go string can hold
bytes that aren’t UTF-8; the library rejects them as a marshalling failure
(-3).
A returned run is copied into Go memory and released with {p}_run_free.
An empty string, byte slice, or numeric slice result is empty and non-nil.
Inside a record, list, or map, numeric lists and optional scalars use the
value-buffer encoding like everything else; the Go types are the same
either way.
Each type that crosses inside a value buffer has one codec pair, shared by every parameter, result, field, and callback argument of that type. A composite is named after its shared stem (the same name every target uses):
func wvWrite_map_string_Store(w *wvWriter, v map[string]*Store) {
wvWriteMap(w, v, (*wvWriter).writeString, wvWriteStore)
}
Objects and lifetime
Each wrapper embeds the runtime’s object core, which owns one strong
reference. Close() error releases it (so a wrapper satisfies
io.Closer), and a runtime.AddCleanup cleanup releases it some time after
an unclosed wrapper becomes unreachable. Every call borrows the native
pointer for its duration:
func (s *Store) Get(key string) (Entry, error) {
cSelf := s.native()
defer s.release()
var cErr C.kvstore_error
cRet := C.kvstore_Store_get(cSelf, wvStrRun(key), &cErr)
if cErr.code != 0 {
return Entry{}, wvKvError(wvTakeError(&cErr))
}
return wvDecode(cRet, wvReadEntry), nil
}
Close is idempotent and goroutine-safe. When it races a call in flight
(even one that closes the wrapper from inside a callback), the reference is
released as soon as that call returns, never mid-call. Using a wrapper after
Close, or passing a nil *Iface where an object is required, panics. An
object inside a record, list, or map crosses as a token that carries a
fresh reference, so the wrapper you passed stays valid. Two wrappers may
refer to the same object (a method that returns its receiver hands back a
new wrapper); each is closed on its own.
Because every wrapper has Close, an IDL method named close is
Close_ (reserved member names).
Errors
A function’s throws decides its Go signature:
| IDL | Go signature | A failure is |
|---|---|---|
throws: KvError | (T, error) | a code of the domain, or an *Error for a runtime code |
throws: any | (T, error) | an *Error with code -1 and the library’s message |
no throws | T | a bug: the wrapper panics with an *Error |
A domain code comes back as its code’s type, a pointer to a struct holding
the code’s payload fields and a Message, and every code type of a domain
implements the domain’s sealed interface:
_, err := store.Get("missing")
var missing *kvstore.KeyNotFoundError
if errors.As(err, &missing) {
fmt.Println(missing.Key, missing.Code()) // missing 1001
}
var kvErr kvstore.KvError
if errors.As(err, &kvErr) {
// any code of the domain
}
Domains are open: a positive code the bindings don’t declare (from a newer
library) comes back as the domain’s *Unknown{Domain} type
(*UnknownKvError), which keeps the code and message and still matches the
domain’s interface. Codes are unique only within a domain, so the
calculator’s CalcError.DivisionByZero and ParseError.NotANumber can both
be 1; each function maps codes through its own domain.
Error() returns the library’s message, or the code’s default message when
Message is empty. A runtime code (-1 generic, -2 a panic in the
library, -3 a marshalling failure, -4 a callback failure) comes back as
the package’s *Error, which keeps the code and message and never matches a
domain interface. A function that declares no errors panics with that
*Error instead (see
the trap policy). The
panic is an ordinary recoverable one, and its text names the code and the
library’s message, as in kvstore: <message> (code -3).
Async and cancellation
Async functions take a context.Context first and always return an error;
they never panic on a failure. A function with no throws reports its
failure as an *Error like a throws: any one. They block the calling
goroutine on a channel that a completion trampoline fills from the
library’s thread; call them from a goroutine of your own for concurrency. A
cancellable function creates a native cancel token, cancels it when the
context is done, and returns ctx.Err() (context.Canceled or
context.DeadlineExceeded) for the cancelled completion (code -5), or
context.Canceled if the library cancelled the call on its own:
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
removed, err := store.Compact(ctx, 60000)
if errors.Is(err, context.DeadlineExceeded) {
// The native call was cancelled.
}
Any other async function returns ctx.Err() as soon as the context is done
and discards the native result when it arrives. A context that’s already
done never launches the call. The result is one C value like a sync
return, so an optional scalar result is a *T and a numeric list result a
[]T.
Callbacks
A callback interface is a Go interface. Passing an implementation stores it
in a handle table and hands the library the interface’s argument struct:
the handle as the context, and the address of one static vtable per
interface, with the header’s size and flags (0: Go may run a method on
any thread), the free entry that deletes the handle once the library is
done, and one //export trampoline per method. The library may call
methods from any thread, and free may run on any thread too.
type Policy interface {
// The TTL a write of `key` gets, given the TTL the caller
// requested (absent for none): ...
//
// Return a KvError to report one of its codes, with its fields, to the native
// caller; any other error reports code -1 with its text.
TTLFor(key string, requested *int64) (*int64, error)
Admit(entry Entry) (Entry, error)
Route(key string, home *Store) (*Store, error)
}
- Arguments. Strings, bytes, typed arrays, and buffered values are lent
for the call, so they’re copied or decoded into Go values, and an
optional scalar is a
*T. An object argument (homeabove) is a new wrapper that owns its own reference: keep it, return it, orCloseit. - Returns. A method may return any type but an iterator or a callback
interface. A scalar returns by value and an optional scalar as its C
struct; a string,
[]byte, typed array, or buffered value is copied into a run allocated with the library’s allocator, which the library adopts; an object returns a fresh reference to the wrapper’s object (the wrapper stays yours). Returning nil for a required object, or a value the library can’t read (text that isn’t UTF-8, an undeclared enum value), fails the call in progress. - Errors. A method that declares
throwsreturns(T, error)orerror. Returning one of its domain’s code types (for example&kvstore.RejectedError{Key: k, Reason: "no secrets"}) reports that code and its payload fields, so the original caller can receive exactly that error. Any other error reports code-1with its text. A method that panics, throwing or not, is recovered and reported as-4with the panic’s text; nothing unwinds into the library. What the caller finally sees is the producer’s choice: a Rust producer renders a typed error’s message from its fields, and the kvstore sample turns every other callback failure intoKvError.CallbackFailed. - Nil implementations. A
Cb?parameter accepts nil, which passes no callback (a null vtable); so does a typed nil (an interface holding a nil pointer, map, slice, func, or channel), which would otherwise reach the library as an implementation whose every call panics. A required one panics on either.
Iterators
An iter<T> return becomes a lazy sequence: each range launches the
native iterator, pulls one element per step, and destroys the iterator when
the loop ends, including on an early break. A function that declares
errors returns an iter.Seq2[T, error] that yields its error as a final
(zero, err) pair:
for key, err := range store.Keys(nil) {
if err != nil {
return err
}
fmt.Println(key)
}
Each element is one C value, so elements may be optional scalars
(iter.Seq[*int64]), numeric lists (iter.Seq[[]int32]), records, or
objects, each received like a return.
Leak checks
DebugLive(kind) reports the library’s live objects (0), callbacks (1),
iterators (2), cancel tokens (3), and runs (4), and DebugLive(-1) is 1
when the library counts at all. Every count is 0 unless the library was
built with the leak-check feature. Wrappers you don’t close are released
by cleanups, so run runtime.GC() (and give the cleanups a moment) before
reading the counts.
Limitations
- The library is bound at link time, so there’s no run-time override of
which library file loads beyond the platform loader’s search path, and
Checkreports a mismatched library only after the program has linked and started. - A non-cancellable async call abandoned by its context keeps running in the library until it finishes.
- Vtables are never thread-affine, so a producer may call a Go callback from any thread; Go’s scheduler makes that safe.
Ruby
The Ruby target generates a pure-Ruby gem that binds the C ABI (revision 6)
through the ffi gem. There’s no native
extension to compile: the gem depends on ffi ~> 1.16 and loads the
producer’s shared library at require time. Ruby 3.2 or newer is required
(the gemspec says so in required_ruby_version).
Ruby is a Tier 2 target: it may lag a new ABI revision for a while, but it passes the same conformance suite as every other target before a release.
What gets generated
For a package named kvstore (prefix kvstore, library kvstore):
ruby/
kvstore.gemspec gem `kvstore`, Ruby >= 3.2, depends on ffi ~> 1.16
README.md
lib/
kvstore.rb require 'kvstore': module Kvstore, the bindings
kvstore/
runtime.rb loader, load-time checks, errors, marshalling
Names come from the package identity:
| Name | Default | Override ([generators.ruby]) |
|---|---|---|
| Gem | the package name (key-store) | name |
| Ruby module | the package name in PascalCase (KeyStore) | module_name |
require path | the C prefix (key_store) | none |
A library is one namespace, so every declaration lives directly in the one
Ruby module: Kvstore::Store, Kvstore::Entry, Kvstore.render_report.
The module’s public surface is only the idiomatic API: error classes, enum
constants, records, rich enums, interface classes, callback-interface
modules, and library functions. The C functions are attached in a private
Native module, and the marshalling the wrappers share lives in a private
Bridge module (both are private_constant, so Kvstore::Native raises
NameError). lib/{prefix}/runtime.rb is fixed code shipped with the
generator (the source lives in targets/ruby/runtime/runtime.rb); only the
module name, the C prefix, and the library names are substituted into it.
A wrapper converts each argument into its one C value and hands the C call to one runtime helper as a block, so the generated code stays short:
def get(key)
key = Bridge.string_arg(key)
Bridge.pin(self) do |self_|
Bridge.call(KvError, [:buffer, Entry]) do |out_err|
Native.kvstore_Store_get(self_, key, out_err)
end
end
end
Bridge.string_arg copies the key’s UTF-8 into a kvstore_run the library
borrows; Bridge.call allocates the error slot, raises per the function’s
error domain, and receives the result (here, decodes an Entry from the
returned run and releases it with kvstore_run_free); Bridge.pin keeps
the receiver alive for the call.
Install, build, and load
weaveffi generate samples/kvstore -o bindings --target ruby
cargo build --release -p kvstore
cd bindings/ruby
gem build kvstore.gemspec
gem install kvstore-1.0.0.gem
The loader opens the library in this order:
- the path in
{PREFIX}_LIBRARY(KVSTORE_LIBRARY=/path/to/libkvstore.dylib), - a copy bundled at
lib/native/(platform gems fromweaveffi package), libkvstore.dylib,libkvstore.so, orkvstore.dllon the system search path.
require 'kvstore'
store = Kvstore::Store.open('/tmp/data')
store.put('greeting', 'hi'.b, Kvstore::EntryKind::VOLATILE)
store.close
weaveffi package --target ruby writes one precompiled platform gem per
desktop platform built, ruby/{gem}-{version}-{platform}.gem (arm64-darwin,
x86_64-darwin, x86_64-linux, aarch64-linux, x64-mingw-ucrt), with the
library at lib/native/. The gems install with gem install and publish
with gem push; Android, iOS, and wasm32 builds are skipped. See
Packaging.
Load-time checks
require checks, before anything else is attached, that the library
implements C ABI revision 6, and then that the library exports the
contract function of every declaration
the bindings were generated with and that each returns the expected hash.
The rows are embedded in the bindings, each with its canonical signature as
a comment:
module Kvstore
Bridge.check_contract!(
[
# method get(string) -> Entry throws KvError
[:kvstore_contract_dc5ad183936cb6fc, 0x1898683461a88009, 'Store.get'],
# ...one row per declaration, error code, and callback method
],
)
Any failure raises Kvstore::LoadError, a subclass of Ruby’s LoadError,
so both rescue Kvstore::LoadError and a plain rescue LoadError around
the require catch it: a library that can’t be opened, a different ABI
revision, or a declaration that’s missing or changed (kvstore: Store.put is missing from the library, kvstore: Store.put changed since these bindings were generated). Declarations, error codes, and callback methods
the library has and the bindings don’t are fine, so a library that only adds
to its API keeps working with older bindings. A failed require isn’t
recorded as loaded, so it can be retried (after setting {PREFIX}_LIBRARY,
for example).
Type mapping
Every value crosses as one C value, in every position (a parameter, a
return, an async result, an iterator element, and a callback argument or
return). The structs are FFI::Struct classes in Native, passed by value.
| IDL type | Ruby type | C value |
|---|---|---|
i8 to i64, u8 to u64 | Integer | :int8 to :uint64 |
f32, f64 | Float | :float, :double |
bool | true or false | :bool |
| C-style enum | Integer constants in a module | :int32 |
T? of a scalar, bool, or C-style enum | T or nil | Native::OptI32 and so on: {has, value} |
string | String (UTF-8) | Native::Run: {ptr, len} |
bytes | String (binary) | Native::Run |
[T] of a numeric scalar (not u8, not bool) | Array of Integer or Float | Native::Run (a typed array) |
| record | Data class | Native::Run (a value buffer) |
| rich enum | module of Data variant classes | Native::Run (a value buffer) |
any other T?, [T], {K: V} | T or nil, Array, Hash | Native::Run (a value buffer) |
| interface | wrapper class | :pointer |
Interface? | wrapper or nil | :pointer (NULL for nil) |
| callback interface | any object with the methods | Native::Callback: {ctx, vtable} |
Cb? | such an object or nil | Native::Callback (a NULL vtable for nil) |
iter<T> | lazy Enumerator | iterator handle |
Trailing optional parameters (T?, Interface?, Cb?) default to nil,
so store.keys is store.keys(nil).
Arguments are checked before the call:
- An integer (or a C-style enum value) must be an
Integerin its type’s range:RangeErrorrather than silent wrapping,TypeErrorfor aFloat. That holds for scalars, optional scalars, typed-array elements, and integers inside value buffers. - A string must be a
String(or convert withto_str) holding valid UTF-8; a string in another encoding is converted. Anything else raisesTypeErrororArgumentError. Strings cross as a run of bytes, so interior NUL characters survive. Returned strings are copied, tagged UTF-8, and released. - A typed-array argument must be an
Array(or convert withto_ary); its range-checked elements are packed into an 8-aligned native run the library borrows for the call. A typed-array return is copied into a newArrayand released. - An optional scalar crosses as its
{has, value}struct, never through a value buffer:nilin,nilout. - An object argument must be a wrapper of the declared interface, and a
record argument an instance of the record’s class (
TypeErrorotherwise).
Every run an argument borrows lives in native memory the Native::Run
struct keeps alive for the call, and every run the library returns is
copied into Ruby and released with {prefix}_run_free before the wrapper
returns.
Records are Data classes: immutable, constructed with keywords or
positionally, with value equality and hashing, with, to_h, and pattern
matching:
entry = Kvstore::Entry.new(key: 'k', value: 'v'.b, kind: Kvstore::EntryKind::VOLATILE,
version: 1, expires_at: nil, tags: [], metadata: {})
entry.with(version: 2)
A rich enum is a module whose variants are Data classes that include it,
so change.is_a?(Kvstore::Change) holds and case change in Kvstore::Change::Put(entry:) works; change.tag (and each variant’s TAG)
is the wire tag.
Value buffers use the value-buffer format.
Nothing per composite type is generated: the runtime’s codec walks a
literal type description ([:list, [:opt, Entry]], [:map, :string, :i64]),
and each record, variant, and error payload registers its field layout
once, at the end of the bindings (Bridge.record(Entry, key: :string, ...)).
A field named like a method a record or error relies on gains a trailing
_ (hash_, to_h_; an error field message is message_), and so does
a type named like a constant the bindings use (Error_, Data_, FFI_);
keywords are fine as member names (entry.end). See
reserved member names.
Objects and lifetime
Each interface becomes a subclass of the runtime’s Bridge::Handle, holding
one strong reference in an FFI::AutoPointer:
# An embedded key-value store. Each object owns its entries, logical
# clock, listeners, and policy; the last release drops them (and frees
# the consumer's callbacks).
class Store < Bridge::Handle
closereleases the reference now and is idempotent; otherwise the GC finalizer releases it. The object itself lives until its last reference anywhere (another wrapper, a record field, the library) goes.closed?says whether the wrapper was closed.- Two open wrappers of the same native object are
==(andeql?, with equalhash), so a record holding objects compares as expected. dupandclonemake an independent wrapper with its own reference.- A constructor named
newbecomesinitialize; other constructors are class methods (Store.open). An interface without one hidesnew. - Every call pins its receiver and object arguments, so a
closefrom another thread or from a callback during the call takes effect only when the call returns. - An object inside a value buffer carries its own reference, minted just before the call; an object decoded from one is adopted into a new wrapper.
- Using a closed wrapper raises
Error(“Kvstore::Store used after close”). - A method spelled like one the wrapper relies on (
close,initialize,class,dup,hash,inspect, …), or a static or factory namedallocate,new, orname, gains a trailing_: an IDL methodcloseisclose_.
Errors
Every error a call reports derives from {Module}::Error (a
StandardError), which carries code. Each error domain becomes a class
under it, named by the shared rule (KvError stays KvError,
KitchenErrors becomes KitchenError, Failure becomes FailureError),
with one nested class per code. A code’s class carries CODE, its
documented MESSAGE, and a reader per payload field:
begin
store.get('missing')
rescue Kvstore::KvError::KeyNotFound => e
e.code # => 1001
e.key # => "missing"
e.message # => "key not found: missing"
end
A library may declare several domains, and a function names the one it
throws, so codes are only unique per domain: Calculator.divide raises
CalcError::DivisionByZero for code 1 and Calculator.parse raises
ParseError::NotANumber for its code 1. Domains are open: a positive code
these bindings don’t know (a newer library added it) raises the domain
class itself, with the code and the library’s message.
What a failure raises follows the trap policy:
| Call | Domain code | Runtime code (-1 to -4) | -5 |
|---|---|---|---|
throws: Domain | the code’s class (KvError::Expired), or the domain class for an unknown code | Error with that code and the library’s message | Cancelled |
throws: any | not possible | Error (a failure is code -1 and its message) | Cancelled |
no throws | not possible | NativeBugError | Cancelled |
NativeBugError < Error marks a bug in the library (a panic, an argument it
couldn’t accept, a callback failure it let through a call that can’t report
one), never an outcome to handle. Its message names the code and the
library’s message, as in native call failed with code -2: {the panic message}; a malformed value the library returned raises it with code -3.
The runtime codes are constants on Error (Error::GENERIC,
Error::PANIC, Error::MARSHAL, Error::CALLBACK, Error::CANCELLED).
An error code’s class can be raised from a callback implementation; its payload fields are required keywords:
raise Kvstore::KvError::Rejected.new('read-only', key: entry.key, reason: 'read-only')
Async and cancellation
An async function blocks its caller until the library’s completion fires,
then returns the result or raises. The wait is a Thread::Queue#pop, so:
- It releases the GVL; other threads keep running. Run calls in threads for concurrency.
- Under a Fiber scheduler (
Fiber.set_scheduler, such as theasyncgem’s),Queue#popin a non-blocking Fiber yields to the scheduler, so only the calling Fiber waits and the thread’s other Fibers keep running; the completion wakes it through the scheduler’sunblock. The conformance suite checks this with two overlapping calls.
A cancellable function takes a cancel: keyword:
token = Kvstore::CancelToken.new
Thread.new { sleep 0.5; token.cancel }
begin
store.compact(60_000, cancel: token)
rescue Kvstore::Cancelled
# cancelled while the pause was running
ensure
token.close
end
CancelToken#cancel may be called from any thread; the call then raises
Cancelled (code -5) unless it already completed. A token stays
cancelled, can be shared by several calls, and is released by close or
the GC. Without a token, interrupting the waiting thread (Thread#raise,
Timeout) still cancels the library’s work through a private token.
The completion receives the result as its one C value (a scalar, an optional’s struct, a run, or an object pointer), which the runtime receives exactly as it does a return. The completion functions are shared by every async call whose result has the same C type and live for the process, so nothing the library may still call is ever garbage-collected.
Callback interfaces
A callback interface becomes a Ruby module whose methods raise
NotImplementedError. Any object that responds to the methods works;
including the module documents intent and supplies the defaults.
class FileLoader
include Kvstore::Loader
def name
'files'
end
def fallback(_key)
nil
end
def load(key)
path = File.join('/data', key)
raise Kvstore::KvError::KeyNotFound.new("no file for #{key}", key: key) unless File.exist?(path)
File.binread(path)
end
end
entry = store.get_or_load('settings', FileLoader.new)
Passing an implementation stores it in a handle table and hands the library
a {ctx, vtable} struct whose ctx is its key, so Ruby object addresses
never cross the boundary; the entry is removed when the library calls the
vtable’s free, which may happen on any library thread. A required callback
parameter rejects nil with TypeError; an optional one (loader = nil)
passes a NULL vtable.
Each interface has one vtable for the life of the process, registered at the end of the bindings as one row per method (its Ruby name, the error class it may raise, its return, and its parameters):
Bridge.vtable(
Listener,
[:accepts, Error, :bool, [:string]],
[:on_change, Error, nil, [[:buffer, Change]]],
)
The runtime builds the {size, flags, free} header, with size the
vtable’s own size and flags 0 (the methods may be called from any
thread), then one trampoline FFI::Function per row, which it keeps
referenced for the life of the process.
Arguments and returns follow the ABI:
- Strings, bytes, value buffers, and typed arrays arrive as copies of the
borrowed run; an optional scalar arrives as the value or
nil; an object argument arrives as a wrapper that adopted the reference the library passed, which the implementation may keep. - A returned number, boolean, C-style enum, or optional scalar crosses by
value (checked against its type’s range); a returned object (
StoreorStore?) as a fresh reference the library adopts (nilis NULL, which the library rejects where the return isn’t optional); and a returned string, bytes, typed array, or value buffer as a run allocated with{prefix}_alloc, which the library adopts. - A method that throws a domain may raise that domain’s code classes: the
library receives the code and the fields as the payload, exactly as if
the producer had raised it (the caller then sees the domain’s own message
for those fields). Any other exception, including
NotImplementedError, is reported as code-1with its message (-4for a method that declares no errors), and the method returns its type’s zero value. Nothing unwinds through C.
Threads and the GVL
Every call into the library except the trivial runtime helpers (_clone,
_destroy, an iterator’s _destroy, {prefix}_run_free, {prefix}_alloc,
{prefix}_debug_live, the error and cancel-token functions, and the
load-time checks) releases the GVL (blocking: true), so a long call
doesn’t stall other Ruby threads. That’s also what lets a callback arrive
while the call that triggered it is in flight: a callback on the calling
thread reacquires the GVL there, and one from a library thread (such as the
notifications compact sends from its worker) runs on the ffi gem’s
callback thread, which needs the GVL too.
Iterators
An iter<T> return is a lazy Enumerator, with every Enumerable method.
Each enumeration launches its own native iterator on its first pull, makes
one _next call per element, and destroys the iterator exactly once, when
iteration finishes, raises, or stops early (first(2), break), so the
same Enumerator can be enumerated again. An external enumeration (next)
releases its iterator the same way when it reaches the end or raises; one
abandoned midway can’t run its ensure, so the iterator handle is an
FFI::AutoPointer whose GC finalizer destroys it once the suspended
enumeration is collected. Either path destroys the iterator exactly once.
Each element is its one C value, received like a return.
Known limitations
- Async calls block the calling thread (or, under a Fiber scheduler, the calling Fiber); there’s no promise-based surface.
- Callback interfaces are duck-typed: a missing method is detected only when the library calls it (and reported to it as a failure).
- A callback that blocks waiting for the thread that made the triggering call deadlocks.
- A deprecated callable warns on every call in the
:deprecatedwarning category, which Ruby hides by default; enable it withWarning[:deprecated] = true(orruby -W:deprecated).
Architecture
This page is for contributors: how the workspace is organized, how a definition becomes bindings, how to add a generator, and how changes are tested. The C ABI contract is the specification everything here implements.
The pipeline
Every generating command (generate, including --check, --diff,
--dry-run, and --dev, and package) runs the same stages:
Rust producer crate IDL (.yml / .yaml / .json)
cargo rustc --crate-type cdylib weaveffi_model::parse::load_api
(with the project's features), then (the root document and every
the library's metadata frames file it imports, merged)
(weaveffi_cli::library, |
weaveffi_model::meta::assemble) |
\ /
+------------> Api (the IR) <---------+
|
v
validate weaveffi_model::validate::validate(&api, &identity, sources):
every rule, including the C symbol table under the
library's real Identity (from weaveffi.toml / cargo
metadata); reports all violations at once and builds the
Model exactly once
|
v
Model the identity, the schema version, the type index, and one
flat list per declaration kind, each binding with its C
names, its lowered AbiFn, and its Shape already resolved
|
v
render Target::render(&Model): each target returns its files in
memory (pure; no I/O), through the shared emitters in
codegen/, and never sees the Api
|
v
orchestrate Orchestrator::plan builds a Changeset against the output
directory; apply writes changed files, removes stale ones,
and keeps generation records in {out}/.weaveffi/
validate stops once the model is built; generate --check and --diff
plan without applying; package renders installable artifacts (wheels, npm
tarballs, gems, …) around the per-platform libraries build compiled.
The producer macros run inside the producer’s build, one item at a time.
Each attribute (#[weaveffi::export], #[weaveffi::record], and the rest)
expands on its own: it emits the item’s extern "C" functions, typed
through the runtime’s value traits so rustc resolves every type wherever
it’s declared; one contract function per declaration, whose hash it
computes at compile time from the canonical signature
(weaveffi_model::contract::Sig) with each type’s spelling filled in from
its trait’s NAME; and one weaveffi_model::meta::Frame describing the
declaration, in an exported {PREFIX}_META_{HASH16} static (the
weaveffi_meta custom section on wasm32). Every generated item repeats
the declaration’s #[cfg]. The CLI reads the frames back out of the built
library (see Library Mode) and validates the assembled
API with the same validator an IDL gets, so the rules that span items
(unique names, symbol collisions) are checked once, for the whole library,
and the contract a producer exports is the one its generated bindings
expect.
Crates
weaveffi-cli ─────────────────► weaveffi-model
▲
weaveffi ──► weaveffi-macros ────────┘ (proc macro, build time only)
weaveffi-fuzz ──► weaveffi, weaveffi-model (unpublished)
The runtime (weaveffi’s hidden __rt module) depends on no other
workspace crate at run time, so a producer never links the generators, and
the generators never link the runtime. The ABI revision is therefore
declared twice, in the runtime’s ABI_VERSION and in the model
(weaveffi_model::model::ABI_VERSION), and
crates/weaveffi-cli/tests/abi_version.rs keeps them equal.
| Crate | Owns |
|---|---|
weaveffi-model | Everything between a definition and code generation: the IR (ir), IDL parsing for YAML and JSON with imports: resolution (parse, behind the default idl feature), library metadata frames (meta), validation and diagnostics (validate), resolved types and their families (ty: Ty, ParamTy, RetTy, Family, RunKind), package identity (pkg), the model with its symbol table (model), the C type algebra and lowered signatures (abi: CType, AbiFn, AbiParam), error-type naming (errors), and the contract (contract). It doesn’t depend on syn; the macros use it without the idl feature. |
weaveffi-cli | The library (src/lib.rs): the target framework and the generators. Public: targets (the Target trait, its hook types, and the REGISTRY), codegen (the Orchestrator, its Changeset, OutputFile, and the CodeWriter), config (weaveffi.toml), project (locating a project, identity resolution, and loading its API), and package (the artifact types). Internal: the shared emitters (codegen::{values, codecs, contract, errors, docs, common}), cabi (the shared C declaration renderer), record (generation records), lang (keyword tables and escaping), manifest (JSON and XML escaping for package manifests), cargo (resolving a producer crate with cargo metadata, its Cargo features, and building its library), build (cross-compiling a producer per platform), platform (the platform matrix and the glibc reader for manylinux tags), library (reading a built library’s metadata), utils (generated-file banners), the target modules under targets::, and the hidden commands (one module per subcommand). The weaveffi binary (src/main.rs): argument parsing, dispatch, and error rendering. |
weaveffi-macros | The attributes and export_runtime!: function (#[weaveffi::export] on a function or an impl block), types (record, enumeration, error, interface, custom), callback (callback_interface), runtime (export_runtime!), shape (the little syntax still read from a signature: borrows, callback parameters, the cancel token, iterator returns), and common (the prefix, docs, #[cfg], frames, and contract functions every expansion shares). |
weaveffi | The producer facade: re-exports the attributes and the few runtime types a producer names (Iter, CancelToken, ForeignError, Error, set_spawner). Its hidden __rt module is the runtime: the error struct and codes, runs and Opt (8-aligned allocation), the value traits (FfiType, FfiRef, FfiReturn, ErrorType, CEnum, Codec) and the value-buffer codec, reference-counted objects, callback vtables (open, with the thread-affinity check) and foreign errors, iterators, cancel tokens, the async spawner (Tokio with the default tokio feature, else a thread per call), metadata and contract hashing, and leak counters (the leak-check feature). |
weaveffi-fuzz | cargo-fuzz targets for the YAML and JSON parsers, parse_type_ref, the validator, metadata frames, and the value-buffer decoder. |
The workspace denies unsafe_code; the runtime opts in, and the functions
the attributes emit carry a scoped allowance, so a macro-based producer
needs no unsafe of its own.
Key invariants
- Generators consume the model only, and never re-derive it. Symbol
names and signatures come from the bindings on the
Model(abi.symbol,c_tag,shape); names come from itsIdentity. - One crossing per value. In ABI revision 6 a value’s C type is a pure
function of its type (
CType::of), so a target’s call layer matches oncodegen::values::Crossing(scalar, enum, optional scalar, UTF-8, bytes, typed array, buffer, object) and marshals a parameter, a return, an async result, an iterator item, and a callback argument or return with the same per-crossing code, varying only in who owns what. - One namespace. Declaration names are unique across the library, so a
Tycarries the bare name (Store) and every name a validated model mentions resolves through theTypeIndex(Model::interface,Model::record,Model::error_domain, and so on). - One symbol table.
Model::c_symbolslists every C identifier with itsSymbolOwner, and validation rejects duplicates and reserved families (SymbolCollision). - One naming rule for error types.
weaveffi_model::errors::type_nameturns a domain or code name into a target’s type name (KitchenErrorsplusErrorisKitchenError), and every target uses it. - Fixed runtime code is real source. A target’s codec, error base
types, and loader live as source files under
targets/<t>/runtime/, included withinclude_str!and filled in with{{PLACEHOLDER}}substitution, so they read and lint as normal code. - No generated glue. Every target binds the C ABI with its language’s own foreign-function interface (Node.js through koffi, Kotlin through JNA, and so on), so no target emits C code of its own to compile.
- Determinism. No hash-map iteration reaches output; output is byte-identical across runs and platforms.
- No branding. Nothing generated is named after WeaveFFI except the
generated-file header and runtime-version comments, and the Swift
runtime’s file name (
WeaveFFIRuntime.swift).
The model
validate indexes every declaration, checks every rule, and then lowers the
document once into the Model: the identity, the schema version, the
library’s doc, the TypeIndex, and flat lists of functions, records,
enums, errors, interfaces, and callbacks.
Types are split by position, so nothing downstream handles a type where it can’t occur:
Tyis a value type, legal everywhere including inside buffers: a primitive, a record, a C-style or rich enum, an interface, or an optional, list, or map of value types.Ty::family()is itsFamily(Direct,OptDirect,Run(RunKind), orObject { nullable }, whereRunKindisUtf8,Bytes,Slice(prim), orBuffer), and its wire shape inside a value buffer is total too.ParamTyis a value or a callback interface, legal only as a parameter of a function or interface member.RetTyis a value or an iterator, legal only as the outermost return of a synchronous callable.
Every callable is an FnBinding: its parameters (ParamBinding), its
return, its ErrorStrategy (Trap, Domain(name), or Untyped), its
abi: AbiFn (the C symbol with its ordered AbiParams and return
CType), and its shape: Shape: synchronous, async (an AsyncBinding
with the completion’s type and the optional cancel-token slot), or an
iterator (an IteratorBinding with its type, _next, and _destroy).
Callback methods are CallbackMethodBindings with their vtable slot, and
error codes carry their payload’s C tag. The contract rows a binding embeds
come from codegen::contract::rows(model), computed with the same
weaveffi_model::contract signatures the macros hash.
Targets and the orchestrator
A generator implements weaveffi_cli::targets::Target, an object-safe trait
whose implementing struct owns its configuration (its [generators.<t>]
table, deserialized with serde):
pub trait Target: Send + Sync {
fn name(&self) -> &'static str;
fn render(&self, model: &Model) -> Vec<OutputFile>; // paths relative to {out}/{name}/
fn package(&self, model: &Model, ctx: &PackageContext<'_>) -> Result<Vec<Artifact>> { .. }
fn finish_package(&self, dist: &Utf8Path, artifacts: &[Artifact], ctx: &PackageContext<'_>)
-> Result<Vec<Utf8PathBuf>> { .. }
fn dev_bundle_dir(&self, model: &Model) -> Option<Utf8PathBuf> { None }
fn linkage(&self) -> Linkage { Linkage::Runtime }
fn fixed_files(&self) -> &'static [&'static str] { &[] }
}
targets::REGISTRY lists every target once: its name, description, whether
it’s generated by default, and how to build it from its config table. It
drives weaveffi.toml parsing, --target validation, help, and
completions, the snapshot and determinism tests, the benchmarks, and a test
that the CI matrices, scripts/check-fixtures.sh, and conformance/run.sh
list exactly the registry’s targets. The hooks carry everything a command
needs to know about a target (what package builds, where generate --dev
copies the library, and whether the bindings load it at run time, link it,
or need a wasm32 build), so no command matches on a target’s name.
Targets render through the shared emitters in codegen/ instead of
keeping their own copies:
values::crossing(ty)gives theCrossingevery call layer matches on; its module docs have the ownership table for each direction.codecslists every optional, list, and map that crosses inside a value buffer, deduplicated and in dependency order, with its one canonical stem (list_i32,opt_Item,map_string_list_i64).contract::rows(model)gives the contract rows (id, hash, path, and canonical signature) every binding embeds and checks at load.errorsgives every domain with its codes and their type names under the shared naming rule.docsrenders doc and deprecation text with backticked API identifiers rewritten to the target’s spelling.commonholds doc-comment emission, prose wrapping, andPascalCase;CodeWriteris the indentation-aware writer.
The Orchestrator runs the selected targets:
- Render. Every target renders in parallel (rayon), in memory.
- Plan. Each file is compared with the output directory, and each
target’s file list with its record from the previous run,
{out}/.weaveffi/{target}.json, giving aChangeset: the files that would be added, modified, or removed. - Apply. Each file is written only if its contents differ, files recorded by the previous run but no longer produced are deleted, and the record is updated.
The CLI
The library’s config module holds ProjectConfig (the [project],
[package], [build], and [generators.*] tables, with discovery and path
resolution). Its project module is the front half every command runs:
Project locates the project and its input (an IDL, a crate, or a library
alone), builds a crate’s library with cargo rustc --lib --crate-type cdylib --profile <p> and the project’s Cargo features and reads its
frames, resolves the identity, and validates the API into the Model once.
A build.rs can use Project and the Orchestrator too. The commands live
in the library’s hidden commands module, one per subcommand: init,
generate, validate, extract, build, and package (schema and
completions are handled in the binary). Every command that takes an input
shares one argument group (the input and --config), and every command
that builds the producer takes --profile and the feature flags. Commands
return an exit code; the library reports errors with miette, and the
binary renders them.
Adding a generator
- Add
crates/weaveffi-cli/src/targets/<lang>/following an existing target’s layout:mod.rs(the config struct, the generator struct that owns it, and theTargetimpl), the files that render types, calls, codecs, and packaging, aruntime/directory of fixed source, andtests.rs. - Implement
Target. Take every name from the model and the identity; marshal every value by itsCrossing; render composites, contract rows, error tables, and doc text through the shared emitters. Bind to{library}(and, if the language loads it at run time, accept a full path in{P}_LIBRARY); check{p}_abi_version()and every contract row once at load, reporting a failure as a catchable error that names the row’s path; read the error message as(ptr, len); map an unknown positive code of a domain to the domain’s base error; follow the trap policy; surface cancellation idiomatically; keep objects alive across calls; allocate callback returns with{p}_alloc; set the vtable’ssize, and its thread-affine flag only if the language needs it. Implementpackageif the ecosystem has an installable artifact, and the other hooks the target needs. - Register it with one entry in
REGISTRYincrates/weaveffi-cli/src/targets/mod.rs, run the snapshot tests, and review and accept the newkitchen_sinksnapshots (list runtimes and manifests infixed_filesso they aren’t snapshotted). - Add
scripts/fixtures/<lang>.sh, which compiles or type-checks a generated tree with the language’s toolchain, and add the target to the CI fixture matrix andscripts/check-fixtures.sh. - Add consumers under
conformance/<lang>/with arun.shthat declares one lane per sample, and add the language toconformance/run.shand the CI conformance matrix. (The registry test fails until every list matches.) - Write
docs/src/generators/<lang>.md(including its tier), add it toSUMMARY.md, and add a row to the capability matrix.
Testing
Each layer catches a different class of regression; an ABI or IR change usually has to pass all of them.
| Layer | Where | What it pins |
|---|---|---|
| Unit tests | #[cfg(test)] modules; tests.rs in each target | Parsing and imports, validation rules, Ty classification and lowering, contract signatures, naming helpers, metadata frames; per target, its naming, escaping, and configuration |
| Validation tests | crates/weaveffi-model/src/validate/tests.rs | Every ValidationError with its source span |
| Runtime tests | crates/weaveffi/tests/ | Exported runtime symbols, run alignment, value traits, thread-affine vtables, cancellation and dropped futures, foreign-error routing, leak counters, and codec laws (property tests) |
| Snapshots | crates/weaveffi-cli/tests/snapshots.rs (insta) | Every registered target renders all six fixtures; the kitchen_sink output is snapshotted file by file (except each target’s fixed_files), and any copy of the C header must equal the C target’s own |
| CLI tests | crates/weaveffi-cli/tests/cli/, abi_version.rs, c_buffer.rs | Every subcommand’s behavior and exit codes, library mode (the tests/fixtures/producer crate extracts to its expected.yml, generating from its library equals generating from that IDL, and feature flags reach the build), determinism, the registry against CI and scripts, the ABI revision lockstep, the C buffer helpers |
| Examples | examples/ | The book’s examples: each producer crate’s tests call its C functions, and examples/idl’s tests validate every IDL the book includes |
| Fixture compile checks | scripts/check-fixtures.sh <target> | Every fixture’s generated tree compiles or type-checks with the target’s toolchain |
| Conformance | conformance/run.sh | Real consumers in every language against every sample, with leak counters at zero |
| Fuzzing | crates/weaveffi-fuzz | Parsers, the validator, and frame decoding never panic; value-buffer decoders reject malformed bytes cleanly |
The fixtures are kitchen_sink (every feature, including optional scalars
and typed arrays in every position, several error domains, and throws: any), edge_cases (reserved words, deep nesting, objects and callbacks in
every legal position), imports (an API split across three files, with
references in every direction), docs_everywhere (doc-comment emission),
and shapes (rich enums and the full numeric primitive set). Only
kitchen_sink is snapshotted; the other four are covered by the fixture
compile checks, the determinism test, and targeted assertions. Snapshots
redact the CLI version, so a version bump doesn’t touch them.
Day to day:
just check # fmt, clippy (with the doc lints), rustdoc
just test # every test; fails on snapshot drift
just snapshots # accept reviewed snapshot changes
just fixtures swift # fixture compile check for one target
ONLY=python just conformance # conformance lanes for one language
just docs # build this book
See CONTRIBUTING.md for the full workflow.
Samples and Examples
The repository has two sets of producers. The examples in examples/
are the code this book shows: small crates whose tests call their C
functions, and IDL documents a test validates. The samples in
samples/ are the producers the
conformance harness runs in every language.
Examples
| Example | What it is | Tested by |
|---|---|---|
examples/getting-started | The Getting Started producer (add, div with a typed error, greet) and its C consumer, main.c | cargo test -p mathlib: the C functions through an extern "C" block, and a check that the README’s quickstart repeats the crate’s source |
examples/macro-tour | One of each producer attribute, for the producer macro guide: functions, typed and untyped errors, records and enums, custom types, an interface with an iterator, a callback interface, and async calls with cancellation | cargo test -p macro-tour (and --features admin): every C function the attributes generate, including a callback interface implemented with a hand-built vtable and a cancelled async call |
examples/idl | The IDL documents the IDL reference includes (contacts.yml, the multi-file drawing/, and the rejected documents), and the greeter project with its C producer, greeter.c | cargo test -p idl-examples: every document validates, and every rejected one fails with the code it’s named after |
Samples
Three Rust producers: a minimal one, a wire-format oracle, and a
feature-complete one. Each is a workspace crate built with the leak-check
feature on, has unit tests, and is consumed by the conformance harness in
all eleven languages, one consumer per sample per language.
weaveffi generate samples/kvstore -o bindings
Each sample’s crate name is its C prefix: kvstore exports
kvstore_Store_open, and its bindings load libkvstore (the targets that
load it at run time also accept a path in KVSTORE_LIBRARY). weaveffi generate builds the crate and reads its API from the library; the
weaveffi.toml beside each crate supplies package metadata.
calculator
The smallest useful producer, small enough to read in a minute:
add(wrapping on overflow) andgreet, a string in and a string out;divide, which throws theCalcErrordomain on a zero divisor;parse, which throws a second domain,ParseError, whoseNotANumbercode carries the input as a field and renders its message from a template (not a number: 4x); both domains use code1, so a binding must interpret a code by the callable’s domain;sqrt, athrows: anyfunction returningResult<f64, String>, which fails with code-1and the messagecannot take the square root of -4;mean([f64]in,f64?out) andrunning_total([i32]in and out), which cross as typed arrays and an optional scalar.
The C target’s c-producer-exports lane also implements the calculator’s
generated header by hand in C and checks that every runtime and contract
symbol it requires is exported.
codec
The oracle for the value-buffer format, built
on shared test vectors. The producer holds a fixed table of values covering
every wire shape: each primitive at its extremes (with NaN, the infinities,
-0.0, and subnormals for floats), empty and non-empty strings and bytes
with non-ASCII text and interior NUL bytes, optionals, lists, maps keyed by
strings, integers, and a C-style enum, nested records, C-style and rich
enums, and objects inside buffers. Each vector is a variant of the Vector
rich enum, so every language’s codec check is one loop:
vector_count()returns how many vectors there are.vector(i)returns vectorifor the consumer to decode. An index past the end fails withCodecError::OutOfRange { index, count }.check_vector(i, v)takes the decoded value back, re-encoded by the consumer, and returnstrueonly if it’s exactly vectori(floats keep their sign, and any NaN matches NaN).vector_name(i)anddescribe_vector(v)label and render a vector, so a failing consumer can say what went wrong.
A round trip can’t catch a decoder and an encoder that make the same mistake,
so each consumer also builds a few vectors from literals and checks those,
and spot-checks decoded fields. The echo_* functions return their argument
through the other families, and each consumer pushes every primitive vector
through the matching echo: scalars by value (echo_i8 … echo_bool),
strings and bytes as runs (echo_text, echo_blob), the C-style enum as an
int32_t (echo_color), optional scalars as {p}_opt_* structs
(echo_opt_i32, echo_opt_f64, echo_opt_bool, and echo_opt_color,
including -0.0, NaN, and absent), typed arrays (echo_f64s, echo_i32s,
and echo_u64s, bit-exact at the extremes), a Rust usize as u64
(echo_usize), a one-scalar string (echo_char; "ab" fails with -3),
and a custom type crossing as a lowercase hex string (echo_hex; "xyz"
fails with -3). chunks is an iterator of typed arrays, and a Token
interface with sum_holder, primary_of, and same_primary checks object
identity and reference counting through buffers.
kvstore
The feature-complete producer: an in-memory key-value store whose API uses
every feature WeaveFFI supports, arranged so a consumer can check each with
concrete assertions. Time is a logical clock per store (now, advanced by
tick), so TTLs are deterministic.
| Feature | Where |
|---|---|
| Interface with constructors, methods, and statics | Store (open, new; put, get, …; open_many, default_capacity, …) |
| Typed errors with payload fields and generated messages | KvError: KeyNotFound { key }, Expired { key, expired_at }, StoreFull { capacity }, InvalidPath, Rejected { key, reason }, CallbackFailed { message } |
An untyped (throws: any) error | import_lines (a Result<usize, String>) |
| Optional scalars and typed arrays | put’s TTL (an i64? parameter), expires_at (an i64? return), value_sizes (a [u64] return), expirations (an iterator of i64?), version_of and versions (async u32? and [u32] results), and Scorer::scores (a [u64] parameter and [f64] return) |
usize | count and listener_count (u64 in the IDL) |
| Records, optionals, lists, maps | Entry (bytes, an optional TTL, tags, metadata), StoreInfo, Stats (a map keyed by a C-style enum) |
| C-style and rich enums | EntryKind; Change (Put, Removed, Cleared) |
| Objects in every position | parameters, returns, Store? both ways (larger), lists (open_many, total_count), map values (by_label), record fields (StoreInfo), iterator elements (partition), an async result (open_store), and a callback’s parameter and return (Policy::route) |
| Callback interfaces | Listener (retained by subscribe), Policy (ttl_for, an optional scalar in and out; admit, a record return whose typed KvError reaches the put caller; route, an object parameter and return), Loader (string, bytes, and optional-object returns; passed as an optional callback), Scorer (typed arrays in and out, used by rank) |
| Callbacks from a producer thread | compact notifies listeners from the thread it runs on |
| Lazy iterators | keys (strings, throwing), entries (records), partition (objects), expirations (optional scalars) |
| Async and cancellation | open_store (an async free function returning an object), compact (cancellable; its background pause stops cooperatively, shown by Store::active_jobs), get_many (an async list), summarize_all |
| Declarations in other Rust modules | stats (Stats, summarize, summarize_all) and report (render_report, with its own ReportError domain) join the library’s one namespace |
| Deprecation | Store::size (use count) |
A callback’s failure surfaces according to its role: a Listener that fails
is unsubscribed while the store operation succeeds; a Policy, Loader, or
Scorer failure fails the call. A typed KvError a consumer raised (with
its fields) reaches the original caller typed, its message rendered from the
fields, and any other consumer failure becomes KvError::CallbackFailed
carrying the consumer’s message, through the domain’s From<ForeignError>
implementation. The store never holds a lock while a callback runs, so
callbacks may call back into it.
Comparison
WeaveFFI sits in a crowded ecosystem of FFI tooling. This page is an honest, side-by-side look at how it compares to the projects you are most likely to evaluate against it: UniFFI (Mozilla’s multi-language generator), Diplomat (the Rust-to-many-languages tool behind ICU4X), cbindgen plus hand-written glue, the single-language bridges swift-bridge, napi-rs, and wasm-bindgen, and the C/C++-first generators SWIG and autocxx. A shorter section covers interoptopus, flapigen, PyO3 with maturin, and cxx.
All comparisons reflect the public state of each project at the time of writing (WeaveFFI C ABI revision 6, schema
0.13.0). If something here is out of date, please open a PR.
The short version
WeaveFFI’s distinguishing bet is one language-neutral IDL, one C ABI, eleven
generators. The producer can be Rust (with WeaveFFI’s attributes writing
the ABI for you) or anything else that can export C symbols, and every generated
package is standalone: consumers never install WeaveFFI. The object model is
on par with the Rust-first tools: interface objects are reference counted
(Arc<T>), can be shared between wrappers and nested inside records, lists,
maps, optionals, iterators, and async results, and callback interfaces let
the producer call consumer code through a vtable whose methods can return any
value and raise typed errors. A Rust producer’s API is read from the library
it compiled (library mode, as in UniFFI), and weaveffi package turns the
builds into installable artifacts for every ecosystem. Every symbol and
package is named after the library, never after WeaveFFI, so several
WeaveFFI-built libraries coexist in one process.
The honest flip side is that WeaveFFI is pre-1.0 and its type system is deliberately smaller than UniFFI’s: no user-defined generics or trait objects, custom types only on the producer side (bindings see the type’s builtin representation), and no async callback methods. The roadmap lists what’s planned.
At a glance
| WeaveFFI | UniFFI | Diplomat | cbindgen + glue | swift-bridge | napi-rs | wasm-bindgen | SWIG | autocxx | |
|---|---|---|---|---|---|---|---|---|---|
| Producer language | Rust, C, C++, Zig (anything with a C ABI) | Rust | Rust | Rust | Rust | Rust | Rust | C / C++ | C++ (consumed from Rust) |
| Input | YAML / JSON IDL (one or several files) or annotated Rust (read from the built library) | UDL or proc-macros (library mode reads the built library) | annotated Rust bridge crate | Rust source | annotated Rust bridge module | annotated Rust | annotated Rust | C/C++ headers + .i file | C++ headers |
| Consumer languages | C, C++, Swift, Kotlin, Node.js, Wasm/JS, Python, .NET, Dart, Go, Ruby | Kotlin, Swift, Python, Ruby first-party; Go, C#, Dart, Kotlin Multiplatform, React Native (uniffi-bindgen-react-native) as external bindgens | C, C++, JS/TS (Wasm), Dart, Kotlin (JNA), Python (nanobind) | C (you write the rest) | Swift | Node.js | JS/TS (Wasm) | many (Python, Java, C#, Ruby, Lua, Perl, PHP, R, …) | Rust |
| Standalone C header | ✓ (the contract every target shares) | ✗ (private scaffolding ABI) | ✓ (C backend) | ✓ (its purpose) | ✓ (generated) | ✗ | ✗ | ✗ | n/a |
| Type system | |||||||||
| Records / enums / optionals / lists / maps | ✓ (value buffers) | ✓ | ✓ (structs, enums, Option, slices; no maps) | manual | ✓ (transparent structs and enums, Option, Vec) | ✓ (serde objects) | ✓ (serde-wasm-bindgen or classes) | ✓ | ✓ |
| Objects with methods | ✓ reference counted, shareable, nestable | ✓ (Arc<T>) | ✓ (opaques, borrowed or owned) | manual | ✓ (opaque types) | ✓ (#[napi] classes) | ✓ (classes) | ✓ (classes) | ✓ (C++ classes) |
| Callback interfaces | ✓ (vtable; synchronous, any return, throws, optional, failures as Result) | ✓ (foreign traits; any return, throws, async) | partial (Kotlin, C, C++; input-only) | manual fn pointers | partial (closures Rust to Swift) | ✓ (ThreadsafeFunction) | ✓ (closures) | partial (directors) | partial |
| Typed error domains | ✓ (any number per library, open to new codes, payload fields; throws a domain or an untyped any) | ✓ (error enums) | ✓ (Result) | manual | ✓ (Result) | ✓ (JS Error) | ✓ (Result<JsValue>) | ✗ | ✗ |
| Async functions | ✓ (callback ABI, pluggable spawner, native cancellation on every target) | ✓ (poll-based, foreign executors) | ✗ | manual | ✓ (both directions) | ✓ (Tokio) | ✓ (Promise) | ✗ | ✗ |
| Iterators | ✓ (iter<T>, lazy on every target) | ✗ (materialize or use a trait) | partial (DiplomatWrite) | manual | ✗ | ✗ | ✓ (JS iterators) | partial | ✗ |
| Generics / trait objects | ✗ (fixed set of built-in shapes) | partial (traits, no generics) | partial (traits on some backends) | ✗ | partial | ✗ | ✗ | ✓ (templates via %template) | ✓ |
| Multi-file / multi-crate definitions | partial (an IDL split across files with imports:, or one crate’s modules; no types shared between libraries) | ✓ (external types across crates) | ✓ (one bridge crate, many modules) | n/a | ✗ | n/a | n/a | ✓ (%include) | ✓ |
| Workflow | |||||||||
| Standalone CLI | ✓ (cargo install weaveffi-cli) | uniffi-bindgen (build.rs or CLI) | diplomat-tool | ✓ | swift-bridge-cli | napi CLI (npm) | wasm-bindgen-cli | system package | cargo build |
| Publishable per-ecosystem packages | ✓ (weaveffi package: wheels, npm tarballs, gems, an XCFramework SwiftPM package, a .nupkg; Gradle, pub, and Go as ready-to-publish directories) | via companion tools (cargo-swift, maturin, uniffi-bindgen-react-native) | partial | n/a | ✓ (SwiftPM) | ✓ (npm) | ✓ (npm via wasm-pack) | ✗ | n/a |
| Schema-checked IDL with JSON Schema | ✓ | ✗ | n/a | n/a | n/a | n/a | n/a | ✗ | n/a |
| Load-time ABI check | ✓ (ABI revision plus a contract function per declaration) | ✓ (checksums) | ✗ | ✗ | ✗ | ✓ (N-API version) | ✗ | ✗ | n/a |
| Generated-output drift check in CI | ✓ (weaveffi generate --check) | build-time | build-time | ✓ | build-time | build-time | build-time | ✗ | build-time |
| Maturity | pre-1.0 | shipping in Firefox and Mozilla products since 2020 | shipping in ICU4X | 1.0+, widely deployed | 0.1.x, active | 2.x+, widely deployed | 0.2.x, ubiquitous | 30+ years | pre-1.0 |
| License | MIT OR Apache-2.0 | MPL-2.0 | MIT OR Apache-2.0 | MPL-2.0 | MIT OR Apache-2.0 | MIT | MIT OR Apache-2.0 | GPL-3.0 (generated code exempt) | MIT OR Apache-2.0 |
Legend: ✓ = first-class support; partial = supported with caveats, on a subset of backends, or via extensions; ✗ = not supported; manual = you write it by hand; n/a = not applicable to that tool’s scope.
Where competitors are stronger
Pick the right tool for the job. These are the places where another project is ahead of WeaveFFI today.
- UniFFI has the richer type system and more production mileage. It
ships in Firefox, Firefox Sync, Glean, and Nimbus and has years of
battle-testing across iOS, Android, and desktop. Its foreign traits can be
async; WeaveFFI’s callback-interface methods can return any type andthrow, but are synchronous. UniFFI’s custom types can map to a consumer-side type in each language (WeaveFFI’s are converted only on the producer side), and it supports external types across crates, whereas a WeaveFFI library is one namespace (one IDL, possibly split across files, or one Rust producer crate). Its ecosystem of companion tools is larger too:cargo-swiftbuilds the XCFramework and SwiftPM package,maturinbuilds Python wheels, anduniffi-bindgen-react-nativetargets React Native, where WeaveFFI’sweaveffi packagecovers the first two itself and has no React Native target. If your matrix is Kotlin, Swift, and Python and you want maximum maturity, UniFFI is the safer pick. - Diplomat has the more mature Kotlin and JS story for a Rust library. It powers ICU4X, its bridge-crate model keeps everything in Rust, and its C++ backend is polished for slotting into existing C++ builds. Its opaques support borrowed as well as owned references, which WeaveFFI does not model (every WeaveFFI object crossing is a strong reference). Diplomat has no async support and no maps, and callbacks exist only on some backends.
- cbindgen is simpler if all you want is a C header. WeaveFFI generates a C header and ten other targets. If you only consume the C surface from C or C++ code, cbindgen has less ceremony, no IDL, and a smaller footprint. You write the object lifecycle, error channel, and any callback plumbing yourself.
- swift-bridge, napi-rs, and wasm-bindgen are deeper in their one
language. Each exposes idioms WeaveFFI’s common denominator can’t:
swift-bridge bridges async functions in both directions and transparent
Swift structs; napi-rs gives you the full N-API surface (
ThreadsafeFunction, typed arrays,AsyncTask, class inheritance) and Tokio integration; wasm-bindgen talks to the whole Web platform throughweb-sysandjs-sysand runs futures on the JS event loop. If you ship to exactly one of those ecosystems, the dedicated bridge is the better fit. - SWIG covers languages WeaveFFI doesn’t. Lua, Tcl, R, Octave, Perl, PHP, Java: if your target is exotic, SWIG probably has a generator, and it reads C and C++ headers directly so you author no IDL. It also handles C++ templates.
- autocxx is unmatched for “wrap an existing C++ library.” It reads your C++ headers and uses bindgen plus cxx under the hood. WeaveFFI does not parse C++; you describe the surface you want to expose and implement the generated header.
- WeaveFFI’s Wasm target is single-threaded. The default
wasm32-unknown-unknownbuild has no threads, so async functions are polled inline until they finish (a future that waits on something outside the call fails with-1, and there’s little for anAbortSignalto cancel), and callback-interface methods fire only while a call into the module is on the stack. wasm-bindgen’swasm-bindgen-futuresintegrates with the JS event loop natively; WeaveFFI targets onlywasm32-unknown-unknown, which has no threads. - The single-language tools package better for their one ecosystem.
maturin(with PyO3) and napi-rs’s CLI build wheels and npm packages for every platform from one CI matrix with years of edge cases handled;weaveffi packageis newer. - No formal stability guarantee yet. WeaveFFI is pre-1.0, and its schema and C ABI may change between minor releases (see Stability). Revision 6 is designed to grow additively, but UniFFI, cbindgen, napi-rs, wasm-bindgen, and SWIG offer stronger compatibility commitments today.
- Not every target is equally mature. C, C++, Swift, Kotlin, Python, Node.js, and .NET are Tier 1; Go, Ruby, Dart, and WebAssembly are Tier 2 and may lag new ABI work (see Target tiers).
When to choose WeaveFFI
WeaveFFI is the right pick when you want:
- One source of truth for many languages. If your library has to land in npm and SwiftPM and PyPI and NuGet and pub.dev and RubyGems and a Go module and a Gradle artifact, that’s the WeaveFFI sweet spot. UniFFI and Diplomat cover a smaller set out of the box; the single-language bridges don’t try.
- A native library that isn’t (only) Rust. WeaveFFI works against anything that exposes a C ABI: Rust (with WeaveFFI’s attributes generating the ABI for you), C, C++, Zig, and so on. UniFFI, Diplomat, swift-bridge, napi-rs, and wasm-bindgen assume Rust; autocxx assumes C++.
- Objects that behave the same everywhere. Reference-counted interfaces
with deterministic release (
close(),Dispose(),deinit, RAII) and a garbage-collector backstop on every managed target, and the ability to put an object inside a record, a list, a map, an optional, an iterator, or an async result on all eleven targets, from one declaration. - Callback interfaces without hand-written trampolines. Declare the
methods once and each target gets a protocol, interface, or abstract class
to implement; the producer receives an
Arc<dyn Trait>it can retain and call from any thread. Methods can return strings, records, and objects, and a consumer-side exception reaches the producer as a typed domain error (when the method throws one) or throughFrom<ForeignError>, which it can propagate to the original caller with?. - Standalone, publishable consumer packages. Generated packages are
self-contained;
weaveffi buildcross-compiles the producer per platform andweaveffi packagebundles it into wheels, npm tarballs, gems, an XCFramework SwiftPM package, a NuGet package, and Gradle, pub, Go, and C/C++ distributions. There is no “install WeaveFFI” step on the consumer side. - Idiomatic per-target output, not a lowest-common-denominator API.
Async functions become
async/awaitin Swift,Promises in Node and Wasm,suspend funin Kotlin,async defin Python,Task<T>in C#, andFuture<T>in Dart, all from the sameasync: trueflag; Rust producers can plug their own executor withweaveffi::set_spawner. Cancelling the awaiting task, coroutine, or promise cancels the native call. - A CI-first CLI.
validate,generate --check,extract,schema,build, andpackageare designed to drop into pipelines, every generator’s output is byte-for-byte deterministic, and generated consumers refuse to load a producer built for a different ABI revision or from a different API definition (a contract function per declaration, so adding a declaration never breaks a deployed binding).
Other tools
- interoptopus generates C#, C, and Python bindings from annotated Rust
(
#[ffi_function],#[ffi_type]), with patterns for services, slices, options, and callbacks. It’s Rust-only on the producer side and covers fewer languages; its C# backend is especially polished. - flapigen (formerly rust_swig) generates Java (JNI) and C++ bindings
from a declarative
foreign_class!description in the producer’s build script. It’s a good fit when exactly those two consumers matter. - PyO3 with maturin builds a native CPython extension module from Rust: Python classes, exceptions, iterators, and async integration with direct access to the Python object model, and wheels for every platform. For a Python-only library it’s deeper and better integrated than any multi-language tool, WeaveFFI’s Python target included.
- cxx is a safe, statically checked bridge between Rust and C++ in both
directions (
#[cxx::bridge]), sharing types likeString,Vec, andunique_ptrwithout a C layer in between. If both sides are your own Rust and C++, it gives stronger guarantees than WeaveFFI’s C++ target, which wraps a C ABI.
When to choose something else
- You only need Kotlin, Swift, and Python and want maximum stability, or you need async callbacks: use UniFFI.
- You only need a C header for a Rust crate: use cbindgen.
- You ship to exactly one of Swift, Node.js, Python, or the browser: use swift-bridge, napi-rs, PyO3 with maturin, or wasm-bindgen respectively.
- You need Rust and C++ calling each other in one codebase: use cxx.
- You need only C#, or only Java and C++: interoptopus or flapigen may be enough.
- You’re wrapping a large existing C++ codebase from Rust: use autocxx (or cxx plus bindgen directly).
- Your target language is Lua, Tcl, R, Octave, Perl, or PHP: use SWIG.
- You want a Rust-only bridge crate with borrowed-reference semantics and a
polished C++ backend: use Diplomat (
#[diplomat::bridge], from therust-diplomat/diplomatrepository).
Migrating to or from WeaveFFI
WeaveFFI’s IDL is intentionally close to UniFFI’s UDL surface area (records,
enums, interfaces, callback interfaces, error enums, async), which makes
hand-porting straightforward in either direction. There is no automatic UDL
to WeaveFFI converter today. Going the other way, weaveffi extract prints
the IDL a Rust producer’s built library embeds, which is the
starting point for reimplementing a Rust producer in another language. See
Library Mode for details, and the
C ABI contract if you’re bringing a non-Rust producer to
the generated header.
FAQ
Why not UniFFI?
UniFFI is excellent and ships in production at Mozilla; if you need only Swift, Kotlin, and Python and want maximum maturity, it’s the safer pick. WeaveFFI exists for a different set of needs: eleven first-party targets from one definition, a producer that can be written in any language with a C ABI (the generated header is a public contract, not private scaffolding), a standalone CLI built for CI, and a schema-checked YAML or JSON IDL. UniFFI is still ahead on async callback methods, consumer-side custom types, and cross-crate type imports. See the comparison for the full table.
Can I use it with a C++ codebase?
To consume a library from C++, --target cpp emits a header-only RAII API
with std::optional, std::vector, std::future, exceptions, and a
CMakeLists.txt; see C++. To expose an existing C++
library, describe the surface in an IDL and implement the generated C header
in C++; WeaveFFI doesn’t parse C++ headers. For automatic wrapping of C++
headers, look at autocxx or
SWIG.
Does it support generics?
Through built-in shapes rather than user-defined generics: T?, [T],
{K:V}, and iter<T>, which compose with each other and with every other
type, including objects ([Store], {string:Store}, iter<Store>).
Arbitrary generics would push type erasure into every generator;
trait-object interfaces are on the roadmap.
What’s the runtime overhead?
A call costs the marshalling of its arguments, one extern "C" call, and the
marshalling of its result, and every value is one C value. Scalars pass by
value, and optional scalars as a small {has, value} struct. Strings and
bytes pass as borrowed runs (a pointer and a length), so the producer copies
only what it keeps, and numeric lists as typed arrays the producer reads in
place (a &[f64] parameter borrows the caller’s array without copying).
Objects pass as one pointer. Records and other collections are encoded into
one value buffer per value. Async calls add a completion callback and
whatever executor drives the future. The runtime itself is a small module
inside the weaveffi crate; the leak-check counters cost an atomic update
per counted operation and are off by default.
How are errors propagated?
Every fallible C call takes a {prefix}_error* out-parameter; async calls
receive one in their completion. Positive codes belong to the error domain
the callable throws, negative codes are the runtime’s (untyped, panic,
marshalling, callback failure, cancelled). A function declared throws: KvError (a Result<T, KvError> in Rust) surfaces the domain’s codes as
typed errors in every language, and an unknown code added later as the
domain’s base error. A function declared throws: any (a Result with an
untyped error such as String, weaveffi::Error, or anyhow::Error)
surfaces its failure as the library’s base error with a message. A function without throws traps on
failure, since a failure there is a bug. See
Errors and Memory.
Can I split an API across files or modules?
Yes. An IDL can list other files under a top-level imports: (see
Multi-file IDLs), and a Rust producer’s
exported items can live in any module or file of the crate. Either way the
library is one namespace: names are unique across it, and no file or module
appears in a C symbol or a binding’s API.
Can two WeaveFFI libraries live in one process?
Yes. Every symbol, type, macro, package, and environment variable is named
after the library’s own prefix and name (kvstore_error,
KVSTORE_LIBRARY), and none after WeaveFFI, so two libraries never
collide, whether linked statically or loaded dynamically. Each carries its
own copy of the small runtime.
What happens if the bindings and the library drift apart?
They refuse to load. Every generated consumer compares the library’s ABI
revision with the one it was generated against, and calls the contract
function of every declaration it was generated with, checking that it
exists and returns the same signature hash. On a mismatch it raises the language’s load error (a
catchable one, in every language) naming the declaration that’s missing or
changed. The hashes cover declaration names, types, and flags, but not
parameter or field names, documentation, or declaration order, so editing doc
comments or renaming a parameter never breaks a deployed binding, and neither
does adding a function, method, type, or error code, or appending a callback
method to its interface.
In CI, weaveffi generate --check catches stale committed bindings before they
ship.
Does the CLI parse my Rust source?
No. WeaveFFI’s attributes embed a description of each declaration in the
library they’re compiled into, and weaveffi generate builds the crate and
reads that description back out of the library, so macros, type aliases,
#[cfg], and Cargo features are already resolved and the bindings match the
build exactly. weaveffi extract prints it as an IDL. See Library Mode.
Can I customize the generated code?
Through weaveffi.toml: package metadata, per-target names (the Swift
module, the Kotlin package, the Go module path, each set with name), and
target-specific options. Run formatters as a separate step after
weaveffi generate. See
Project Configuration. Changing the C ABI itself is a
generator contribution; see the architecture guide.
Does it work with Flutter?
The Dart target emits dart:ffi bindings with a pubspec.yaml usable from
Flutter and plain Dart on every platform that supports dart:ffi.
weaveffi package --target dart bundles the desktop libraries under
native/<platform>/; for iOS and Android you add the library to the Flutter
app’s native build yourself, since Flutter’s native-assets build isn’t
generated yet. For the web, use the WebAssembly target. See
Dart.
Is it Windows-friendly?
The CLI is plain Rust and runs on Windows, and the workspace’s tests run on
Windows in CI. Headers carry a {PREFIX}_API macro that resolves to
__declspec(dllimport) for consumers and dllexport when a C or C++
producer defines {PREFIX}_BUILD, and every loader knows the {library}.dll
naming. The conformance harness runs on Linux and macOS today; Windows lanes
are on the roadmap.
How do I distribute the native library?
Build it per platform and let weaveffi package bundle it into each
ecosystem’s package layout (npm platform packages, platform wheels, NuGet
runtimes/, an XCFramework, and so on), then publish with each
ecosystem’s own tools. Every generated manifest takes its name and version
from [package]. See Packaging.
Who owns an object, and when is it freed?
The producer reference-counts it. Each wrapper holds one strong reference and
releases it through the language’s disposal idiom (close(), Dispose(),
deinit, a destructor), with a garbage-collector backstop; the object is
freed when the last reference anywhere goes. Objects returned, yielded,
delivered, or passed to a callback are references the receiver adopts;
objects passed to the producer are borrowed. See
Errors and Memory.
Which executor runs my async functions, and how does cancellation work?
By default, Tokio (the weaveffi crate’s default tokio feature): the
current runtime when the call is made from inside one, otherwise one the
library creates. With default-features = false, each call runs on a thread
of its own. weaveffi::set_spawner installs any other executor and
overrides both. Consumers see their native async idiom, and cancelling it (a Swift Task, a Kotlin coroutine, an
AbortSignal, a CancellationToken, a Go context) cancels the native
call: the runtime drops the future and completes with the cancelled code,
which surfaces as the language’s cancellation error. See
Async and Cancellation.
What’s the license?
MIT OR Apache-2.0, at your option. Generated code carries no license header of its own and is yours to license as you like.
Stability and Versioning
WeaveFFI will follow Semantic Versioning from 1.0.0. Until then it’s in active pre-1.0 development and any surface may change between minor releases. This page says what the version numbers mean, what 1.0 will promise, and how to keep a downstream project steady today.
Three version numbers
- The crate version is shared by every published crate (
weaveffi,weaveffi-macros,weaveffi-model,weaveffi-cli) and by the CLI. Releases are cut from Conventional Commits by release-plz, which bumps it and tagsv{version}. - The IDL schema version (
0.13.0) is theversion:an IDL document declares, and every file it imports declares the same one. Pre-1.0, only the current version is accepted; a document declaring any other is rejected withUnsupportedSchemaVersion. A Rust producer’s embedded metadata records the schema version too, and a library built by another WeaveFFI version is refused when the CLI reads it. - The C ABI revision (
6) is what{p}_abi_version()returns. It changes only when the runtime surface, the value-buffer encoding, or a calling convention changes incompatibly, independently of the other two. Revision 6 is designed to grow additively: new declarations, new callback methods appended to their interface, and new error codes each get their own contract function, and vtables are open, so adding one never needs a new revision and never breaks a deployed binding.
What 1.0 will cover
After 1.0.0, these surfaces change incompatibly only in a major release:
- The CLI: subcommands, flags, exit codes, and documented output
formats (
validate --format jsonin particular). - The IDL schema: accepted keys, type syntax, and the exported JSON Schema.
- Generated code: exported symbols, signatures, type names, and package layouts. A patch release won’t change generated bytes; a minor release may add symbols but won’t remove or rename any.
- The C ABI revision and the contract it names.
- The public Rust API of the published crates (the
weavefficrate’s hidden runtime module, which only macro expansions name, isn’t part of it).
Target tiers
Every target passes the same conformance gate (real consumers against every sample, with every leak counter at zero) before a release ships, but they come in two tiers:
- Tier 1: C, C++, Swift, Kotlin, Python, Node.js, and .NET. A change to the ABI or the IDL lands in every Tier 1 target at once, and their generated APIs are what 1.0 will freeze first.
- Tier 2: Go, Ruby, Dart, and WebAssembly. These are fully supported and conformance-tested, but may lag Tier 1 on new ABI work and may change shape more freely before 1.0.
Deprecation will precede removal after 1.0: a deprecated feature warns for
at least one minor release (the CLI prints a diagnostic, and generators emit
each language’s deprecation marker from the IDL’s deprecated: field) and
is removed in the next major release. Post-1.0 schema bumps will ship with a
migration tool and accept more than one version.
Determinism
Regenerating with the same WeaveFFI version from the same definition and
weaveffi.toml produces byte-identical output on every platform. Generators
never iterate hash maps into output, and a test regenerates the fixtures
twice and compares. Non-determinism is a bug; please report it with the
definition that triggers it.
CI workflow
Pin the CLI version and commit the generated output, generation records
({out}/.weaveffi/) included, so an upgrade is an explicit, reviewable
change. Then gate CI on weaveffi generate --check, which renders in memory
and compares with the committed directory without writing anything:
- name: Bindings are up to date
run: |
cargo install weaveffi-cli --locked --version "=${WEAVEFFI_VERSION}"
weaveffi validate --warn
weaveffi generate --check
generate --check lists the files that would change and exits 0 when
the output matches and 1 otherwise (generate --diff prints the diff).
For a Rust producer, both commands build the crate first (see
Library Mode), with the features in [build], so the
job needs the Rust toolchain; pass --library <path> to reuse a library an
earlier step built.
Documentation versions
The book at https://weaveffi.com/ documents the latest release. Each
release’s book also stays published under /v{major}.{minor}/ (for example
/v0.26/), and the book for the development head of main is under
/dev/. The version a page documents is shown in its header.
Roadmap
WeaveFFI is in active 0.x development. This page lists what comes next.
Items are planned (the design is settled) or exploring (wanted, with
open design questions). Nothing carries a date; the
changelog
records what shipped.
Callback interfaces
Async callback methods (planned)
A callback method that returns a future on the consumer side needs a completion flowing the other way and a cancellation story when the producer drops the future. The vtable shape is simple (a completion function and context per async method, which open vtables can add without a new revision); the hard part is one producer working the same way whether the consumer runtime is an event loop, a thread pool, or the single-threaded Wasm host.
Off-thread value callbacks in Dart (exploring)
Dart can’t run a value-returning callback method synchronously on a thread
that isn’t its isolate’s, so the Dart binding marks its vtables
thread-affine, and a producer that calls such a method from one of its own
threads gets -4 (callback called off its thread) instead of a result.
That’s safe, but it means a Dart callback that returns a value only works
when the producer calls it on the thread that passed it in. Lifting the
restriction needs a way to hop to the isolate and wait for the result.
Definitions
Types shared between libraries (exploring)
A library is one namespace, and an IDL can be split across files with
imports:, but two libraries can’t share a type: each declares its own. A
monorepo wants one library’s bindings to reference another’s records and
objects. The open questions are how the bindings find each other’s types
and how each library’s contract covers the shared ones.
Duration and timestamp primitives (exploring)
Producers pass time as an integer with a documented unit (a Rust producer
can declare a custom type, as the macro tour’s Timeout does). duration
and timestamp primitives mapped to each language’s types would remove the
ambiguity; the open question is the representation.
Consumer-side custom types (exploring)
A Rust producer can declare a custom type (#[weaveffi::custom]) that
crosses as a builtin, such as a Uuid as a string, but every binding
still exposes the builtin. Per-language conversion hooks in weaveffi.toml
would let a binding expose the language’s own type (java.util.UUID,
Foundation.UUID, uuid.UUID) instead; the open questions are how a hook
is declared and how a conversion failure on the consumer side is reported.
Generic and trait-object interfaces (exploring)
WeaveFFI has a fixed set of generic shapes (T?, [T], {K:V}, iter<T>).
Under discussion are trait-object interfaces (one declared method set with
several producer implementations behind Arc<dyn Trait>) and, less likely,
parameterized interfaces monomorphized per instantiation.
Targets and runtime
Kotlin Multiplatform (exploring)
The Kotlin target reaches Android and the JVM. A Multiplatform flavor using
Kotlin/Native cinterop for iOS and desktop is the natural next step.
Wasm threads and JSPI (exploring)
On wasm32-unknown-unknown futures are polled inline and callbacks fire
only while a call is on the stack. A spawner that schedules on the JS event
loop, JavaScript Promise Integration (so a pending future can suspend the
module until a promise settles), or shared-memory builds with Web Workers
would lift those limits.
Zero-copy blittable records (exploring)
Every record crosses as a serialized value buffer. A record of fixed-size
scalars could instead cross as a #[repr(C)] struct, which matters for hot
paths that move many small records. (Numeric lists already cross as typed
arrays.) The open questions are how a record opts in, and how the contract
and every target’s layout checks keep the two sides agreeing on the layout.
Poll-based async (exploring)
Async functions complete through a callback the producer fires on its own thread, and each binding hops back to its scheduler. A poll-based protocol, where the consumer’s runtime drives the future and the producer only wakes it, would fit event-loop runtimes better and avoid that hop. It would be an option next to the completion-callback ABI, not a replacement.
Per-language support packages (exploring)
Every package inlines its helpers (codec, error types, object base), which keeps consumers free of dependencies but means a codec fix ships as a regeneration. Opt-in shared support packages per ecosystem are under consideration; inlining would stay the default.
Testing
Windows conformance lanes (planned)
The workspace’s tests run on Windows, Linux, and macOS, but the conformance
harness runs only on Linux and macOS. Adding Windows lanes means making
conformance/run.sh and the per-language scripts portable (or adding
PowerShell equivalents) and installing each toolchain on Windows runners.
Toward 1.0
1.0 means the surfaces in What 1.0 will cover stop changing without a major release. ABI revision 6 was designed so that the ABI can keep growing after 1.0 without a new revision: new declarations, callback methods, and error codes are additive, error domains are open, and vtables accept a consumer generated before a method was appended. 1.0 needs:
- every Tier 1 target (C, C++, Swift, Kotlin, Python, Node.js, and .NET) passing the full conformance matrix on Linux, macOS, and Windows, and the Tier 2 targets (Go, Ruby, Dart, and WebAssembly) on at least Linux and macOS (see Target tiers);
- the deprecation policy in place;
- a schema migration tool and more than one accepted schema version;
- the known limitations on each generator page resolved or documented as permanent;
- a review of every published crate’s public API.
Contributing
Open an issue or discussion on GitHub if an item here matters to you or something you need is missing.
Rust Crates
WeaveFFI is published as four crates that share one version:
| Crate | Use it when |
|---|---|
weaveffi | You’re writing a Rust producer. It’s the only dependency a producer needs: the attributes, the few types a producer names, and the runtime the attributes expand against. |
weaveffi-macros | Never directly; weaveffi re-exports its macros. |
weaveffi-model | You’re building a tool on the IR: parsing (with imports), validating, or extracting an API, reading library metadata, or reading the validated Model. Its default idl feature adds the YAML and JSON formats, the JSON Schema, and rich diagnostics. |
weaveffi-cli | You want the weaveffi command (cargo install weaveffi-cli), or you’re driving or extending the generators from Rust (project::Project loads a project, from a build.rs too). |
- Rust API Map lists the items a producer uses from
weaveffi, and the entry points of the other crates. - Doc Comment Style is the convention for the doc comments themselves.
The full API docs are published at
weaveffi.com/api/rust/weaveffi/
(under each version’s path too, /v{major}.{minor}/api/rust/) and build
locally with:
cargo doc --workspace --all-features --no-deps --open
Every public item in the library crates is documented, enforced by
#![deny(missing_docs)] and the Clippy doc lints.
Rust API Map
A map of the public API: what a Rust producer uses from the weaveffi
crate, and the entry points of the crates tools build on. cargo doc has
the full signatures; this page says which items you’ll reach for.
[dependencies]
weaveffi = "0.25"
The weaveffi crate
| Item | Purpose |
|---|---|
#[weaveffi::export] | Exports a function, or every pub fn of an interface’s inherent impl block as a constructor, method, or static. An async fn is async, cancellable when its last parameter is a CancelToken; a Result return throws its error type (a domain, or any for an untyped error). #[weaveffi(skip)] leaves a member out. |
#[weaveffi::record] | A struct with named fields, crossing by value. |
#[weaveffi::enumeration] | A C-style enum, or a rich enum whose variants carry named fields. |
#[weaveffi::error] | An error domain: explicit positive codes, optional fields, and a generated Display (from #[weaveffi(message = "...")] templates or the variants’ docs) and std::error::Error, unless written #[weaveffi::error(no_display)]. |
#[weaveffi::interface] | A reference-counted, Send + Sync object type. |
#[weaveffi::callback_interface] | A Send + Sync trait the consumer implements, each method returning Result<T, E> with E: From<ForeignError>; accepted as Arc<dyn Trait> or Option<Arc<dyn Trait>>. |
#[weaveffi::custom(repr = R, lift = f, lower = g)] | A type alias or struct that crosses as R. |
weaveffi::export_runtime!() | Exports the runtime symbols under the crate’s prefix and defines the crate’s tag type; call once, at the crate root. |
Iter<T> | The return type for iter<T>; build one with Iter::new from anything IntoIterator. |
CancelToken | A cancellable async fn’s last parameter; is_cancelled() for cooperative cleanup. |
ForeignError | A consumer callback’s failure (code, message), which every callback method’s error type converts from. As an exported function’s error type it’s throws: any. |
Error | An untyped error (throws: any) that any std::error::Error converts into with ?; Error::msg makes one from any Display. |
set_spawner, Spawner, BoxFuture | Install the executor async functions run on, overriding the default (Tokio, or a thread per call without the tokio feature). |
The features are tokio (default: async exports run on Tokio),
leak-check (live-resource counters for {p}_debug_live), and anyhow
(anyhow::Error as an untyped error). The
producer macro guide covers every attribute.
The runtime the attributes expand against lives in a hidden module of the
weaveffi crate. Producers never name it, and it isn’t part of the crate’s
semver surface; the C ABI contract is the
specification it implements.
weaveffi-model
| Module | Purpose |
|---|---|
ir | The IR an IDL document or a producer’s metadata becomes: Api and its declarations, TypeRef, Throws, and CURRENT_SCHEMA_VERSION. |
parse | load_api (a document with every file it imports) and parse_api_str (one document), with miette diagnostics. Requires the idl feature. |
validate | validate(&api, &identity, sources), which reports every violation and builds the Model; collect_warnings for the advisory lints. |
model | The validated Model generators render from, with every C symbol and lowered signature, and ABI_VERSION. |
ty, abi | Resolved types and their families (Ty, Family, RunKind), and the C type algebra (CType, AbiFn). |
pkg | Package (the [package] table) and the resolved Identity. |
contract | Contract ids, canonical signatures, and FNV-1a hashing. |
meta | The metadata frames a producer embeds, and assemble, which turns them back into an Api. |
errors | The error-type naming rule every target shares. |
weaveffi-cli
| Item | Purpose |
|---|---|
project::Project | Locate a project as the weaveffi command does, read its API (from an IDL or a producer’s built library), and validate it into a Model. |
codegen::Orchestrator | Render targets and write them to an output directory, rewriting only changed files and removing stale ones. |
config::ProjectConfig | The parsed weaveffi.toml. |
targets::{Target, REGISTRY} | The trait every generator implements and the list of registered targets. |
package | The artifact types weaveffi package writes. |
Library Mode shows a
build.rs that uses Project and the Orchestrator.
Doc comment style
This page describes how WeaveFFI’s Rust doc comments are written. Follow it when you add or revise public API so the generated Rust API docs read consistently and the doc lints stay green in CI.
TL;DR
- Every public item carries a doc comment. This is enforced by
#![deny(missing_docs)]on each library crate. - Use
///for items,//!for modules and crates. - The first line is a short imperative summary ending in a period.
- Document fallible and panicking behavior with
# Errors,# Panics, and# Safetysections. These are the Rust analog of “what can go wrong,” and the matching Clippy lints require them. - Link other items with intra-doc links:
[`Model`]or[`Api`](weaveffi_model::ir::Api). - Wrap code-like identifiers in backticks. Product and tool names
(WeaveFFI, SwiftPM, CMake) are allow-listed in
clippy.tomlinstead. - Comments explain why, not what.
Grammar and punctuation
Prose in doc comments and Markdown follows the Chicago Manual of Style
(17th edition), matching the repository’s AGENTS.md. Highlights:
- No em dashes (
U+2014). Use commas, parentheses, semicolons, colons, or separate sentences instead. - Use straight ASCII quotes and apostrophes (
"and'), not curly ones, so prose stays copy-pasteable into source and terminals. - Use the serial (Oxford) comma in lists of three or more.
- Use contractions where they read naturally (“doesn’t,” “isn’t”).
- Use sentence case for headings: capitalize only the first word and proper nouns.
Doc comments
WeaveFFI follows the conventions in
RFC 1574
and the rustdoc book.
The standard section headings (# Examples, # Errors, # Panics,
# Safety) play the role that Args, Returns, and Raises play in a
Google-style docstring.
Functions and methods
#![allow(unused)]
fn main() {
/// Generate bindings for every requested target and write them to `out_dir`.
///
/// Targets are rendered from a shared [`Model`] so symbol names and
/// parameter lowering are computed once and reused across languages.
///
/// # Errors
///
/// Returns an error if the IDL fails to validate, a requested target is
/// unknown, or any output file cannot be written.
///
/// # Examples
///
/// ```no_run
/// use my_crate::generate;
/// # use weaveffi_model::ir::Api;
/// # fn demo(api: Api) -> anyhow::Result<()> {
/// generate(&api, "./generated", &["c", "swift"])?;
/// # Ok(())
/// # }
/// ```
pub fn generate(api: &Api, out_dir: &str, targets: &[&str]) -> anyhow::Result<()> {
// ...
}
}
Notes:
-
Lead with a one-line imperative summary, then a blank line, then any extended description.
-
Refer to parameters by name in backticks (
`out_dir`). Don’t restate their types; the rendered signature already shows them. -
Add a
# Errorssection to every public function that returnsResult, describing the conditions that produce anErr. Clippy’smissing_errors_docenforces this. -
Add a
# Panicssection to any public function that can panic, describing when. Clippy’smissing_panics_docenforces this. If a panic path is provably unreachable (for example anexpecton sanitized input), suppress it locally with a reason instead of documenting a panic that cannot happen:#![allow(unused)] fn main() { // `CString::new` is infallible here: interior NUL bytes are stripped above. #[allow(clippy::missing_panics_doc)] pub fn string_to_c_ptr(s: impl AsRef<str>) -> *const c_char { // ... } } -
Prefer
```no_runor```ignorefor examples that need a builtcdylib, a file path, or other state the doctest can’t set up. Use a plain```rustblock (whichcargo testcompiles and runs) when the snippet is self-contained.
unsafe functions
Every public unsafe fn, and any function that dereferences raw pointers
across the C ABI, needs a # Safety section spelling out the caller’s
obligations. Clippy’s missing_safety_doc enforces this.
#![allow(unused)]
fn main() {
/// Register a handle and its destructor with the given arena.
///
/// # Safety
///
/// `arena` must be a valid pointer returned by `arena_create`. `ptr` and
/// `dtor` must stay valid until `arena_destroy` is called.
pub unsafe fn arena_register(arena: *mut HandleArena, ptr: *mut c_void, dtor: Dtor) {
// ...
}
}
Structs, enums, and their members
Document the type, then every public field or variant. missing_docs
flags undocumented pub fields and variants, not just the type itself.
#![allow(unused)]
fn main() {
/// Error struct passed across the C ABI boundary.
#[repr(C)]
pub struct FfiError {
/// Status code. `0` means success; a positive value is a domain error
/// code and a negative value is one of the reserved runtime codes.
pub code: i32,
/// Owned UTF-8 message (not NUL-terminated), or null when it's empty.
pub message_ptr: *const u8,
/// Byte length of `message_ptr`; `0` when null.
pub message_len: usize,
/// Owned value buffer holding the error code's payload fields, or null
/// when the code declares no fields.
pub payload_ptr: *const u8,
/// Byte length of `payload_ptr`; `0` when null.
pub payload_len: usize,
}
/// How a value crosses the ABI boundary.
pub enum Ownership {
/// The callee owns the value; the caller must not free it.
Borrowed,
/// Ownership transfers to the caller, who must free it.
Owned,
}
}
Field and variant docs can be terse. One clause that says what the field means (not what its type is) is usually enough.
Modules and crates
Open every crate’s lib.rs with a //! summary, and every module with a
//! header describing its role:
#![allow(unused)]
fn main() {
//! C ABI runtime: error struct, memory helpers, and utility functions.
}
Crate-level docs are enforced separately by
RUSTDOCFLAGS="-D rustdoc::missing_crate_level_docs" in CI, so a crate
without a //! header fails the rustdoc job.
Private items
missing_docs only requires docs on the public API, so private helpers
aren’t strictly required to have them. Still, write a short /// line for
non-obvious private items: contributors read them in editors and reviews.
Comments: explain why
Comments are most useful when they explain things the reader can’t learn from the code itself:
- a non-obvious invariant or ABI constraint,
- a trade-off between two reasonable approaches,
- a reference to an external spec, RFC, or upstream bug.
Don’t narrate what the next line does (// increment the counter) or
restate a name (// the generator). Delete redundant comments when you
find them.
Intra-doc links
Link to other items so rustdoc can resolve and cross-reference them. This is the Rust analog of the docs site’s autorefs:
#![allow(unused)]
fn main() {
/// Renders from the shared [`Model`], never re-deriving lowering.
///
/// See [`Api`](weaveffi_model::ir::Api) for the input model and
/// [`Target`](crate::targets::Target) for the trait every
/// generator implements.
}
Use the short [`Type`] form when the item is in scope, and the
[`Type`](path::to::Type) form to link across modules or crates.
doc_markdown and backticks
Clippy’s doc_markdown lint flags identifiers that look like code but
aren’t wrapped in backticks. Wrap real identifiers, types, paths, and
file names in backticks (`Model`, `weaveffi.toml`).
Product names, tool names, and naming-convention terms (WeaveFFI, SwiftPM,
CMake, NuGet, snake_case, PascalCase) read as prose, not code. Rather
than backticking them, they’re allow-listed in clippy.toml under
doc-valid-idents. Add a new entry there when you introduce another such
name.
Enforcement
The doc lints are set in each library crate’s lib.rs, and clippy.toml
holds the doc_markdown allow list. Every library crate denies
missing_docs; weaveffi, weaveffi-model, and weaveffi-cli also turn
on the Clippy doc lints below (weaveffi-macros exports only proc macros,
which missing_docs covers):
| Lint | What it requires |
|---|---|
missing_docs (deny) | A doc comment on every public item, field, and variant |
clippy::missing_errors_doc | A # Errors section on public fns returning Result |
clippy::missing_panics_doc | A # Panics section on public fns that can panic |
clippy::missing_safety_doc | A # Safety section on public unsafe fns (on by default) |
clippy::doc_markdown | Backticks around code-like identifiers |
CI runs these through the existing gates, so missing or malformed docs fail the build. Check your changes locally before pushing:
# Lint everything, including the doc lints (warnings are denied).
cargo clippy --workspace --all-targets -- -D warnings
# Build the API docs the way the rustdoc job does.
RUSTDOCFLAGS="-D warnings -D rustdoc::all -D rustdoc::missing_crate_level_docs" \
cargo doc --workspace --no-deps
# Or run formatting, clippy, and rustdoc together.
just check
The generated API reference is published under /api/rust/ on the docs
site when it deploys; the Rust API Map is the guided tour.