Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
b929875
chore(quest): claim quest/m2/wasm/backend.md
kixelated Nov 16, 2026
828b7e2
feat(ffi): the web target, TypeScript over a wasm32-wasip1 build
kixelated Nov 16, 2026
5e2c9f9
fix(ffi): the other bindings' scripts for the host-only Spawned and t…
kixelated Nov 16, 2026
2fc7e41
fix(ffi): web review round 1: private opaque values, a kept U+FEFF, s…
kixelated Nov 16, 2026
a6b7581
fix(ffi): an opaque value's bytes never reach a caller
kixelated Nov 16, 2026
f140401
fix(ffi): web review: give back the stack after a callout, import nam…
kixelated Nov 16, 2026
df80063
fix(ffi): web review: no Rust cleanup after a trap, futures that alwa…
kixelated Nov 16, 2026
20d595d
fix(ffi): a refused load leaves no abort for the next
kixelated Nov 16, 2026
8e0aa4e
test(ffi): a variant's tag field and a trap in a later poll, against …
kixelated Nov 16, 2026
21d665a
test(ffi): a trap Rust raises in a later poll, with a marker the harn…
kixelated Nov 16, 2026
f59e928
Merge remote-tracking branch 'origin/main' into HEAD
kixelated Nov 16, 2026
3de6dea
docs(quest): the web target moves off wasm32-wasip1, and the bytes cr…
kixelated Nov 16, 2026
0e11da8
Merge origin/main into quest/m2/wasm/backend
kixelated Nov 16, 2026
4704cb7
fix(ffi): a web future that is not Send starts and polls with its thr…
kixelated Nov 16, 2026
f8767e1
fix(ffi): a web handle disposed while a call lowers is freed after it
kixelated Nov 16, 2026
7969a84
style(ffi): format the web poll's outputs
kixelated Nov 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 78 additions & 3 deletions ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ those functions look up by name. `python/<prefix>.py` holds it in Python, over a
extension the crate builds with `--features python`, `swift/<prefix>.swift` holds it in
Swift, over the C header as a clang module, `go/` holds it in Go, a package per crate
over the C ABI through cgo, and `dart/<prefix>.dart` holds it in Dart, over the C ABI through
`dart:ffi` and what the crate builds with `--features dart`.
`dart:ffi` and what the crate builds with `--features dart`. When `wasm32-wasip1` is among
the targets, `web/` holds it in TypeScript for the web, ES modules over the `.wasm` the
crate builds with `--target wasm32-wasip1 --features web`.
An export again rewrites only the files whose content changed, and removes from
`include/<prefix>/` and `go/` only what it no longer writes, so a build of an unchanged
`include/<prefix>/`, `go/`, and `web/` only what it no longer writes, so a build of an unchanged
export stays fresh. The crate's version, `0.0.0+<hash>`, hashes its Rust sources and
manifest, so exports that differ build apart in a target directory they share.

Expand Down Expand Up @@ -1255,10 +1257,83 @@ would export, and fails on it, so the list holds only what the export refuses. I
fails on an `instance not inferred` refusal, which is a bug in the exporter's inference
rather than in the crate.

## TypeScript (web)

`web/` is TypeScript over the C ABI of the crate built for `wasm32-wasip1` with `--features
web`, tested on Node 24, whose type stripping runs it as it is. Each file is an ES module a
bundler takes as it is, importing its neighbors by their `.ts` names; the `.wasm` needs no
tool run on it after `cargo build`, and no wasm-bindgen. The binding serves
`wasm32-wasip1` alone: an item another target has and it lacks is left out, not declared to
fail. `load(source)` of `index.ts` compiles and instantiates the module, from its bytes, a
`Response`, or a `WebAssembly.Module`, before any other call, and checks its contract and
target there.

