Wado

Components

A Wado program compiles to a Component Model component. This chapter says how Wado values cross a component boundary, how a component waits, and how Wado declarations link to Component Model definitions and resources. Which world a component targets, and what its entry point is, is in Worlds and Entry Points.

Type Mapping at Component Boundaries

A Wado value that crosses a component boundary is lowered to a Component Model value, and lifted back on the other side, by the Canonical ABI.

The table below is the Wado↔CM correspondence, read in both directions: Wado→CM when generating a component's exported interface, and CM→Wado when importing an external component (use { Iface } from "./c.wasm" with { type: "wasm" }, see Wasm Module and Component Imports). CM types are written in their WIT spelling.

Wado Type CM Type at Boundary Notes
bool bool Boolean value
char char Unicode scalar value
i8, i16, i32, i64 s8, s16, s32, s64 Signed integers
u8, u16, u32, u64 u8, u16, u32, u64 Unsigned integers
i128, u128 record { low, high } Prelude structs, so each crosses as its own record
f32, f64 f32, f64 Floating point
String string UTF-8 string
List<T> list<T> Dynamic array; a WASI binding names list<u8> as ByteList
HashMap<K, V> map<K, V> K is bool, char, String, or an integer; a repeated key takes the last pair's value
[T1, T2, ...] tuple<T1, T2, ...> Tuple types
Option<T> option<T> Optional value
Result<T, E> result<T, E> Result type; result<ok> and bare result are the payload-elided forms
struct { ... } record { ... } Record
enum { ... } enum { ... } Enumeration without payloads
variant { ... } variant { ... } Variant/sum type with payloads
flags { ... } flags { ... } Bit flags
type T = U type t = U Newtype, as a named alias of its base; a stdlib one too (ByteList is byte-list)
resource resource Resource handle; owned and borrowed handles both map here
Stream<T> stream<T> Component Model async stream
Future<T> future<T> Component Model async future

A function type has no row: it crosses only as a callback.

These types have no Component Model type, so they do not cross a component boundary:

A reference and a view both point into storage they do not own; pass an owned value such as a List<T> or a String instead.

A signature that names one of them, anywhere within it, is a compile error at that parameter, or at the function's declaration for its result. This holds for every export fn, not only a world's entry point, because each one lands on the component's surface, and for every imported operation, but for the &ListView<T> of a list argument.

An anonymous struct never crosses either: no signature can name one yet (Anonymous Structs).

Rationale: WEP: Half-Precision Primitives.

List Arguments

A synchronous import takes a list<T> parameter, for T a number type (u8…u64, s8…s64, f32, f64), as a &ListView<T> from core:linear: a component's world function and an operation of an interface or a resource alike. The reference crosses as the list<T> it views. An argument converts to it from any ListArg<T> (List View Arguments), so a &LinearArray<T> lends its own block, which the callee reads in place. A handler serving such an operation reads the view it is handed.

An asynchronous import takes the List<T>, since the host reads its arguments after it returns.

Rationale: WEP: Linear Arrays.

Published Types

An export fn puts every named type its signature reaches, through fields and payloads too, into the package's Component Model interface. The package publishes each one, in one of two ways:

An adopted type takes the name the export use gives it: export use { FileType as Kind } from "core:fs"; publishes variant kind, and every reference to the type in the interface says kind, a field of another adopted type included. A package publishes a type under one name, so adopting it under another name than an earlier export use, or than its own where it is declared export, is a compile error.

A reached type the package does not publish is a compile error at the parameter, or at the function's declaration for its result. Two kinds of type need no publishing: a #[cm] type, whose own interface publishes it, and a standard library newtype such as ByteList, which crosses as the alias it is.

A WIT record shows every field, so each field of a published struct is pub. A field that is not is a compile error, at the field for an export struct and at the export use for an adopted one.

Callbacks

A function type crosses the Component Model boundary in one place: as a parameter of a #[cm] import, where it is a callback. Anywhere else it is a compile error: in an export fn's parameters or result, in an import's result, and inside a type that crosses, as a field or a payload (Option<fn(..)> included).

#[cm("example:demo/target", linearity = "unrestricted", repr = "externref")]
resource Target {
    #[cm("example:demo/target#listen")]
    #[cm_params("self", "listener")]
    fn listen(&self, listener: fn mut(i32));
}

