Wado

WEP: Extern Handles — Resources the Collector Reclaims (externref)

Context

The web bindings are built on one handle type: a DOM object the program may copy freely. It is a resource declared linearity = "unrestricted" (Resource Inheritance). Today it crosses the component boundary as an f64 holding a class and an index into a table the host keeps.

A handle is never released

The table keeps every object the program has received, for the life of the instance. Every Event a dispatch creates stays, and so does every element created and then removed. The callback registry does the same for every closure the program registers.

Releasing by hand is not a way out. A DOM program holds handles in structs, lists and closures, copies them, and upcasts them. An owner for each one is what the affine discipline asks, and Resource Inheritance already found that a handle hierarchy cannot meet it.

Only a reference lets the collector do it

Wasm GC has no finalizers. When the guest drops a number, or a GC struct holding one, nothing runs, so the host never learns that the number is dead. That rules out every scheme that keeps the handle a number:

A Wasm externref is a reference the engine's collector traces through both heaps. A handle that is one needs no table and no release.

The Component Model has no reference type

This is why the handle is a number today. A component value is never a reference, own and borrow are the only handle types, and a host is reachable only through canon lower. Compatibility with the Component Model and WASI is no longer a constraint on the web bindings, so the handle may leave the canonical ABI.

What was measured

A hand-written component was run on wasmtime 50.0.1 under wado's own engine configuration, and after a jco 1.30.0 transpile on Node 26 (V8) and Bun 1.4.4 (JavaScriptCore, Safari's engine), against jsdom. The two JavaScript engines agreed on every row. Its main core module imports functions that take and return externref. Inside the component a second core module satisfies those imports with functions that trap. The component is not in the tree: the roadmap's collection test takes its place.

Check wasmtime jco, Node and Bun
The component validates and instantiates passes passes
A call to a web import the host does not replace traps passes —
A guest GC struct is a handle: extern.convert_any, ref.test, ref.eq passes passes
The host replaces the trapping module's functions with its own — passes
A host object crosses as an externref, in both directions — passes
The host calls a core export the component does not lift — passes
That export runs during an import call, and calls a canon lowered sync import — passes
It does the same from the event loop, outside any export call — passes
Handles the guest dropped are collected — passes
A handle held in a guest global survives, and is collected once cleared — passes
A detached element and a closure that hold each other are collected — passes
A guest GC struct keys a JavaScript WeakMap — passes

One fact decides how == lowers. On both engines no host value passes ref.test eqref once internalized: not a DOM object, a plain object, a function or a string. A guest struct does. The specification says the same of every engine. The JS API turns a JavaScript object that is not an exported Wasm object into ref.host (ToWebAssemblyValue), and the core specification types that as ref any, so ref.eq never accepts one.

The host replaces the functions through jco's instantiation mode, which hands the embedder each core module and its imports before instantiating it.

The handle table and wait were run on a core module alone, with no component around it, on the same two engines:

Check V8 JavaScriptCore
A list of 1000 handles crosses both ways through an exported table passes passes
Cleared slots keep nothing alive: every element is collected passes passes
A list copied into a guest GC array survives, and dies with the array passes passes
Two promises in flight are waited on in the other order passes passes
The instance is re-entered while a wait is suspended passes passes
Entering through WebAssembly.promising, relative to an empty call 42 7

Decision

repr = "externref" declares an extern handle

A resource states its representation beside its linearity:

#[cm("wado-lang:web/node", linearity = "unrestricted", repr = "externref", classes = "1..=4")]
resource Node extends EventTarget { ... }

A resource so declared is an extern handle. The two fields are two axes. linearity says whether a handle may be copied, which the compiler enforces. repr says what the handle is in Wasm, which decides how it crosses a boundary. Its value is the Wasm type's own name. Everything below follows from repr, and nothing from linearity.

An extern handle is an externref

An extern handle is one Wasm value, (ref extern). Every type in an extends tree is that one value, so an upcast and an inherited method's receiver stay no-ops. Option<R> of an extern handle type R is (ref null extern), with None as the null reference: the niche every Option of a reference takes.