- **The platform** is the web's: the module's std is `wasm32-wasip1`'s, whose imports are a
detail between the generated module and its binding, which implements each with the web
API for it, so nothing of WASI ships. Its clocks are `performance.now`, from
`performance.timeOrigin` for the real-time one; its randomness `crypto.getRandomValues`;
its stdout and stderr `console.log` and `console.error`, a line at a time; its
environment and arguments empty; and its exit an abort. `load` refuses a module importing
anything else. Measured on the api fixture, stripped, with LTO at `opt-level = "s"`, that
std costs 24 KB over `wasm32-unknown-unknown`'s (3%), 9.5 KB gzipped, and the glue 2 KB
more; `wasm32-unknown-unknown` has no clock, so `Instant::now` panics there.
- **The API** is rust2-ts's shape: each type is a module of its own, `web/<Type>.ts`, which
exports the type by its name and its functions, each taking `self` first, so a caller
writes `import * as Counter from "./web/Counter.ts"` and `Counter.get(c)`, and a bundler
drops every function no caller names. `index.ts` holds the free functions, the constants,
and `load`. Names are the C names without the prefix: a type in Pascal case, and a
function in camel case, a constant's in upper case; a reserved word is exported as is
from a local with a trailing `$`, so `Counter.new("c", 1)` and `Point.default()` work
through the module's namespace.
- **Values**: a record is a plain object of its fields in camel case, positional ones `_0`,
`_1`, and so on; an opaque value an `rt.Opaque`, its bytes, which only Rust makes. A plain
enum is a union of its variants' names, and an enum with data a union of objects tagged
by `tag`. A tuple is an array, `Option<T>` is `T | undefined`, or `T | rt.None` where `T`
can already be `undefined`, `Result<T, E>` an `rt.Result`, `{ ok: true, value }` or `{ ok:
false, error }`, and an error is that value, never thrown. `u8` through `u32`, `usize`,
`isize`, `f32`, `f64`, and `char` are numbers, each checked as it crosses in; `u64`, `i64`,
and `u128` are rust2-ts's `rt.u64` and so on, a number while a safe integer and 32-bit
limbs past it, converted from the `bigint` a wasm `i64` is at the boundary, which costs a
getter 9% over returning that `bigint` as it is. `String` and `&str` are strings, bytes a
`Uint8Array`, a `Vec` of numbers the typed array holding them exactly, any other `Vec` an
array, a path an `rt.PathBuf` of its bytes, and `Duration`, the addresses, and the ranges
plain objects. A `&mut` value is an `rt.Place`, whose `v` the call writes back, and a
value's `&mut self` method returns it first, as Dart's does.
- **Memory**: each call lowers what it passes onto a stack of the binding's in linear
memory, which it gives back once the call returns, and reads what Rust returns at the
layouts C's wasm32 ABI gives the header's structs, passing a struct of one scalar as it,
any other through a pointer to a copy, and one returned through a pointer passed first.
Bytes and text Rust returns are copied out, and the buffer freed at once, so no view
outlives a growth of memory, which detaches it; what Rust lends a closure or trait is
copied before any call it makes can grow memory. A copy costs what V8's allocation of
the `ArrayBuffer` does, about 0.8 µs for 1 KiB on Node 24.
- **Objects** are an `rt.Handle`, disposed by `[Symbol.dispose]`, as `using` does. Of a
checked type, disposing it drops the value through Rust's own `_drop`, which fails while
a call borrows it; of any other, it throws while a call holds it. The handle is freed once
disposed and no call holds it, so one disposed while a later argument lowers fails the
call's check rather than reach Rust freed. A call that meets a disposed handle throws
`<Type> is closed`, and a `FinalizationRegistry` frees one never disposed. On Node 24, a returned object disposed
costs 0.5 µs, 0.2 µs of it the registry's, against 0.1 µs for the C calls alone.
- **Traits** are interfaces JavaScript implements, with an optional `close()` Rust calls
once it drops an implementation, and **closures** are functions: each is a C function
the module imports from `rust2`, whose data is a token the binding finds the value by, so
JavaScript never writes the module's function table. Its std traits are functions of its
module: `toString`, `debug`, an object's `clone`, `eq`, with `Hash` `hash`, and `default`.
- **Futures** are an `rt.Call`, a `Promise` with `cancel()`: the call polls once as it is
made, and each wake polls again on a microtask, never inside the wake. Cancelling frees
the future in Rust, losing nothing, and rejects with `rt.Cancelled`. A future JavaScript
implements is any promise, a waker a function, and a reader an `rt.Reader`.
- **Failure**: a run-time check that fails throws an `Error` naming the C function and the
check, as each binding raises. Rust's panic aborts the module, as do a throw out of a
closure, trait, or reader, since Rust has nowhere to unwind to: the message goes to
`console.error`, and every later call throws, since nothing of Rust's state is sound.
- **Threads**: none. wasm32 runs Rust on JavaScript's one thread, with no shared memory and
no atomics, so no check of a value that is not `Send` or `Sync` can fail.

## Tests