test {
    let target = mock_target();
    let mut seen: List<i32> = [];
    with Target => &mut EchoTarget {} do {
        target.listen(|v| seen.push(v));
    }
    assert seen == [7];                 // `EchoTarget` calls the listener with 7
}

Rationale: WEP: The Web Interface for Wado.

Concurrency Model

Wado follows the Component Model's concurrency model. It has no await: a wait blocks the current task until the value is ready, so a function that waits is not itself async.

Async Imports

A Component Model async func import is an interface operation declared async fn op(...) -> AsyncCall<T> (Async Operations). Calling it starts the call and returns an AsyncCall<T> at once. The caller decides when to wait:

A function or closure that starts an async call also holds the effects these methods declare, so it may later wait on that call without declaring them. A closure is a body of its own: a call it starts grants nothing to the function around it. A function handed a call declares what waiting on it performs, as for any resource it is handed (Resources as Effects).

use { Client, Request, Response, ErrorCode } from "wasi:http";

fn fetch(req: Request) -> Result<Response, ErrorCode> with Client {
    let call = Client::send(req);   // the request starts; nothing waits yet
    // ... work here runs while the host handles the request ...
    return call.wait();             // blocks until the response arrives
}

test {
    let mut mock = MockClient {};
    let fetched = with Client => &mut mock do { fetch(mock.new_request()) matches { Ok(_) } };
    assert fetched;
    mock.end_writes();
}

An AsyncCall<T> is affine: wait and cancel take it by value, and assigning one moves it (Affine Types). A call that drops unawaited is cancelled, and its result buffer freed.

with Fetch => &Canned {} do {
    let call = Fetch::get("/abc");
    let moved = call;
    assert call.wait() == 4;   // error: `call` moved to `moved`
    println(`${moved.wait()}`);
}

Waiting on Several

A WaitableSet<W> owns what it waits on. insert moves a member in, and wait blocks until one is ready, then moves that member back out in a Ready<W> beside the event. A call is ready once it resolved: an event that only moves it from Starting to Started keeps it waiting. poll asks without blocking. The event is a ReadyEvent: Call with the CallState a call resolved in, Copied with the CopyResult a started stream or future copy ended on, or Unreported for a member that neither has a handle for the host to report nor an event of its own. A member whose event is already known enters ready with that event, whether the host reported it to another set or the call or copy settled as it started. A set that drops drops its remaining members first. drain instead moves every member out, the ready ones first, so a race keeps its losers.

A member is any type implementing Waitable, whose wait_on answers either the handle the host reports the member by or the event it is ready with. The trait is sealed: the standard library implements it on the calls and on the started copies (ReadCopy, WriteCopy, FutureReadCopy), since a hand-written wait_on could name a handle its value does not own. A bare stream or future end is no member: no copy on it is in flight, so the host has no event to report for it. A set waiting on two kinds takes a variant over them, which derives the trait with the marker impl Waitable for V;. Each case holds one member, or none for one that is ready without the host:

affine variant Timer {
    Short(AsyncCall<()>),
    Long(AsyncCall<()>),
}

impl Waitable for Timer;

fn first_ready() -> String with MonotonicClock {
    let mut set = WaitableSet::<Timer>::new();
    set.insert(Timer::Long(MonotonicClock::wait_for(60_000_000_000)));
    set.insert(Timer::Short(MonotonicClock::wait_for(0)));
    let ready = set.wait();
    let name = match ready.member {
        Short(call) => {
            call.wait();
            "short"
        },
        Long(call) => {
            call.wait();
            "long"
        },
    };
    return `${name} first, ${set.len()} left`;
}

export fn run() with (Stdout, MonotonicClock) {
    assert first_ready() == "short first, 1 left";
    println("set dropped");
}

The host reports a call's resolution once, but a call a set handed back after its resolution still ends as any call does. wait returns its result, cancel and a drop end it, and a set it enters again reports it at once with the same event.

Handling an Async Operation

A handler method for an async operation is a plain fn that returns T, and it resumes with a T. The caller still receives an AsyncCall<T>, one that has already completed, so its .wait() returns the value at once.