The handle is no longer a number. as converts a handle only to a resource it extends, and nothing converts one to or from f64.

A handle is either the host's object or backed by a value of the guest (below). The program cannot tell which, and no rule below depends on which host is running.

The web imports leave the canonical ABI

An import whose signature holds an extern handle is a core function import of the main module. Its flat signature is the canonical ABI's, with two differences: a handle is one externref, and a closure is one externref (below). A string or a list of scalars still crosses as a pointer and a length in linear memory, and a result that does not fit in one value still returns through a pointer. The host reads the memory and calls cabi_realloc through the core instance, as the canonical ABI's lowering did for it before.

These imports are not component imports. The emitted WIT does not list them.

A handle in memory is a slot in the handle table

Linear memory cannot hold a reference, and the canonical ABI puts a value there in three cases: a list's elements, parameters past 16 flat values, and a result past one. A handle in any of them is written as an i32, the index of a slot in a table the guest keeps. A handle inside a record or a variant that stays flat is that index too, so one type has one flat form.

List<Node> therefore crosses both ways with no host call per element, and so does a record with a handle in it, alone or in a list. No shape is left without a form, and the flat limits stay the canonical ABI's.

Returning a handle beside other values as several Wasm results was the alternative for results. It needs the limits lifted for these imports alone, and it leaves a list of handles unanswered.

One component runs on every host

The component satisfies the web imports itself, from a core module the compiler synthesizes whose every function is unreachable. The result is a valid component with no web import at the component level.

One artifact serves both, so the program a server renders is the one the browser runs.

A guest value backs a handle

A handler such as SurfaceDom answers web calls in Wado, so it must make handles. Every extern handle type has two functions for it:

let node: Node = HtmlInputElement::backed_by(input);
let back = node.backing::<SurfaceInput>();   // Option<&mut SurfaceInput>

A backed handle is a GC struct holding the class and the value, converted with extern.convert_any. A node of SurfaceDom is then collected like any other value.

The handle holds the value, and nothing else names it. backed_by takes it as any argument is taken, so a variable the caller keeps is another value. Taken by reference instead, the handle and the variable named one place. A write through the handle then changed a value the compiler held to be unwritten, unless every caller remembered to pass &mut.

backing gives &mut T under &self, and from a handle no mut names. That is the rule every resource follows: it names an object, so &R promises nothing about the object. The marker Resource states which types those are.

Each call of backed_by makes a handle equal to no other, so a handler makes one handle for one object, with the class of what the object is. A Node and an HtmlInputElement of one node are then one handle, upcast or narrowed, as two views of one host object are.

A node of SurfaceDom lives in its handle, and its parent, children and siblings are handles too. SurfaceDom itself holds the document and the window, and no list of nodes. The tree alone keeps a node alive, so a node that is detached and that the program dropped is collected, as a browser's is. A listener is kept by the node it was added to, and goes with it.

The backing type is bound by RefMut: a struct, a tuple, a list, a string or a 128-bit integer, which a reference reaches in place. A reference to any other value is a cell holding a copy, and backing has only a reference to hand back. A cell carries neither the value's identity nor its type: the cells of two extern handle types are one struct, and so are those of two function types, so backing::<Element>() would answer a handle a Node backs.

Any code may call either function. A backed handle that reaches a real host is no object of that host's, and the host rejects it as it would any wrong value.

The two functions are the trait Backing, implemented once for every type the compiler states ExternHandle of. A bound R: ExternHandle therefore offers both.

Narrowing asks for the class once

The class numbering of Resource Inheritance stays: each resource declares classes = "lo..=hi", and a narrowing is a range test on a class. What changes is where the class comes from.

A match with any number of type-pattern arms reads the class once. Narrowing the host's object costs one call where it cost none. One import per target type was the alternative: it needs no numbering, but a match then calls once per arm.