```bash
just ffi test # export the fixtures, build them, and drive api from C, C++, Kotlin, Python, Swift, Go, and Dart
just ffi test # export the fixtures, build them, and drive api from C, C++, Kotlin, Python, Swift, Go, Dart, and TypeScript on Node
just ffi moq # export moq's crates at the pinned revision, build them, and run moq/moq.c, moq/moq.cpp, moq/moq.kt, moq/moq.py, moq/moq.swift, moq/moq.go, and moq/moq.dart
just ffi moq-c # the same export, built in debug, running only moq/moq.c: `just ci`'s check on moq
just ffi moq-cpp # the same export, running only moq/moq.cpp
Expand Down
14 changes: 7 additions & 7 deletions ffi/fixtures/api/examples/transcript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1012,8 +1012,8 @@ fn main() {
let nines = api::Mark::of(9);
let (front, back) = (api::seat(nines, 1), api::seat(nines, 2));
println!("seat {front:?} {} {}", front == front.clone(), front == back);
// A kept closure, called on another thread after the call that took it returned.
println!("spawned {}", api::Spawned::new(|| 7).join());
// A kept closure, called on another thread after the call that took it returned, is
// each native language's own check, since wasm32 has no thread to call it on.
// A kept closure: called again at the instant it asks for, then once its waiter wakes.
let start = api::Moment::new(0, 1000).unwrap();
let mut calls = 0;
Expand Down Expand Up @@ -1086,15 +1086,15 @@ fn finish<F: std::future::Future>(future: F) -> F::Output {
}
}

/// A path no Rust string spells: on Unix, bytes that are not UTF-8; on Windows, a lone
/// surrogate, which is WTF-8's `ed a0 80`.
#[cfg(unix)]
/// A path no Rust string spells: on Unix and WASI, bytes that are not UTF-8; on Windows, a
/// lone surrogate, which is WTF-8's `ed a0 80`.
#[cfg(any(unix, target_os = "wasi"))]
fn unspelled() -> std::path::PathBuf {
api::stray()
}

/// A path no Rust string spells: on Unix, bytes that are not UTF-8; on Windows, a lone
/// surrogate, which is WTF-8's `ed a0 80`.
/// A path no Rust string spells: on Unix and WASI, bytes that are not UTF-8; on Windows, a
/// lone surrogate, which is WTF-8's `ed a0 80`.
#[cfg(windows)]
fn unspelled() -> std::path::PathBuf {
<std::ffi::OsString as std::os::windows::ffi::OsStringExt>::from_wide(&[0xd800]).into()
Expand Down
76 changes: 66 additions & 10 deletions ffi/fixtures/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ pub use dep::*;
/// The largest value a [`Counter`] reaches.
pub const LIMIT: u64 = 1000;

/// The largest `i64`, past what a binding's float holds exactly.
pub const FAR: i64 = i64::MAX;

/// A point: a record, since every field is `pub`. Its docs reach the header, where a
/// comment such as `/* this */` must not close the header's own.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
Expand Down Expand Up @@ -948,12 +951,14 @@ pub async fn drive<E>(start: Moment, mut poll: impl FnMut(Moment, &Waiter) -> Re
.await
}

#[cfg(not(target_arch = "wasm32"))]
/// A thread running a closure it keeps past the call that made it, which
/// [`Spawned::join`] waits on.
pub struct Spawned {
thread: std::thread::JoinHandle<u32>,
}

#[cfg(not(target_arch = "wasm32"))]
impl Spawned {
pub fn new(task: impl FnOnce() -> u32 + Send + 'static) -> Self {
Self {
Expand Down Expand Up @@ -1146,6 +1151,7 @@ impl Channel {
/// Sends from another thread, before it returns, so the wake lands from that thread, as
/// an async runtime's worker wakes a task: the one way Dart, whose isolates share no
/// object, has to wake from another thread.
#[cfg(not(target_arch = "wasm32"))]
pub fn send_from_thread(&self, payload: Bytes) {
std::thread::scope(|scope| {
scope.spawn(|| self.send(payload));
Expand Down Expand Up @@ -1713,17 +1719,20 @@ pub fn emit(log: impl Log, lines: Vec<u8>) -> u32 {
lines.iter().filter(|&&n| log.log(n, &format!("line {n}"))).count() as u32
}

#[cfg(not(target_arch = "wasm32"))]
/// [`emit`] on another thread, which the call waits on.
pub fn emit_from_thread(log: impl Log, lines: Vec<u8>) -> u32 {
on_thread(&log, &lines)
}

#[cfg(not(target_arch = "wasm32"))]
/// [`emit_from_thread`] before it returns its future, and again once polled.
pub fn emit_later(log: Box<dyn Log>, lines: Vec<u8>) -> impl Future<Output = u32> + use<> {
let eager = on_thread(&*log, &lines);
async move { eager + on_thread(&*log, &lines) }
}

#[cfg(not(target_arch = "wasm32"))]
fn on_thread(log: &(impl Log + ?Sized), lines: &[u8]) -> u32 {
std::thread::scope(|scope| {
scope
Expand All @@ -1748,10 +1757,12 @@ pub fn counted(n: u32, mut count: impl FnMut(u32)) -> std::future::Ready<Result<
/// Each line to `keep` on another thread, returning how many it kept: a lent closure may
/// run on any thread until the call returns.
pub fn filter(lines: Vec<u8>, mut keep: impl FnMut(u8, &str) -> bool + Send) -> u32 {
std::thread::scope(|scope| {
let kept = scope.spawn(move || lines.iter().filter(|&&n| keep(n, &format!("line {n}"))).count());
kept.join().expect("the thread finishes") as u32
})
let kept = move || lines.iter().filter(|&&n| keep(n, &format!("line {n}"))).count() as u32;
// wasm32 has no other thread, so it runs there on the caller's.
#[cfg(target_arch = "wasm32")]
return { kept }();
#[cfg(not(target_arch = "wasm32"))]
std::thread::scope(|scope| scope.spawn(kept).join().expect("the thread finishes"))
}

/// Logs a line once polled, returning whether it was kept: the future holds `log` until it
Expand Down Expand Up @@ -1789,16 +1800,19 @@ impl Logger {
}

/// [`Logger::write`] on another thread, which the call waits on.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_from_thread(&self, line: &str) -> bool {
std::thread::scope(|scope| scope.spawn(|| self.write(line)).join().expect("the thread finishes"))
}
}

#[cfg(not(target_arch = "wasm32"))]
/// A thread logging a line to a foreign implementation, which [`LogThread::join`] waits on.
pub struct LogThread {
thread: std::thread::JoinHandle<bool>,
}

#[cfg(not(target_arch = "wasm32"))]
impl LogThread {
pub fn new(log: Box<dyn Log>, line: String) -> Self {
Self {
Expand All @@ -1812,6 +1826,7 @@ impl LogThread {
}
}

#[cfg(not(target_arch = "wasm32"))]
/// A future that never finishes, whose drop logs a line to `log` on another thread it
/// waits on.
pub fn log_on_drop(log: Box<dyn Log>) -> impl Future<Output = ()> + use<> {
Expand All @@ -1822,13 +1837,16 @@ pub fn log_on_drop(log: Box<dyn Log>) -> impl Future<Output = ()> + use<> {
}
}

#[cfg(not(target_arch = "wasm32"))]
/// A waker whose wake and drop each log a line to `log` on another thread they wait on.
pub fn log_waker(log: Box<dyn Log>) -> Waker {
Waker::from(Arc::new(LogWake(log)))
}

#[cfg(not(target_arch = "wasm32"))]
struct LogWake(Box<dyn Log>);

#[cfg(not(target_arch = "wasm32"))]
impl std::task::Wake for LogWake {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
Expand All @@ -1839,14 +1857,17 @@ impl std::task::Wake for LogWake {
}
}

#[cfg(not(target_arch = "wasm32"))]
impl Drop for LogWake {
fn drop(&mut self) {
on_thread(&*self.0, &[0]);
}
}

#[cfg(not(target_arch = "wasm32"))]
struct LogOnDrop(Box<dyn Log>);

#[cfg(not(target_arch = "wasm32"))]
impl Drop for LogOnDrop {
fn drop(&mut self) {
on_thread(&*self.0, &[0]);
Expand Down Expand Up @@ -3017,16 +3038,18 @@ pub fn file(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
dir.join(name)
}

/// A path whose bytes are not UTF-8, as a Unix path may be.
#[cfg(unix)]
/// A path whose bytes are not UTF-8, as a Unix or WASI path may be.
#[cfg(any(unix, target_os = "wasi"))]
pub fn stray() -> std::path::PathBuf {
std::path::PathBuf::from(<std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(vec![
0xff,
]))
#[cfg(unix)]
use std::os::unix::ffi::OsStringExt;
#[cfg(target_os = "wasi")]
use std::os::wasi::ffi::OsStringExt;
std::path::PathBuf::from(std::ffi::OsString::from_vec(vec![0xff]))
}

/// Lends [`stray`]'s path to `visit`.
#[cfg(unix)]
#[cfg(any(unix, target_os = "wasi"))]
pub fn visit_stray(visit: impl Fn(&std::path::Path)) {
visit(&stray());
}
Expand Down Expand Up @@ -3847,6 +3870,39 @@ pub fn pointer_bits(platform: Platform) -> u32 {
}
}

/// A variant whose field is named as a binding's tag naming the variant.
#[derive(Debug, PartialEq)]
pub enum Labelled {
Tagged { tag: u32 },
Bare,
}

/// `labelled`, as it came.
pub fn same_labelled(labelled: Labelled) -> Labelled {
labelled
}

/// A core of a native target's CPU: a record wasm32 lacks.
#[cfg(not(target_arch = "wasm32"))]
pub struct Core {
pub id: u32,
}

/// Where work runs, with a variant only native targets have holding a record only they
/// have, which wasm32's binding reads no field of.
pub enum Placement {
/// Wherever the target runs it.
Anywhere,
/// On one core of a native target.
#[cfg(not(target_arch = "wasm32"))]
Pinned(Core),
}

/// Where the library's target runs work.
pub fn placement() -> Placement {
Placement::Anywhere
}

/// The family of the library's target, a plain enum with a variant only wasm32 has.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Family {
Expand Down
Loading