impl Client for MockClient {
    fn send(&mut self, request: Request) -> Result<Response, ErrorCode> {
        resume Result::<Response, ErrorCode>::Ok(self.canned_response());
    }
}

test {
    let mut mock = MockClient {};
    with Client => &mut mock do {
        let call = Client::send(mock.new_request());
        assert call.wait() matches { Ok(_) };   // completed already
    };
    mock.end_writes();
}

Rationale: WEP: Generic AsyncCall<T>.

Async Exports

An export async fn uses the Component Model async calling convention. Its body delivers the result with task return and may keep running afterwards, for example to write a response's trailers.

Streams and Futures

Stream<T> and Future<T> are unbuffered channels. A write settles once the other end reads, and a read once the other end writes. A task that waits on one end before it starts the copy on the other blocks forever, so it either starts both copies before waiting, or hands one end to another task: an async import's subtask, or the caller of an export async fn.

A future's ends are each used once, so both consume their end: Future::read(self) and FutureWritable::write(self, value). A second read or write is a use after move. A FutureWritable dropped before its write traps with a message naming it, since the reader would otherwise wait forever.

A stream copy is started and finished in two steps, so a task can wait on several at once. Stream::start_read(self, max) returns a ReadCopy<T> and StreamWritable::start_write(self, data) a WriteCopy<T>. Each moves the end into the copy, since the Component Model traps on a second copy on an end that is copying. finish waits where the copy has not settled, and hands back the end with what the copy moved. Both copies are Waitable, and a set reports a settled one as ReadyEvent::Copied. Dropping a copy that has not settled cancels it. read_to_end, read_to_end_bytes, write_all and write_raw_all borrow the end and copy until the stream ends.

A future read starts the same way. Future::start_read(self) moves the end into a FutureReadCopy<T>, which a set waits on as it waits on a stream copy. finish waits where the read has not settled and returns the value, or None where the writer dropped without writing. Dropping a read that has not settled cancels it, and dropping one that read a value drops the value.

A write hands back what it did not deliver: the part of the value a reader dropped before taking, or the suffix of a stream write the reader did not take. FutureWritable::write returns a FutureWrite<T> { rest: Option<T>, result }, and WriteCopy::finish a StreamWrite<T> { rest: List<T>, result }. A caller that ignores the result drops the rest.

A handler for Stream<T> or StreamWritable<T> answers the operations a copy starts with, begin_read and begin_write. It returns a copy that has already settled, built by StartedRead::settled or StartedWrite::settled, or one it started on another end, so every copy a program makes goes through it, a started one included. A copy dropped in flight is cancelled by cancel_read or cancel_write on the end the program holds. A handler that started the copy on another end answers that operation by cancelling there.

begin_read also takes a ReadInto: where a host copy lands, in memory the copy allocates or in memory core:* lends it. A handler that settles the copy ignores it, and one that starts the copy on another end passes it on.

A future write's result is a FutureWriteResult. It is Pending where the write returned before its reader read: the host then holds the value and hands it to the reader, so nothing comes back in rest.

Linking and Resources

Attribute Syntax for Component Model Linking

#[cm(...)] links a Wado definition to the Component Model definition it stands for:

// Link an effect interface to a CM interface
#[cm("example:cli/console@0.1.0")]
pub interface Console {
    #[cm("example:cli/console@0.1.0#write-via-stream")]
    fn write_via_stream(data: Stream<u8>) -> Future<Result<(), ErrorCode>>;
}

// Link a resource to a CM resource
#[cm("example:cli/terminal-output@0.1.0#terminal-output")]
pub resource TerminalOutput;

// Link an enum to a CM enum, and each case to its WIT case
#[cm("example:cli/types@0.1.0#error-code")]
pub enum ErrorCode {
    #[cm("io")]
    Io,
    #[cm("illegal-byte-sequence")]
    IllegalByteSequence,
    #[cm("pipe")]
    Pipe,
}

test {
    assert ErrorCode::IllegalByteSequence != ErrorCode::Pipe;   // the CM name changes no Wado name
}

A type declared in an interface (Effect Definition) takes its CM name from that interface: the interface's name with the type's name in kebab case, so Geo::Point in a:x/geo@0.1.0 is a:x/geo@0.1.0#point. A #[cm("…#name")] on a module-level type is an error, so that form names only an operation.