The slice will grow to the whole web platform, well past a thousand classes, so the cost of class-of must not grow with the slice. The glue keeps a map from each declared interface's prototype to its class, and walks the object's prototype chain until the map answers. The walk is as long as the object's inheritance chain. It finds the nearest declared ancestor of an object whose own interface the slice leaves out, as the instanceof scan of today's glue does.

Both were run over jsdom objects with the slice padded to 1507 classes, the real ones last in the scan's order:

class-of by Relative time, V8 Relative time, JavaScriptCore
instanceof scan, deepest first 773 1884
Prototype chain into a map 1 1

They agreed on every object tried, an HTMLDivElement and a Text outside the slice included.

Inspect reads the class the same way and writes the name of the resource that owns it. There is no index to write beside it.

== is identity

Two handles are equal when they are one object. The guest decides in this order:

  1. Two null references are equal, and a null differs from anything else. This is None == None for an Option<R>, and it calls no import.
  2. Two backed handles are equal when ref.eq holds of their backing values, which one backed_by call gives to one handle.
  3. Two handles neither of which is backed are the host's objects. The guest calls the import same, which answers JavaScript's ===.
  4. A backed handle and one that is not differ.

A handle is backed exactly when it passes ref.test for the backing struct's type, which no host object does. Under a handler every handle is backed, so same is never called where only a trap would answer it.

A closure crosses as itself

A closure parameter of a web import crosses as an externref of the closure's own GC struct. The registry in core:rt and its u32 keys go away.

A member returning a Promise<T> returns an AsyncCall

A WebIDL member that returns Promise<T> is declared as any async operation is, async fn … -> AsyncCall<Result<T, Rejection>>. The program meets no new type:

let call = window.fetch("/api");   // AsyncCall<Result<Response, Rejection>>
let response = call.wait()?;       // blocks until the promise settles

An AsyncCall then holds one of two things: the Component Model subtask it has always held, or an extern handle to a JavaScript promise.

A real Component Model async import was the alternative, and it would need no second kind of call. It was run under jco 1.30.0 with a listener that waits on a wasi:clocks timer:

The page calls the listener through The listener's wait Its body starts during the dispatch
A synchronously lifted export, as today fails: the stack cannot suspend yes
The same export under jco's asyncExports works, two at once included no
The core export, with no lift fails: no task is current yes

A wait on a subtask needs a Component Model task, and jco starts a task's body after the dispatch has returned. A listener that starts late cannot prevent_default or stop_propagation, whether it waits or not. The promise keeps the body inside the dispatch, at the cost of a second kind of call.

The late start is jco's, not the Component Model's. canon_lift resumes the new task's thread before it returns to the caller, so the body runs up to its first block inside the call. It defers the start only under backpressure, which includes a call that arrives while another task of the instance holds its one stack: a listener the program itself fires with dispatch_event.

Every callback may wait

A stack can be suspended only when JavaScript entered it through WebAssembly.promising. The glue enters every callback that way, so wait works in a listener as it does in run.

A listener that waits returns to the page at its first wait and resumes later. What it does after that comes too late for the event: prevent_default after a wait has no effect, as in a JavaScript async listener.

Whether a closure can reach wait is a static property of that closure, so the entry stays free to differ per closure without a change to any program.

A reference to a handle is a cell

An externref holds no place to write, so &Node and &mut Node point at a cell holding the handle, as a reference to a scalar or a variant does. A &mut to a field or an element holding a handle is the replace-on-assign error those types give, and a &mut argument is stored back after the call where the callee replaced the handle. A &self method on a handle therefore allocates a cell wherever its call is not inlined.

A handle is not hashable

A handle implements no Hash and no Ord, so it keys no map.

Roadmap

Each step lands with SurfaceDom's tests passing. The jsdom run fails from the representation step until the loader step, since an externref does not pass through the canonical ABI the present glue is called through. Closures come before the glue: a listener is how the jsdom run reaches the program, so the glue cannot be run without them.

Known gaps

Supersedes

Until the roadmap lands, those sections describe what is built.