Not yet implemented: a type is not yet declared inside an interface, so TerminalOutput and ErrorCode above sit at module level and name their interface through #[cm] (WEP).

#[cm_params("name", ...)] on an operation gives the CM-side names of its parameters. Without it, each parameter's CM name is its Wado name in kebab-case.

#[cm("name")] on a field, a case or a flag of a #[cm(...)] type gives the member's CM name. Without it, the member's CM name is its Wado name in kebab-case.

Resource Linearity

A #[cm(...)] resource may declare what may be done with its handle: linearity = "affine" or linearity = "unrestricted". Omitting the field reads as "affine", and a resource without #[cm(...)] is affine: linearity is a field of #[cm(...)], so nothing declares one copyable.

repr = "externref" declares how the handle is represented: one reference to a host object, which the collector reclaims. Nothing runs when such a handle dies, so it requires linearity = "unrestricted". An unrestricted resource has no representation of its own, so it requires repr = "externref" in turn.

An affine resource is move-only and carries a drop obligation (see Affine Types). An unrestricted one owns nothing, so it is an ordinary copyable value. Assigning or passing one leaves the original usable, and nothing is dropped at the end of a scope.

A resource names an object rather than holding a value. A copy of an unrestricted one, or a reference to either kind, names the same object, and an operation may change that object through &self. So &R to a resource promises nothing about the object, and no mut is needed to change it.

Every resource type implements Resource, a sealed marker the compiler states. An affine resource implements AffineResource too and an extern handle ExternHandle, and a bound on either implies Resource.

fn is_one<affine R: Resource>(_r: &R) -> bool {
    return true;
}

fn through_extern<R: ExternHandle>(r: &R) -> bool {
    return is_one(r);
}

fn through_affine<affine R: AffineResource>(r: &R) -> bool {
    return is_one(r);
}

test "an extern handle and an affine resource are each a resource" {
    let node = Node::backed_by("node");
    assert is_one(&node);
    assert through_extern(&node);
    let [rx, _tx] = Stream::<u8>::new();
    assert is_one(&rx);
    assert through_affine(&rx);
}

An affine resource crosses the Component Model boundary as an own / borrow handle. A resource declared repr = "externref" is an extern handle, which Extern Handles describes. as upcasts an extern handle to a resource it extends. No other cast accepts one, so an affine resource and an extern handle never convert into each other, and neither converts to a number.

An extern resource is not a Component Model resource. Its operations are plain functions that take the handle as an ordinary parameter, so a #[cm(...)] name written in the [constructor]T, [method]T.m or [static]T.m form is an error on one. classes = "..." (see Resource Inheritance) is accepted only beside repr = "externref".

Backed Handles

A handle of any resource is either an object of the host or backed by a value of the guest. Every resource type implements Backing:

The value's type is one a reference reaches in place, which the bound T: RefMut states: a struct, a tuple, a list, a string or a 128-bit integer. A scalar, a variant, a closure, a reference or an extern handle backs no handle.

A backed handle is how a guest answers an import itself, as a handler in a test does. It is no object of the host's: where an affine one is handed to a host call, the call traps before the host sees it, and a real host rejects a backed extern handle. Its drop is in Resources as Effects.

A resource declared without #[cm(...)], on itself or on any operation, has no host implementation, and a guest value backs every handle of it. It has no WIT name, so it does not cross a component boundary: one in the signature of an export fn is an error. It takes no part in extends, which requires extern handles on both sides (Resource Inheritance).

Extern Handles

An extern handle is one Wasm externref. It is either an object of the host, or backed by a value of the guest (Backed Handles). Option<R> of an extern handle type R is the same reference, nullable. Every extern handle type implements ExternHandle, a marker the compiler states.

struct Tag {
    name: String,
    uses: i32,
}

test {
    let tag = Tag { name: "div", uses: 0 };
    let node: Node = Element::backed_by(tag);    // an upcast keeps the backing
    let Some(back) = node.backing::<Tag>() else {
        panic("a Tag backs the handle");
    };
    back.uses += 1;                              // `&mut`, through a handle no `mut` names
    assert node.backing::<Tag>() matches { Some(t) && t.uses == 1 };
    assert tag.uses == 0;                        // the handle holds its own value
    assert node.backing::<String>() matches { null };
    let copy = node;
    assert copy == node;                         // a copy is the same handle
    assert node != Element::backed_by(tag);      // each call makes another
}

An import whose signature names an extern handle is a web import. The handle may stand anywhere a value does: as a parameter or a result, in an Option, a list, a record or a variant. A web import is not part of the component's world, and an extern handle in the signature of an export fn is an error: a reference to a host object does not cross a component boundary.

A host that serves no web imports still runs the component. There, a call of one that no handler answers traps.

An async web import returns an AsyncCall<T> as any async import does. The host answers the call with a promise, and wait suspends until it settles. cancel, and dropping the call, stop the waiting and nothing else: the work behind a promise goes on. Such a call cannot join a WaitableSet, and inserting one traps.

An extern handle is a scalar where a reference is concerned. A &Node is a reference to a place holding the handle, as a &i32 is to a place holding a number, and a &mut to a field or element holding one is the same error.

Resource Ownership

An affine resource follows Affine Types. A resource's fn drop(self) is its Drop impl, and an imported resource's ends the handle through the Component Model's resource.drop. Lowering a resource to the host as an own, as an argument, a result or what a stream or future write carries, moves it: the host owns the handle from then on.

Handles at the Boundary

Wado position CM handle
By-value R parameter or result own<R>
&R or &mut R parameter, &self or &mut self borrow<R>
Bare self receiver own<R>, transferring the receiver

Rationale: WEP: Resource Ownership.

Resource Inheritance

resource Child extends Parent declares that a child handle is usable wherever the parent is. The clause stands between the resource's name and its body, and names one resource as the parent. Both resources must declare repr = "externref", because an upcast copies the handle and an affine one may not be copied. Single inheritance only, and a cycle is an error.

#[cm("example:ui/target", linearity = "unrestricted", repr = "externref", classes = "0..=1")]
resource Target {
    #[cm("example:ui/target#add-listener")]
    fn add_listener(&self, kind: String);
}

#[cm("example:ui/widget", linearity = "unrestricted", repr = "externref", classes = "1..=1")]
resource Widget extends Target {
    #[cm("example:ui/widget#label")]
    fn label(&self) -> Option<String>;
}

fn use_it(w: Widget) with Target {
    w.add_listener("click");   // inherited, no cast; Target declares it
    let t: Target = w;         // upcast is implicit
}

test {
    let w = Widget::backed_by("button");
    let t: Target = w;
    assert t == w && t matches { _: Widget };
}

A generic resource takes no part in extends, on either side.

Subtyping

extends induces Child <: Parent. The relation is reflexive and transitive, and resources extends does not relate are incomparable.

let r: Option<HtmlInputElement> = Option::Some(input);
let n: Option<Node> = r;                    // ERROR: Option is invariant
let r: Option<HtmlInputElement> = Option::Some(input);
let n: Option<Node> = r.map(|el| el as Node);  // OK: each element is upcast
assert n matches { Some(_: HtmlInputElement) };

Methods

A method call resolves statically. recv.m() gathers every m declared along recv's extends chain and every m of a trait impl that applies to it. None is an error, and one resolves the call, upcasting the receiver to the resource that declares it. Two or more is ambiguous: write Declaring::method(&value) or Trait::method(&value) to pick one.

Constants

A resource holds the associated constants of every resource it extends: Child::NAME names the constant a resource along the extends chain declares as NAME, in an expression and in a pattern alike. A child may not declare a constant under a name it inherits. A constant in a trait impl belongs to that impl and is not inherited.

Handle Classes

Every extern handle of an extends tree carries a class, a 16-bit number naming its runtime type. A backed handle carries the class of the resource backed_by was called on. An object of the host carries the class of the nearest ancestor of its runtime type that the program declares, so a type the program does not name reads as its nearest named ancestor.

classes = "lo..=hi" on the #[cm(...)] numbers the classes of an extends tree. A resource's own class is lo, and the resources extending it hold the rest of the range:

A type pattern narrowing to T tests whether the handle's class lies in T's range. A type pattern narrows only to a resource that declares classes.

Traits on Handles

Rationale: WEP: Resource Inheritance and Narrowing.