# Text Format / AST Explainer This explainer walks through the text format of the Component Model which extends the Core WebAssembly text format (WAT). ## Gated Features By default, the features described in this explainer (as well as the supporting [Binary.md](Binary.md), [WIT.md](WIT.md) and [CanonicalABI.md](CanonicalABI.md)) have been implemented and are included in the [WASI] 0.2 Developer Preview release. All additions since 0.2 are explicitly marked with Unicode symbols ("emoji-gated") to indicate which specific text- and binary-format productions or semantic rules were added. The following features have already shipped as part of a subsequent [WASI] Developer Preview release, as recorded in the [top-level readme](../../README.md), and thus are not open to breaking changes before the final 1.0 release: * πŸ”€: native concurrency support with `async`, `stream` and `future` * πŸ—ΊοΈ: the `map` type * 🏷️: `implements` and `external-id` annotations for imports/exports All other features are in various stages of implementation, are not enabled by default, may have breaking changes, and, after a suitable [WASI] SG vote, may be shipped as part of a future WASI Developer Preview release: * πŸͺ™: value imports/exports and component-level start function * πŸͺΊ: nested namespaces and packages in import/export names * 🚝: enabling more canonical ABI options on more async-related builtins * 🚟: using `async` with `canon lift` without `callback` (stackful lift) * 🧡: threading built-ins * πŸ§΅β‘‘: [shared-everything-threads]-based threading built-ins * πŸ”§: fixed-length lists * πŸ“: the `error-context` type * πŸ”—: canonical interface names * 🐘: [memory64] * πŸ“‘: getters and setters * ➑️: `stream.forward` and `future.forward` built-ins ## Grammar This section defines components using an EBNF grammar that parses something in between a pure Abstract Syntax Tree (like the Core WebAssembly spec's [Structure Section]) and a complete text format (like the Core WebAssembly spec's [Text Format Section]). The goal is to balance completeness with succinctness, with just enough detail to write examples and define a [binary format](Binary.md) in the style of the [Binary Format Section], deferring full precision to the [formal specification](../../spec/). Additionally, standard [abbreviations] defined by the Core WebAssembly text format (e.g., inline export definitions) are assumed but not explicitly defined below. ### Index Spaces As with Core WebAssembly, the Component Model appends each definition to an [index space], allowing earlier definitions to be referred to by later definitions in the text and binary format via unsigned integer index. There are 5 component-level index spaces (components, component instances, functions, types and values πŸͺ™), 6 core index spaces already in the Core WebAssembly specification (functions, tables, memories, globals, tags and types) and 2 additional core index spaces (modules and module instances) that are not in the Core WebAssembly specification at the moment, but, with [module-linking], could be in the future. These 13 index spaces correspond 1:1 with the terminals of `sort` shown below and so "sort" and "index space" can be used interchangeably. The grammar rule for `sort` prefixes the Core WebAssembly sorts with `core` to disambiguate current and future overlaps. ```ebnf core:sort ::= func | table | memory | global | tag | type | module | instance componentsort ::= component | instance | func | type | value πŸͺ™ sort ::= componentsort | core ``` As with Core WebAssembly, for each index space `X`, there is an `{X}idx` grammar rule that parses indices as either a direct `u32` or a [`core:id`] that is resolved to a `u32` according to the usual Core WebAssembly text format rules. When the text format accepts indices in one of several different index spaces, the sort is required to be written explicitly using the `externidx` rule, which embeds an expanded version of [`core:externidx`] prefixed with `core`. ```ebnf idx ::= | core:{Xα΅’}sortidx ::= (Xα΅’ ) (for Xα΅’ ∈ ) core:{Xα΅’}idx ::= | (for Xα΅’ ∈ ) core:externidx ::= | ... | (for X₁,…,Xβ‚™ ∈ ) {Xα΅’}sortidx ::= (Xα΅’ ) (for Xα΅’ ∈ ) {Xα΅’}idx ::= | <{Xα΅’}sortidx> (for Xα΅’ ∈ ) externidx ::= <{X₁}sortidx> | ... | <{Xβ‚™}sortidx> (for X₁,…,Xβ‚™ ∈ ) | core-prefix() where core-prefix() is defined: if parses (), then core-prefix() parses (core ) if parses , then core-prefix() parses ``` The -`sortidx` schemas generate rules like `funcsortidx` and `core:funcsortidx` which both parse `(func $foo)` and `(func 0)`. The -`idx` schemas generate rules like `funcidx`/`core:funcidx` that extend `funcsortidx`/`core:funcsortidx` to also parse plain identifiers (like `$foo`) and `u32` indices (like `0`). The `core-prefix` meta-function is used here and below to transform a rule for parsing a parenthesized definition without `core` into the same definition but with a `core` token right after the leftmost parenthesis. For example, since `` parses `(func $f)`, `core-prefix()` parses `(core func $f)`. This allows `` rules (which don't include a `core` token) to be used inside `(core ...)` expressions and `core-prefix()` rules to be used outside `(core ...)` expressions (at component-level) to explicitly mark where a `core` token might be required. The exception in `core-prefix` for `` means that, for example, `core-prefix()` accepts both `(core func $foo)` and plain `$foo`. ### Component Definitions At the top-level, a `component` is a sequence of definitions of various kinds: ```ebnf component ::= (component ? *) definition ::= core-prefix() | core-prefix() | core-prefix() | | | | | | πŸͺ™ | | | πŸͺ™ ``` As suggested by this grammar, unlike in Core WebAssembly modules, component `definition`s can be in any order and a single kind of `definition` can appear multiple times, interleaved with other kinds of `definition`s. Moreover, the order of `definition`s in the text format is significant and, unlike Core WebAssembly, `definition`s are not reordered and grouped by the text format. Furthermore, component `definition`s are strictly *acyclic*, such that a given `definition` (in the text or binary format) can only refer to identifiers or indices introduced by preceding definitions. Based on this, while the following two core modules are both valid and equivalent (with the first being "desugared" into the second): ```wat (module (import "" "f" (func (type $FT))) (type $FT (func)) ) (module (type (func)) (import "" "f" (func (type 0))) ) ``` only the latter component is valid: ```wat ;;(component ;; (import "f" (func (type $FT))) ❌ $FT not defined ;; (type $FT (func)) ;;) (component (type $FT (func)) (import "f" (func (type $FT))) ) ``` As defined in the previous section, `core-prefix()` adds a `core` token after the leftmost parenthesis of `` and so, e.g., `core-prefix()` parses `(core module ...)` instead of `(module ...)`. The `core` prefix disambiguates current and future overlaps between core- and component-level definitions (like `func`, `instance` and `type`). The [`core:module`] production is unmodified by the Component Model and thus components embed Core WebAssembly (text and binary format) modules as currently standardized, allowing reuse of an unmodified Core WebAssembly implementation. The next production, `core:instance`, is not currently included in Core WebAssembly, but would be if Core WebAssembly adopted the [module-linking] proposal. This new core definition is introduced below, alongside its component-level counterpart. Finally, the existing [`core:type`] production is extended below to add core module types as proposed for module-linking. Thus, the overall idea is to represent core definitions (in the AST, binary and text format) as-if they had already been added to Core WebAssembly so that, if they eventually are, the implementation of decoding and validation can be shared in a layered fashion. The next kind of definition is, recursively, a component itself. Thus, components form trees with all other kinds of definitions only appearing at the leaves. For example, with what's defined so far, we can write the following component: ```wat (component (component (core module (func (export "one") (result i32) (i32.const 1))) (core module (func (export "two") (result f32) (f32.const 2))) ) (core module (func (export "three") (result i64) (i64.const 3))) (component (component (core module (func (export "four") (result f64) (f64.const 4))) ) ) (component) ) ``` This top-level component roots a tree with 4 modules and 1 component as leaves. However, in the absence of any `instance` definitions (introduced next), nothing will be instantiated or executed at runtime; everything here is dead code. ### Instance Definitions Whereas modules and components represent immutable *code*, instances associate code with potentially-mutable *state* (e.g., linear memory) and thus are necessary to create before being able to *run* the code. Instance definitions create module or component instances by selecting a module or component to **instantiate** and then supplying a set of named *arguments* which satisfy all the named *imports* of the selected module or component. This low-level instantiation mechanism allows the Component Model to simultaneously support multiple different styles of traditional [linking](Linking.md). The syntax for defining a core module instance is: ```ebnf core:instance ::= (instance ? ) core:instanceexpr ::= (instantiate *) | * core:instantiatearg ::= (with (instance )) | (with (instance *)) core:inlineexport ::= (export ) ``` where [`core:name`] is the WebAssembly text format's quoted string literal. When instantiating a module via `instantiate`, the two-level imports of the core modules are resolved as follows: 1. The first import name is looked up in the named list of `core:instantiatearg` to select a core module instance. (In the future, other `core:sort`s could be allowed if core wasm adds single-level imports.) 2. The second import name is looked up in the named list of exports of the core module instance found by the first step to select the imported core definition. Based on this, we can link two core modules `$A` and `$B` together with the following component: ```wat (component (core module $A (func (export "one") (result i32) (i32.const 1)) ) (core module $B (func (import "a" "one") (result i32)) ) (core instance $a (instantiate $A)) (core instance $b (instantiate $B (with "a" (instance $a)))) ) ``` To see examples of other sorts, we'll need `alias` definitions, which are introduced in the next section. The `*` form of `core:instanceexpr` allows module instances to be created by directly tupling together preceding definitions, without the need to `instantiate` a helper module. The `*` form of `core:instantiatearg` is syntactic sugar that is expanded during text format parsing into an out-of-line instance definition referenced by `with`. To show an example of these, we'll also need the `alias` definitions introduced in the next section. The syntax for defining component instances is symmetric to core module instances above: ```ebnf instance ::= (instance ? ) instanceexpr ::= (instantiate *) | * instantiatearg ::= (with ) | (with (instance *)) name ::= inlineexport ::= (export ) | (export ) πŸ”— ``` Components may import and export various core definitions when they are compatible with the [shared-nothing] model, which currently means only `module` (since modules are pure immutable code) but may in the future include, e.g., `data` (since data segments are pure immutable data). Component-level `name` literals reuse the Core WebAssembly text format's [`core:name`] quoted-string-literal syntax which includes literals such as `"a"`, `"β˜ƒοΈŽ"`, `"\7f"` and `"\u{7fff}"`. To see a non-trivial example of component instantiation, we'll first need to introduce a few other definitions below that allow components to import, define and export component functions. ### Alias Definitions Alias definitions project definitions out of other components' index spaces and into the current component's index spaces. As represented in the AST below, there are three kinds of "targets" for an alias: the `export` of a component instance, the `core export` of a core module instance and a definition of an `outer` component (containing the current component): ```ebnf alias ::= (alias export ( ?)) | (alias core export (core-prefix() ?)) | (alias outer ( ?)) outeraliassort ::= core module | core type | component | type ``` An `alias` definition adds a new index into the index space of the declared sort, binding the optional `?`, if present, to the new index. In the case of `export` aliases, validation requires `` to select an instance in the instance index space and `name` must match an export in the type of that instance. For example, the following export alias allows `$P` to extract the `foo` function of its child component `$C` and re-export it directly from `$P`: ```wat (component $P (component $C ... (export "foo" (func $foo-impl)) ) (instance $c (instantiate $C)) (alias export $c "foo" (func $foo-alias)) (export "foo" (func $foo-alias)) ) ``` Additional syntactic sugar is added for allowing export aliases to be defined *inline* as a syntactic generalization of the `{X}sortidx` grammar rules defined [above](#index-spaces) for each core- and component-level sort `X`: ```ebnf core:{Xα΅’}sortidx ::= ... | (Xα΅’ +) (for Xα΅’ ∈ ) {Xα΅’}sortidx ::= ... | (Xα΅’ +) (for Xα΅’ ∈ ) ``` Each `` projects an export of an instance: the first `` projects from `` (which must select an instance) and each subsequent `` projects from the (instance) result of the preceding alias. Because the `{X}sortidx` rules are included in all the core- and component-level `{X}idx` and `externidx` rules defined [above](#index-spaces), an inline export alias `(X $id "name1" "name2" ...)` can be used anywhere that a normal `(X $id)` can be used, and with the same `core`-prefixing rules. For example, the following example is equivalent to the previous example, avoiding the need to explicitly define `$foo-alias`: ```wat (component $P (component $C ... (export "foo" (func $foo-impl)) ) (instance $c (instantiate $C)) (export "foo" (func $c "foo")) ) ``` In the case of `outer` aliases, the `` pair serves as a [de Bruijn index], with the first `` being the number of enclosing `component`s or `type`s to skip and the second `` being an index into the target's `outeraliassort`'s index space. In particular, the first `` can be `0`, in which case the outer alias refers to the current `component`/`type`. To maintain the acyclicity of module instantiation, outer aliases are only allowed to refer to *preceding* outer definitions. `outer` aliases are currently restricted to only refer to the 4 `outeraliassort`s, as opposed to the full set of `sort`s, but this may be relaxed in the future if needed. To ensure that nested components can be arbitrarily "unbundled" (transforming inline definitions into `import`s of out-of-line definitions), `outer` aliases that cross component boundaries must only refer to definitions that can be substituted inline, if needed. `outer` aliases can also refer to `import` definitions, in which case unbundling would replace the `alias` definition with a copy of the `import`. Of the available `outeraliassort`s: `core module`, `core type` and `component` definitions are *always* substitutable. However, due to the *generativity* of `resource` types (discussed in the next section), `type` definitions that transitively refer to a `resource` type may *not* be `outer`-aliased and are thus rejected by validation. For example, in the following component, `$T2` and `$T3` cannot be `outer`- aliased by `$E`: ```wat (component $C (component $D) (import "I" (component $I)) (type $T1 (record (field "x" u32) (field "y" u32))) (type $T2 (resource (rep i32))) (type $T3 (borrow $T2)) (import "f" (func $f)) (alias outer $C $D (component $D')) (alias outer $C $I (component $I')) (alias outer $C $T1 (type $T1')) (alias outer $C $T2 (type $T2')) (alias outer $C $T3 (type $T3')) ;; (alias outer $C $f (func $f)) ❌ 'func' not in 'outeraliassort' (component $E (alias outer $C $D (component $D)) (alias outer $C $I (component $I)) (alias outer $C $T1 (type $T1)) ;; (alias outer $C $T2 (type $T2)) ❌ resource type ;; (alias outer $C $T3 (type $T3)) ❌ refers to resource type ;; (alias outer $C $f (func $f)) ❌ 'func' not in 'outeraliassort' ) ) ``` For `outer` aliases, there is also inline syntactic sugar, which is simply to use the identifier of the outer definition, resolved using normal lexical scoping rules. For example, the following component: ```wat (component (component $C ...) (component (instance (instantiate $C)) ) ) ``` is desugared into: ```wat (component $Parent (component $C ...) (component (alias outer $Parent $C (component $Parent_C)) (instance (instantiate $Parent_C)) ) ) ``` Lastly, for symmetry with [imports][func-import-abbrev], aliases can be written in an inverted form that puts the sort first: ```wat (func $f (import "i" "f") ...type...) ≑ (import "i" "f" (func $f ...type...)) (WebAssembly 1.0) (func $f (alias export $i "f")) ≑ (alias export $i "f" (func $f)) (core module $m (alias export $i "m")) ≑ (alias export $i "m" (core module $m)) (core func $f (alias core export $i "f")) ≑ (alias core export $i "f" (core func $f)) ``` With what's defined so far, we're able to link modules with arbitrary renamings: ```wat (component (core module $A (func (export "one") (result i32) (i32.const 1)) (func (export "two") (result i32) (i32.const 2)) (func (export "three") (result i32) (i32.const 3)) ) (core module $B (func (import "a" "one") (result i32)) ) (core instance $a (instantiate $A)) (core instance $b1 (instantiate $B (with "a" (instance $a)) ;; no renaming )) (core func $a_two (alias core export $a "two")) ;; ≑ (alias core export $a "two" (core func $a_two)) (core instance $b2 (instantiate $B (with "a" (instance (export "one" (func $a_two)) ;; renaming, using out-of-line alias )) )) (core instance $b3 (instantiate $B (with "a" (instance (export "one" (func $a "three")) ;; renaming, using inline alias sugar )) )) ) ``` To show analogous examples of linking components, we'll need component-level type and function definitions which are introduced in the next two sections. ### Type Definitions The syntax for defining core types extends the existing core type definition syntax, adding a `module` type constructor: ```ebnf core:rectype ::= ... from the Core WebAssembly spec core:typedef ::= ... from the Core WebAssembly spec core:subtype ::= ... from the Core WebAssembly spec core:comptype ::= ... from the Core WebAssembly spec | core:moduletype ::= (module *) core:moduledecl ::= | | | core:alias ::= (alias outer (type ?)) core:importdecl ::= (import ) core:exportdecl ::= (export strip-id()) where strip-id(X) parses '(' sort Y ')' when X parses '(' sort ? Y ')' ``` Here, `core:comptype` (short for "composite type") as defined in the [GC] proposal is extended with a `module` type constructor. The GC proposal also adds recursion and explicit subtyping between core wasm types. Owing to their different requirements and intended modes of usage, module types support implicit subtyping and are not recursive. Thus, the existing core validation rules would require the declared supertypes of module types to be empty and disallow recursive use of module types. In the MVP, validation will also reject `core:moduletype` defining or aliasing other `core:moduletype`s, since, before module-linking, core modules cannot themselves import or export other core modules. The body of a module type contains an ordered list of "module declarators" which describe, at a type level, the imports and exports of the module. In a module-type context, import and export declarators can both reuse the existing [`core:externtype`] production defined by the Core WebAssembly spec, with the only difference being that, in the text format, imports can bind an identifier for later reuse while exports cannot. With the Core WebAssembly [type-imports], module types will need the ability to define the types of exports based on the types of imports. In preparation for this, module types start with an empty type index space that is populated by `type` declarators, so that, in the future, these `type` declarators can refer to type imports local to the module type itself. For example, in the future, the following module type would be expressible: ```wat (component $C (core type $M (module (import "" "T" (type $T)) (type $PairT (struct (field (ref $T)) (field (ref $T)))) (export "make_pair" (func (param (ref $T)) (result (ref $PairT)))) )) ) ``` In this example, `$M` has a distinct type index space from `$C`, where element 0 is the imported type, element 1 is the `struct` type, and element 2 is an implicitly-created `func` type referring to both. Lastly, the `core:alias` module declarator allows a module type definition to reuse (rather than redefine) `type` definitions in the enclosing component's `core type` index space via `outer` alias. In the future, more kinds and sorts of aliases may be useful and added. As an example, the following component defines two semantically-equivalent module types, where the former defines the function type via `type` declarator and the latter refers via `alias` declarator. ```wat (component $C (core type $C1 (module (type (func (param i32) (result i32))) (import "a" "b" (func (type 0))) (export "c" (func (type 0))) )) (core type $F (func (param i32) (result i32))) (core type $C2 (module (alias outer $C $F (type)) (import "a" "b" (func (type 0))) (export "c" (func (type 0))) )) ) ``` Component-level type definitions are symmetric to core-level type definitions, but use a completely different set of value types. Unlike [`core:valtype`] which is low-level and assumes a shared linear memory for communicating compound values, component-level value types assume no shared memory and must therefore be high-level, describing entire compound values. ```ebnf type ::= (type ? ) deftype ::= | | | | defvaltype ::= bool | s8 | u8 | s16 | u16 | s32 | u32 | s64 | u64 | f32 | f64 | char | string | error-context πŸ“ | (record (field )+) | (variant (case ?)+) | (list ) | (list ) πŸ”§ | (tuple +) | (flags +) | (enum +) | (option ) | (result ? (error )?) | (map ) πŸ—ΊοΈ | (own ) | (borrow ) | (stream ?) πŸ”€ | (future ?) πŸ”€ valtype ::= | keytype ::= bool | s8 | u8 | s16 | u16 | s32 | u32 | s64 | u64 | char | string πŸ—ΊοΈ resourcetype ::= (resource (rep i32) (dtor core-prefix())?) | (resource (rep i64) (dtor core-prefix())?) 🐘 functype ::= (func async? (param )* (result )?) componenttype ::= (component *) instancetype ::= (instance *) componentdecl ::= | instancedecl ::= core-prefix() | | | importdecl ::= (import bind-id()) exportdecl ::= (export bind-id()) externtype ::= ( (type ) ) | core-prefix() | | | | (value ) πŸͺ™ | (type ) typebound ::= (eq ) | (sub resource) valuebound ::= (eq ) πŸͺ™ | πŸͺ™ where bind-id(X) parses '(' sort ? Y ')' when X parses '(' sort Y ')' ``` Because there is nothing in this type grammar analogous to the [gc] proposal's [`rectype`], none of these types are recursive. To prevent integer overflow in obscure corner cases, as an extra validation requirement, `defvaltype`s may not be equal or greater than 228 bytes when serialized into linear memory according to the `i64` ABI definition of [Element Size](CanonicalABI.md#element-size). #### Fundamental value types The value types in `valtype` can be broken into two categories: *fundamental* value types and *specialized* value types, where the latter are defined by expansion into the former. The *fundamental value types* have the following sets of abstract values: | Type | Values | | ------------------------- | ------ | | `bool` | `true` and `false` | | `s8`, `s16`, `s32`, `s64` | integers in the range [-2N-1, 2N-1-1] | | `u8`, `u16`, `u32`, `u64` | integers in the range [0, 2N-1] | | `f32`, `f64` | [IEEE754] floating-point numbers, with a single NaN value | | `char` | [Unicode Scalar Values] | | `error-context` πŸ“ | an immutable, nondeterministic, host-defined value meant to aid in debugging | | `record` | heterogeneous [tuples] of named values | | `variant` | heterogeneous [tagged unions] of named values | | `list` | homogeneous, variable- or fixed-length [sequences] of values | | `own` | a unique, opaque address of a resource that will be destroyed when this value is dropped | | `borrow` | an opaque address of a resource that must be dropped before the current export call returns | | `stream` πŸ”€ | an asynchronously-passed list of homogeneous values | | `future` πŸ”€ | an asynchronously-passed single value | How these abstract values are produced and consumed from Core WebAssembly values and linear memory is configured by the component via *canonical lifting and lowering definitions*, which are introduced [below](#canonical-definitions). For example, while abstract `variant`s contain a list of `case`s labelled by name, canonical lifting and lowering map each case to an `i32` value starting at `0`. ##### Numeric types While core numeric types are defined in terms of sets of bit-patterns and operations that interpret the bits in various ways, component-level numeric types are defined in terms of sets of values. This allows the values to be translated between source languages and protocols that use different value representations. Core integer types are just bit-patterns that don't distinguish between signed and unsigned, while component-level integer types are sets of integers that either include negative values or don't. Core floating-point types have many distinct NaN bit-patterns, while component-level floating-point types have only a single NaN value. And boolean values in core wasm are usually represented as `i32`s where operations interpret all-zeros as `false`, while at the component-level there is a `bool` type with `true` and `false` values. ##### πŸ“ Error Context type Values of `error-context` type are immutable, nondeterministic, host-defined and meant to be propagated from failure sources to callers in order to aid in debugging. Currently `error-context` values contain only a "debug message" string whose contents are determined by the host. Core wasm can create `error-context` values given a debug string, but the host is free to arbitrarily transform (discard, preserve, prefix or suffix) this wasm-provided string. In the future, `error-context` could be enhanced with other additional or more-structured context (like a backtrace or a chain of originating error contexts). The intention of this highly-nondeterministic semantics is to provide hosts the full range of flexibility to: * append a basic callstack suitable for forensic debugging in production; * optimize for performance in high-volume production scenarios by slicing or discarding debug messages; * optimize for developer experience in debugging scenarios when debug metadata is present by appending expensive-to-produce symbolicated callstacks. A consequence of this, however, is that components *must not* depend on the contents of `error-context` values for behavioral correctness. In particular, case analysis of the contents of an `error-context` should not determine *error recovery*; explicit `result` or `variant` types must be used in the function return type instead (e.g., `(func (result (tuple (stream u8) (future $my-error)))`). ##### Container types The `record`, `variant`, and `list` types allow for grouping, categorizing, and sequencing contained values. πŸ”§ When the optional `` immediate of the `list` type constructor is present, the list has a fixed length and the representation of the list in memory is specialized to this length. Note that the fixed length must be larger than 0. ##### Handle types The `own` and `borrow` value types are both *handle types*. Handles logically contain the opaque address of a resource and avoid copying the resource when passed across component boundaries. By way of metaphor to operating systems, handles are analogous to file descriptors, which are stored in a table and may only be used indirectly by untrusted user-mode processes via their integer index in the table. In the Component Model, handles are lifted-from and lowered-into `i32` values that index an encapsulated per-component-instance table that is maintained by the canonical function definitions described [below](#canonical-definitions). In the future, handles could be backwards-compatibly lifted and lowered from [reference types] (via the addition of a new `canonopt`, as introduced [below](#canonical-abi)). The uniqueness and dropping conditions mentioned above are enforced at runtime by the Component Model through these canonical definitions. The `typeidx` immediate of a handle type must refer to a `resource` type (described below) that statically classifies the particular kinds of resources the handle can point to. ##### Asynchronous value types The `stream` and `future` value types are both *asynchronous value types* that are used to deliver values incrementally over the course of a single async function call, instead of copying the values all-at-once as with other (synchronous) value types like `list`. The mechanism for performing these incremental copies avoids the need for intermediate buffering inside the `stream` or `future` value itself and instead uses buffers of memory whose size and allocation is controlled by the core wasm in the source and destination components. Thus, in the abstract, `stream` and `future` can be thought of as inter-component control-flow or synchronization mechanisms. Just like with handles, in the Component Model, async value types are lifted-from and lowered-into `i32` values that index an encapsulated per-component-instance table that is maintained by the canonical ABI built-ins [below](#canonical-definitions). The Component-Model-defined ABI for creating, writing-to and reading-from `stream` and `future` values is meant to be bound to analogous source-language features like promises, futures, streams, iterators, generators and channels so that developers can use these familiar high-level concepts when working directly with component types, without the need to manually write low-level async glue code. For languages like C without language-level concurrency support, these ABIs (described in detail in the [Canonical ABI explainer]) can be exposed directly as function imports and used like normal low-level Operation System I/O APIs. A `stream` asynchronously passes zero or more `T` values in one direction between a source and destination, batched in chunks for efficiency. Streams are useful for: * improving latency by incrementally processing values as they arrive; * delivering potentially-large lists of values that might OOM wasm if passed as a `list`; * long-running or infinite streams of events. A `future` asynchronously delivers exactly one `T` value from a source to a destination, unless the destination signals that it doesn't want the `T` value any more. When function types contain the [`async`][summary] effect, the return value is returned asynchronously if the call blocks (and is returned synchronously otherwise) and thus there is no need to *additionally* return a `future` value unless *additional* asynchronous signalling is required. The `T` element type of `stream` and `future` is an optional `valtype`. As with variant-case payloads and function results, when `T` is absent, the "value(s)" being asynchronously passed can be thought of as [unit] values. In such cases, there is no representation of the value in Core WebAssembly (pointers into linear memory are ignored) however the *timing* of completed reads and writes and the number of elements they contain are observable and meaningful. Thus, empty futures and streams can be useful for timing-related APIs. Currently, validation rejects `(stream T)` and `(future T)` when `T` transitively contains a `borrow`. This restriction could be relaxed in the future by extending the call-scoping rules of `borrow` to streams and futures. Additionally, `(stream char)` is temporarily rejected with a future [TODO](Concurrency.md) to allow and properly use the `string-encoding`, taking care to not split code points. #### Specialized value types The sets of values allowed for the remaining *specialized value types* are defined by the following mapping: ``` (tuple *) ↦ (record (field "π’Š" )*) for π’Š=0,1,... (flags *) ↦ (record (field bool)*) (enum +) ↦ (variant (case )+) (option ) ↦ (variant (case "none") (case "some" )) (result ? (error )?) ↦ (variant (case "ok" ?) (case "error" ?)) string ↦ (list char) (map ) ↦ (list (tuple )) ``` Specialized value types have the same set of semantic values as their corresponding despecialized types, but have distinct type constructors (which are not type-equal to the unspecialized type constructors) and thus have distinct binary encodings. This allows specialized value types to convey a more specific intent. For example, `result` isn't just a variant, it's a variant that *means* success or failure, so source-code bindings can expose it via idiomatic source-language error reporting. Additionally, this can sometimes allow values to be represented differently. For example, `string` in the Canonical ABI uses various Unicode encodings while `list` uses a sequence of 4-byte `char` code points. Similarly, `flags` in the Canonical ABI uses a bit-vector while an equivalent record of boolean fields uses a sequence of boolean-valued bytes. Since a `map` is a specialization of a list of (key, value) pairs without any additional semantic guarantee of key uniqueness or ordering, the Component Model does not prevent duplicate keys from appearing in the list. Bindings generators *may* deduplicate and reorder keys as long as the *last* (key, value) pair in the original list defines the final value of the key. However, bindings generators are not *required* to deduplicate keys and may instead simply present the original list to guest code. To simplify bindings generation, `` is a conservative subset of ``, but this subset could be expanded over time based on use cases. Similarly, validation currently rejects `(map K V)` when `V` transitively contains an `own`, `borrow`, `future`, `stream` or `error-context`, since dropping the value of a duplicate key would otherwise require bindings generators to correctly dispose of the contained handles. This restriction could be relaxed in the future. Note that, at least initially, variants must have a non-empty list of cases. This could be relaxed in the future to allow an empty list of cases, with the empty `(variant)` effectively serving as an [empty type] and indicating unreachability. #### Definition types The remaining 4 type constructors in `deftype` use `valtype` to describe shared-nothing functions, resources, components, and component instances: The `func` type constructor describes a component-level function definition that takes a list of `valtype` parameters with [strongly-unique] names and optionally returns a `valtype`. The optional `async` effect type indicates that calling the function may block (because the function transitively calls a blocking built-in like `waitable-set.wait` or blocks on an imported `async` function). The `resource` type constructor creates a fresh type for each instance of the containing component (with "freshness" and its interaction with general type-checking described in more detail [below](#type-checking)). Resource types can be referred to by handle types (such as `own` and `borrow`) as well as the canonical built-ins described [below](#canonical-built-ins). The `rep` immediate of a `resource` type specifies its *core representation type*, which is currently fixed to `i32` or `i64`, but will potentially be relaxed to include other types. When the last handle to a resource is dropped, the resource's destructor function specified by the `dtor` immediate will be called (if present), allowing the implementing component to perform clean-up like freeing linear memory allocations. A destructor for a `resource (rep $T)` must have type `($T) -> ()`. The `instance` type constructor describes a list of named, typed definitions that can be imported or exported by a component. Informally, instance types correspond to the usual concept of an "interface" and instance types thus serve as static interface descriptions. In addition to the S-Expression text format defined here, which is meant to go inside component definitions, interfaces can also be defined as standalone, human-friendly text files in the [`wit`](WIT.md) [Interface Definition Language]. The `component` type constructor is symmetric to the core `module` type constructor and contains *two* lists of named definitions for the imports and exports of a component, respectively. As suggested above, instance types can show up in *both* the import and export types of a component type. Both `instance` and `component` type constructors are built from a sequence of "declarators", of which there are four kinds—`type`, `alias`, `import` and `export`—where only `component` type constructors can contain `import` declarators. The meanings of these declarators is basically the same as the core module declarators introduced above, but expanded to cover the additional capabilities of the component model. #### Declarators The `importdecl` and `exportdecl` declarators correspond to component `import` and `export` definitions, respectively, allowing an identifier to be bound for use by subsequent declarators. The definitions of `labellit`, `externnamelit` and `attribute` are given in the [imports and exports](#import-and-export-definitions) section below. Following the precedent of [`core:typeuse`], the text format allows both references to out-of-line type definitions (via `(type )`) and inline type expressions that the text format desugars into out-of-line type definitions. πŸͺ™ The `value` case of `externtype` describes a runtime value that is imported or exported at instantiation time as described in the [value definitions](#value-definitions) section below. The `type` case of `externtype` describes an imported or exported type along with its "bound": The `sub` bound declares that the imported/exported type is an *abstract type* which is a *subtype* of some other type. Currently, the only supported bound is `resource` which (following the naming conventions of the [GC] proposal) means "any resource type". Thus, only resource types can be imported/exported abstractly, not arbitrary value types. This allows type imports to always be compiled independently of their arguments using a "universal representation" for handle values (viz., `i32`, as defined by the [Canonical ABI](CanonicalABI.md)). In the future, `sub` may be extended to allow referencing other resource types, thereby allowing abstract resource subtyping. The `eq` bound says that the imported/exported type must be structurally equal to some preceding type definition. This allows: * an imported abstract type to be re-exported; * components to introduce another label for a preceding abstract type (which can be necessary when implementing multiple independent interfaces with the same resource); and * components to attach transparent type aliases to structural types to be reflected in source-level bindings (e.g., `(export "bytes" (type (eq (list u64))))` could generate in C++ a `typedef std::vector bytes` or in JS an exported field named `bytes` that aliases `Uint64Array`. The `alias` declarator reuses the syntax for component-level `alias` definitions so that `export` and `outer` aliases can be used inside `component` and `instance` *types*. For example, `export` aliases are necessary to define the type of a component that uses an imported `resource` type in an exported function parameter type: ```wat (component (type $CT (component (import "fs" (instance $fs (export "file" (type (sub resource))) ;; file methods )) (alias export $fs "file" (type $fileT)) (export "process" (func (param "file" (borrow $fileT)))) )) (import "fs-component" (component (type $CT))) ) ``` Similarly, `outer` aliases are necessary to define an `instance` or `component` type that uses a `resource` type defined or imported by the containing component, since `instance` and `component` types start with empty type index spaces: ```wat (component $C (import "r" (type $R (sub resource))) (type $IT (instance (alias outer $C $R (type $R)) (export "process" (func (param "input" (borrow $R)))) )) (import "uses-r" (instance (type $IT))) ) ``` In terms of validation, `alias` declarators inherit all the previously-mentioned validation rules of `alias` definitions and add the following rules: * `alias export` declarators may only alias the `instance` and `type` sorts * `alias outer` declarators may only alias the `core type` and `type` sorts ```wat (component $C (component $D) (type $T1 (record (field "x" u32) (field "y" u32))) (type $T2 (resource (rep i32))) (type $T3 (borrow $T2)) (type (component ;; (alias outer $C $D (component $D)) ❌ not allowed inside type (alias outer $C $T1 (type $T1)) (alias outer $C $T2 (type $T2)) (alias outer $C $T3 (type $T3)) )) (component (type (component (alias outer $C $T1 (type $T1)) ;; (alias outer $C $T2 (type $T2)) ❌ resource type ;; (alias outer $C $T3 (type $T3)) ❌ refers to resource type )) ) ) ``` The `type` declarator is restricted by validation to disallow `resource` type definitions, thereby preventing "private" resource type definitions from appearing in component types and avoiding the [avoidance problem]. Thus, the only resource types possible in an `instancetype` or `componenttype` are introduced by `importdecl` or `exportdecl`. With what's defined so far, we can define component types using a mix of type definitions: ```wat (component $C (type $T (list (tuple string bool))) (type $U (option $T)) (type $G (func (param "x" (list $T)) (result $U))) (type $D (component (alias outer $C $T (type $C_T)) (type $L (list $C_T)) (import "f" (func (param "x" $L) (result (list u8)))) (import "g" (func (type $G))) (export "g2" (func (type $G))) (export "h" (func (result $U))) (import "T" (type $T (sub resource))) (import "i" (func (param "x" (list (own $T))))) (export "T2" (type $T' (eq $T))) (export "U" (type $U' (sub resource))) (export "j" (func (param "x" (borrow $T')) (result (own $U')))) )) ) ``` Note that the inline use of `$G` and `$U` are syntactic sugar for `outer` aliases. #### Type Checking Like core modules, components have an up-front validation phase in which the definitions of a component are checked for basic consistency. Type checking is a central part of validation and, e.g., occurs when validating that the `with` arguments of an [`instantiate`](#instance-definitions) expression are type-compatible with the `import`s of the component being instantiated. To incrementally describe how type-checking works, we'll start by asking how *type equality* works for non-resource, non-handle, local type definitions and build up from there. Type equality for almost all types (except as described below) is purely *structural*. In a structural setting, types are considered to be Abstract Syntax Trees whose nodes are type constructors with types like `u8` and `string` considered to be "nullary" type constructors that appear at leaves and non-nullary type constructors like `list` and `record` appearing at parent nodes. Then, type equality is defined to be AST equality. Importantly, these type ASTs do *not* contain any type indices or depend on index space layout; these binary format details are consumed by decoding to produce the AST. For example, in the following compound component: ```wat (component $A (type $ListString1 (list string)) (type $ListListString1 (list $ListString1)) (type $ListListString2 (list $ListString1)) (component $B (type $ListString2 (list string)) (type $ListListString3 (list $ListString2)) (type $ListString3 (alias outer $A $ListString1)) (type $ListListString4 (list $ListString3)) (type $ListListString5 (alias outer $A $ListListString1)) ) ) ``` all 5 variations of `$ListListStringX` are considered equal since, after decoding, they all have the same AST. Next, the type equality relation on ASTs is relaxed to a more flexible [subtyping] relation. Currently, subtyping is only relaxed for `module`, `instance` and `component` types, but may be relaxed for more type constructors in the future to better support API Evolution (being careful to understand how subtyping manifests itself in the wide variety of source languages so that subtype-compatible updates don't inadvertently break source-level clients). Module, component and instance subtyping allows a subtype to export more and import less than is declared by the supertype, ignoring the exact order of imports and exports and considering only names. For example, here, `$I1` is a subtype of `$I2`: ```wat (component (type $I1 (instance (export "foo" (func)) (export "bar" (func)) (export "baz" (func)) )) (type $I2 (instance (export "bar" (func)) (export "foo" (func)) )) ) ``` and `$C1` is a subtype of `$C2`: ```wat (component (type $C1 (component (import "a" (func)) (export "x" (func)) (export "y" (func)) )) (type $C2 (component (import "a" (func)) (import "b" (func)) (export "x" (func)) )) ) ``` 🏷️/πŸ”— Note that all `attributes` on `import`s and `export`s are ignored by type checking and so adding, removing or changing any `external-id` attribute on the `func`s above (or any `implements` or `version-suffix` attribute on `instance` imports or exports) does not change the result. When we next consider type imports and exports, there are two distinct subcases of `typebound` to consider: `eq` and `sub`. The `eq` bound adds a type equality rule (extending the built-in set of subtyping rules mentioned above) saying that the imported type is structurally equivalent to the type referenced in the bound. For example, in the component: ```wat (component (type $L1 (list u8)) (import "L2" (type $L2 (eq $L1))) (import "L3" (type $L2 (eq $L1))) (import "L4" (type $L2 (eq $L3))) ) ``` all four `$L*` types are equal (in subtyping terms, they are all subtypes of each other). In contrast, the `sub` bound introduces a new *abstract* type which the rest of the component must conservatively assume can be *any* type that is a subtype of the bound. What this means for type-checking is that each subtype-bound type import/export introduces a *fresh* abstract type that is unequal to every preceding type definition. Currently (and likely in the MVP), the only supported type bound is `resource` (which means "any resource type") and thus the only abstract types are abstract *resource* types. As an example, in the following component: ```wat (component (import "T1" (type $T1 (sub resource))) (import "T2" (type $T2 (sub resource))) ) ``` the types `$T1` and `$T2` are not equal. Once a type is imported, it can be referred to by subsequent equality-bound type imports, thereby adding more types that it is equal to. For example, in the following component: ```wat (component $C (import "T1" (type $T1 (sub resource))) (import "T2" (type $T2 (sub resource))) (import "T3" (type $T3 (eq $T2))) (type $ListT1 (list (own $T1))) (type $ListT2 (list (own $T2))) (type $ListT3 (list (own $T3))) ) ``` the types `$T2` and `$T3` are equal to each other but not to `$T1`. By the above transitive structural equality rules, the types `$List2` and `$List3` are equal to each other but not to `$List1`. Handle types (`own` and `borrow`) are structural types (like `list`) but, since they refer to resource types, transitively "inherit" the freshness of abstract resource types. For example, in the following component: ```wat (component (import "T" (type $T (sub resource))) (import "U" (type $U (sub resource))) (type $Own1 (own $T)) (type $Own2 (own $T)) (type $Own3 (own $U)) (type $ListOwn1 (list $Own1)) (type $ListOwn2 (list $Own2)) (type $ListOwn3 (list $Own3)) (type $Borrow1 (borrow $T)) (type $Borrow2 (borrow $T)) (type $Borrow3 (borrow $U)) (type $ListBorrow1 (list $Borrow1)) (type $ListBorrow2 (list $Borrow2)) (type $ListBorrow3 (list $Borrow3)) ) ``` the types `$Own1` and `$Own2` are equal to each other but not to `$Own3` or any of the `$Borrow*`. Similarly, `$Borrow1` and `$Borrow2` are equal to each other but not `$Borrow3`. Transitively, the types `$ListOwn1` and `$ListOwn2` are equal to each other but not `$ListOwn3` or any of the `$ListBorrow*`. These type-checking rules for type imports mirror the *introduction* rule of [universal types] (βˆ€T). The above examples all show abstract types in terms of *imports*, but the same "freshness" condition applies when aliasing the *exports* of another component as well. For example, in this component: ```wat (component (import "C" (component $C (export "T1" (type (sub resource))) (export "T2" (type $T2 (sub resource))) (export "T3" (type (eq $T2))) )) (instance $c (instantiate $C)) (alias export $c "T1" (type $T1)) (alias export $c "T2" (type $T2)) (alias export $c "T3" (type $T3)) ) ``` the types `$T2` and `$T3` are equal to each other but not to `$T1`. These type-checking rules for aliases of type exports mirror the *elimination* rule of [existential types] (βˆƒT). Next, we consider resource type *definitions* which are a *third* source of abstract types. Unlike the abstract types introduced by type imports and exports, resource type definitions provide canonical built-ins for setting and getting a resource's private representation value (that are introduced [below](#canonical-built-ins)). These built-ins are necessarily scoped to the component instance that generated the resource type, thereby hiding access to a resource type's representation from the outside world. Because each component instantiation generates fresh resource types distinct from all preceding instances of the same component, resource types are "[generative]". For example, in the following example component: ```wat (component (type $R1 (resource (rep i32))) (type $R2 (resource (rep i32))) (func $f1 (result (own $R1)) (canon lift ...)) (func $f2 (param (own $R2)) (canon lift ...)) ) ``` the types `$R1` and `$R2` are unequal and thus the return type of `$f1` is incompatible with the parameter type of `$f2`. The generativity of resource type definitions matches the abstract typing rules of type exports mentioned above, which force all clients of the component to bind a fresh abstract type. For example, in the following component: ```wat (component (component $C (type $r1 (export "r1") (resource (rep i32))) (type $r2 (export "r2") (resource (rep i32))) ) (instance $c1 (instantiate $C)) (instance $c2 (instantiate $C)) (type $c1r1 (alias export $c1 "r1")) (type $c1r2 (alias export $c1 "r2")) (type $c2r1 (alias export $c2 "r1")) (type $c2r2 (alias export $c2 "r2")) ) ``` all four types aliases in the outer component are unequal, reflecting the fact that each instance of `$C` generates two fresh resource types. If a single resource type definition is exported more than once, the exports after the first are equality-bound to the first export. For example, the following component: ```wat (component (type $r (resource (rep i32))) (export "r1" (type $r)) (export "r2" (type $r)) ) ``` is assigned the following `componenttype`: ```wat (component (export "r1" (type $r1 (sub resource))) (export "r2" (type (eq $r1))) ) ``` Thus, from an external perspective, `r1` and `r2` are two labels for the same type. If a component wants to hide this fact and force clients to assume `r1` and `r2` are distinct types (thereby allowing the implementation to actually use separate types in the future without breaking clients), an explicit type can be ascribed to the export that replaces the `eq` bound with a less-precise `sub` bound (using syntax introduced [below](#import-and-export-definitions)). ```wat (component (type $r (resource (rep i32))) (export "r1" (type $r)) (export "r2" (type $r) (type (sub resource))) ) ``` This component is assigned the following `componenttype`: ```wat (component (export "r1" (type (sub resource))) (export "r2" (type (sub resource))) ) ``` The assignment of this type to the above component mirrors the *introduction* rule of [existential types] (βˆƒT). When supplying a resource type (imported *or* defined) to a type import via `instantiate`, type checking performs a substitution, replacing all uses of the `import` in the instantiated component with the actual type supplied via `with`. For example, the following component validates: ```wat (component $P (import "C1" (component $C1 (import "T" (type $T (sub resource))) (export "foo" (func (param (own $T)))) )) (import "C2" (component $C2 (import "T" (type $T (sub resource))) (import "foo" (func (param (own $T)))) )) (type $R (resource (rep i32))) (instance $c1 (instantiate $C1 (with "T" (type $R)))) (alias export $c1 "foo" (func $foo)) (instance $c2 (instantiate $C2 (with "T" (type $R)) (with "foo" (func $foo)))) ) ``` This depends critically on the `T` imports of `$C1` and `$C2` having been replaced by `$R` when validating the instantiations of `$c1` and `$c2`. These type-checking rules for instantiating type imports mirror the *elimination* rule of [universal types] (βˆ€T). Importantly, this type substitution performed by the parent is not visible to the child at validation- or run-time. In particular, there are no runtime casts that can "see through" to the original type parameter, avoiding avoiding the usual [type-exposure problems with dynamic casts][non-parametric parametricity]. In summary: all type constructors are *structural* with the exception of `resource`, which is *abstract* and *generative*. Type imports and exports that have a subtype bound also introduce abstract types and follow the standard introduction and elimination rules of universal and existential types. Lastly, since "nominal" is often taken to mean "the opposite of structural", a valid question is whether any of the above is "nominal typing". Inside a component, resource types act "nominally": each resource type definition produces a new local "name" for a resource type that is distinct from all preceding resource types. The interesting case is when resource type equality is considered from *outside* the component, particularly when a single component is instantiated multiple times. In this case, a single resource type definition that is exported with a single name will get a fresh type with each component instance, with the abstract typing rules mentioned above ensuring that each of the component's instance's resource types are kept distinct. Thus, in a sense, the generativity of resource types *generalizes* traditional name-based nominal typing, providing a finer granularity of isolation than otherwise achievable with a shared global namespace. ### Canonical Definitions From the perspective of Core WebAssembly running inside a component, the Component Model is an [embedder]. As such, the Component Model defines the Core WebAssembly imports passed to [`module_instantiate`] and how Core WebAssembly exports are called via [`func_invoke`]. This allows the Component Model to specify how core modules are linked together (as shown above) but it also allows the Component Model to arbitrarily synthesize Core WebAssembly functions (via [`func_alloc`]) that are imported by Core WebAssembly. These synthetic core functions are created via one of several *canonical definitions* defined below. #### Canonical ABI To implement or call a component-level function, we need to cross a shared-nothing boundary. Traditionally, this problem is solved by defining a serialization format. The Component Model MVP uses roughly this same approach, defining a linear-memory-based [ABI] called the "Canonical ABI" which specifies, for any `functype`, a [corresponding](CanonicalABI.md#flattening) [`core:functype`] and [rules](CanonicalABI.md#lifting-and-lowering) for copying values into and out of linear memory. The Component Model differs from traditional approaches, though, in that the ABI is configurable, allowing multiple different memory representations of the same abstract value. In the MVP, this configurability is limited to the small set of `canonopt` shown below. However, Post-MVP, [adapter functions] could be added to allow far more programmatic control. The Canonical ABI is explicitly applied to "wrap" existing functions in one of two directions: * `lift` wraps a core function (of type `core:functype`) to produce a component function (of type `functype`) that can be passed to other components. * `lower` wraps a component function (of type `functype`) to produce a core function (of type `core:functype`) that can be imported and called from Core WebAssembly code inside the current component. Canonical definitions specify one of these two wrapping directions, the function to wrap and a list of configuration options: ```ebnf canon ::= (canon lift core-prefix() * bind-id()) | (canon lower * (core func ?)) canonopt ::= string-encoding=utf8 | string-encoding=utf16 | string-encoding=latin1+utf16 | (memory core-prefix()) | (realloc core-prefix()) | (post-return core-prefix()) | async πŸ”€ | (callback core-prefix()) πŸ”€ ``` While the production `externtype` accepts any `sort`, the validation rules for `canon lift` would only allow the `func` sort. In the future, other sorts may be added (viz., types), hence the explicit sort. The `string-encoding` option specifies the encoding the Canonical ABI will use for the `string` type. The `latin1+utf16` encoding captures a common string encoding across Java, JavaScript and .NET VMs and allows a dynamic choice between either Latin-1 (which has a fixed 1-byte encoding, but limited Code Point range) or UTF-16 (which can express all Code Points, but uses either 2 or 4 bytes per Code Point). If no `string-encoding` option is specified, the default is `utf8`. It is a validation error to include more than one `string-encoding` option. The `(memory ...)` option specifies the memory that the Canonical ABI will use to load and store values. If the Canonical ABI needs to load or store, validation requires this option to be present (there is no default). The types of lowered functions may also depend on the [`core:memtype`] of this memory, specifically its [`core:addrtype`] (indicated by `memory.addrtype`), if pointers are transitively contained in parameters or results. The `(realloc ...)` option specifies a core function that is validated to have the following core function type: ```wat (func (param $originalPtr memory.addrtype) (param $originalSize memory.addrtype) (param $alignment memory.addrtype) (param $newSize memory.addrtype) (result memory.addrtype)) ``` The Canonical ABI will use `realloc` both to allocate (passing `0` for the first two parameters) and reallocate. If the Canonical ABI needs `realloc`, validation requires this option to be present (there is no default). The `(post-return ...)` option may only be present in `canon lift` when `async` is not present and specifies a core function to be called with the original return values after they have finished being read, allowing memory to be deallocated and destructors called. This immediate is always optional but, if present, is validated to have parameters matching the callee's return type and empty results. πŸ”€ The `async` option may only be used with `async` function types and specifies that the component wants to make (for imports) or support (for exports) multiple concurrent (asynchronous) calls. This option changes the derived Canonical ABI significantly; see the [concurrency explainer] for more details. πŸ”€ The `(callback ...)` option may only be present in `canon lift` when the `async` option has also been set and specifies a core function that is validated to have the following core function type: ```wat (func (param $ctx i32) (param $event i32) (param $payload i32) (result $done i32)) ``` Again, see the [concurrency explainer] for more details. Based on this description of the AST, the [Canonical ABI explainer] gives a detailed walkthrough of the static and dynamic semantics of `lift` and `lower`. One high-level consequence of the dynamic semantics of `canon lift` given in the Canonical ABI explainer is that component functions are different from core functions in that all control flow transfer is explicitly reflected in their type. For example, with Core WebAssembly [exception-handling] and [stack-switching], a core function with type `(func (result i32))` can return an `i32`, throw, suspend or trap. In contrast, a component function with type `(func (result string))` may only return a `string` or trap. To express failure, component functions can return `result` and languages with exception handling can bind exceptions to the `error` case. Similar to the `import` and `alias` abbreviations shown above, `canon` definitions can also be written in an inverted form that puts the sort first: ```wat (func $f (import "i" "f") ...type...) ≑ (import "i" "f" (func $f ...type...)) (WebAssembly 1.0) (func $g ...type... (canon lift ...)) ≑ (canon lift ... (func $g ...type...)) (core func $h (canon lower ...)) ≑ (canon lower ... (core func $h)) ``` For example: ```wat (canon lower (func $f) (realloc (core func $libc "realloc")) (memory (core memory $libc "mem")) (core func $f_lower)) ``` can be equivalently written: ```wat (core func $f_lower (canon lower (func $f) (realloc (core func $libc "realloc")) (memory (core memory $libc "mem")))) ``` As the latter demonstrates, the `core-prefix`ed `canonopt` rules defined above still require a `core` prefix even though they are now lexically nested inside a `(core ...)` expression (which the text format otherwise avoids). Using canonical function definitions, we can finally write a non-trivial component that takes a string, does some logging, then returns a string. ```wat (component (import "logging" (instance $logging (export "log" (func (param string))) )) (import "libc" (core module $Libc (export "mem" (memory 1)) (export "realloc" (func (param i32 i32) (result i32))) )) (core instance $libc (instantiate $Libc)) (core func $log (canon lower (func $logging "log") (memory (core memory $libc "mem")) (realloc (core func $libc "realloc")) )) (core module $Main (import "libc" "memory" (memory 1)) (import "libc" "realloc" (func (param i32 i32) (result i32))) (import "logging" "log" (func $log (param i32 i32))) (func (export "run") (param i32 i32) (result i32) ... (call $log) ... ) ) (core instance $main (instantiate $Main (with "libc" (instance $libc)) (with "logging" (instance (export "log" (func $log)))) )) (func $run (param string) (result string) (canon lift (core func $main "run") (memory (core memory $libc "mem")) (realloc (core func $libc "realloc")) )) (export "run" (func $run)) ) ``` This example shows the pattern of splitting out a reusable language runtime module (`$Libc`) from a component-specific, non-reusable module (`$Main`). In addition to reducing code size and increasing code-sharing in multi-component scenarios, this separation allows `$libc` to be created first, so that its exports are available for reference by `canon lower`. Without this separation (if `$Main` contained the `memory` and allocation functions), there would be a cyclic dependency between `canon lower` and `$Main` that would have to be broken using an auxiliary module performing `call_indirect`. #### Canonical Built-ins In addition to the `lift` and `lower` canonical function definitions which adapt *existing* functions, there are also a set of canonical "built-ins" that define core functions out of nothing that can be imported by core modules to dynamically interact with Canonical ABI entities like resources, [threads, tasks, subtasks, waitable sets, streams and futures](Concurrency.md). ```ebnf canon ::= ... | (canon resource.new (core func ?)) | (canon resource.drop (core func ?)) | (canon resource.rep (core func ?)) | (canon context.get (core func ?)) πŸ”€ | (canon context.set (core func ?)) πŸ”€ | (canon backpressure.inc (core func ?)) πŸ”€ | (canon backpressure.dec (core func ?)) πŸ”€ | (canon task.return (result )? * (core func ?)) πŸ”€ | (canon task.cancel (core func ?)) πŸ”€ | (canon waitable-set.new (core func ?)) πŸ”€ | (canon waitable-set.wait (memory core-prefix()) (core func ?)) πŸ”€ | (canon waitable-set.poll (memory core-prefix()) (core func ?)) πŸ”€ | (canon waitable-set.drop (core func ?)) πŸ”€ | (canon waitable.join (core func ?)) πŸ”€ | (canon subtask.cancel async? (core func ?)) πŸ”€ | (canon subtask.drop (core func ?)) πŸ”€ | (canon stream.new (core func ?)) πŸ”€ | (canon stream.read * (core func ?)) πŸ”€ | (canon stream.write * (core func ?)) πŸ”€ | (canon stream.cancel-read async? (core func ?)) πŸ”€ | (canon stream.cancel-write async? (core func ?)) πŸ”€ | (canon stream.drop-readable (core func ?)) πŸ”€ | (canon stream.drop-writable (core func ?)) πŸ”€ | (canon stream.forward (core func ?)) ➑️ | (canon future.new (core func ?)) πŸ”€ | (canon future.read * (core func ?)) πŸ”€ | (canon future.write * (core func ?)) πŸ”€ | (canon future.cancel-read async? (core func ?)) πŸ”€ | (canon future.cancel-write async? (core func ?)) πŸ”€ | (canon future.drop-readable (core func ?)) πŸ”€ | (canon future.drop-writable (core func ?)) πŸ”€ | (canon future.forward (core func ?)) ➑️ | (canon thread.index (core func ?)) 🧡 | (canon thread.new-indirect core-prefix() core-prefix() (core func ?)) 🧡 | (canon thread.resume-later (core func ?)) 🧡 | (canon thread.suspend (core func ?)) 🧡 | (canon thread.yield (core func ?)) πŸ”€ | (canon thread.suspend-then-resume (core func ?)) 🧡 | (canon thread.yield-then-resume (core func ?)) 🧡 | (canon thread.suspend-then-promote (core func ?)) 🧡 | (canon thread.yield-then-promote (core func ?)) 🧡 | (canon error-context.new * (core func ?)) πŸ“ | (canon error-context.debug-message * (core func ?)) πŸ“ | (canon error-context.drop (core func ?)) πŸ“ | (canon thread.spawn-ref shared? core-prefix() (core func ?)) πŸ§΅β‘‘ | (canon thread.spawn-indirect shared? core-prefix() core-prefix() (core func ?)) πŸ§΅β‘‘ | (canon thread.available-parallelism shared? (core func ?)) πŸ§΅β‘‘ ``` ##### Resource built-ins ###### `resource.new` | Synopsis | | | -------------------------- | -------------------------- | | Approximate WIT signature | `func(rep: T.rep) -> T` | | Canonical ABI signature | `[rep: T.rep] -> [i32]` | The `resource.new` built-in creates a new resource (of resource type `T`) with `rep` as its representation and returns a new owning handle pointing to the new resource. Validation only allows `resource.new T` to be used within the component that defined `T`. In the Canonical ABI, `T.rep` is defined to be the `$rep` in the `(type $T (resource (rep $rep) ...))` type definition that defined `T`. While it's designed to allow different types in the future, it is currently limited to `i32` or `i64`. For details, see [`canon_resource_new`] in the Canonical ABI explainer. ###### `resource.drop` | Synopsis | | | -------------------------- | ---------------------------------- | | Approximate WIT signature | `func(t: T)` | | Canonical ABI signature | `[t:i32] -> []` | The `resource.drop` built-in drops a resource handle `t` (with resource type `T`) and, if the handle was owning, calls the resource's `dtor`, if present. For details, see [`canon_resource_drop`] in the Canonical ABI explainer. ###### `resource.rep` | Synopsis | | | -------------------------- | ------------------------ | | Approximate WIT signature | `func(t: T) -> T.rep` | | Canonical ABI signature | `[t:i32] -> [T.rep]` | The `resource.rep` built-in returns the representation of the resource (with resource type `T`) pointed to by the handle `t`. Validation only allows `resource.rep T` to be used within the component that defined `T`. In the Canonical ABI, `T.rep` is defined to be the `$rep` in the `(type $T (resource (rep $rep) ...))` type definition that defined `T`. While it's designed to allow different types in the future, it is currently limited to `i32` or `i64`. As an example, the following component imports the `resource.new` built-in, allowing it to create and return new resources to its client: ```wat (component (import "Libc" (core module $Libc ...)) (core instance $libc (instantiate $Libc)) (type $R (resource (rep i32) (dtor (core func $libc "free")))) (core func $R_new (param i32) (result i32) (canon resource.new $R) ) (core module $Main (import "canon" "R_new" (func $R_new (param i32) (result i32))) (func (export "make_R") (param ...) (result i32) (return (call $R_new ...)) ) ) (core instance $main (instantiate $Main (with "canon" (instance (export "R_new" (func $R_new)))) )) (export $R' "r" (type $R)) (func (export "make-r") (param ...) (result (own $R')) (canon lift (core func $main "make_R")) ) ) ``` Here, the `i32` returned by `resource.new`, which is an index into the current component instance's table, is immediately returned by `make_R`, thereby transferring ownership of the newly-created resource to the export's caller. For details, see [`canon_resource_rep`] in the Canonical ABI explainer. ##### πŸ”€πŸ§΅ Concurrency built-ins See the [concurrency explainer] for background. ###### πŸ”€ `context.get` | Synopsis | | | -------------------------- | ------------------ | | Approximate WIT signature | `func() -> T` | | Canonical ABI signature | `[] -> [T]` | The `context.get` built-in returns the `i`th element of the [current thread]'s [thread-local storage] array. Validation currently restricts `i` to be `0` (or, with 🧡, less than 2) and `T` to be `i32` (or, with 🐘, `i64`), but these restrictions may be relaxed in the future. Additionally, component-level validation requires that all `context.get` and `context.set` built-ins use the *same* `T`, so that there is no mixing of writes with one type and reads with another. For details, see [Thread-Local Storage] in the concurrency explainer and [`canon_context_get`] in the Canonical ABI explainer. ###### πŸ”€ `context.set` | Synopsis | | | -------------------------- | ----------------- | | Approximate WIT signature | `func(v: T)` | | Canonical ABI signature | `[T] -> []` | The `context.set` built-in sets the `i`th element of the [current thread]'s [thread-local storage] array to the value `v`. Validation currently restricts `i` to be `0` (or, with 🧡, less than 2) and `T` to be `i32` (or, with 🐘, `i64`), but these restrictions may be relaxed in the future. Additionally, component-level validation requires that all `context.get` and `context.set` built-ins use the *same* `T`, so that there is no mixing of writes with one type and reads with another. For details, see [Thread-Local Storage] in the concurrency explainer and [`canon_context_set`] in the Canonical ABI explainer. ###### πŸ”€ `backpressure.inc` and `backpressure.dec` | Synopsis | | | -------------------------- | ---------- | | Approximate WIT signature | `func()` | | Canonical ABI signature | `[] -> []` | The `backpressure.{inc,dec}` built-ins allow code running in a component to prevent new incoming export calls to the component by enabling [backpressure]. These built-ins increment and decrement a per-component-instance counter that, when greater than zero, enables backpressure. If these built-ins would overflow or underflow a 16-bit unsigned integer, they trap instead. As a composable convention, each piece of code that calls `backpressure.inc` must take responsibility for calling `backpressure.dec` exactly once when the source of backpressure subsides. For details, see [Backpressure] in the concurrency explainer and [`canon_backpressure_{inc,dec}`] in the Canonical ABI explainer. ###### πŸ”€ `task.return` | Synopsis | | | -------------------------- | --------------------------------------- | | Approximate WIT signature | `func(results: FuncT.results)` | | Canonical ABI signature | `[lower(FuncT.results)*] -> []` | The `task.return` built-in takes as parameters the result values of the [current task]. At most one call to `task.return` or `task.cancel` may be made from any of a task's threads; if neither is called, the task never resolves. The `canon task.return` definition takes component-level return type and the list of `canonopt` to be used to lift the return value. When called, the declared return type and the `string-encoding` and `memory` `canonopt`s are checked to exactly match those of the current task. For details, see [Returning] in the concurrency explainer and [`canon_task_return`] in the Canonical ABI explainer. ###### πŸ”€ `task.cancel` | Synopsis | | | -------------------------- | ---------- | | Approximate WIT signature | `func()` | | Canonical ABI signature | `[] -> []` | The `task.cancel` built-in indicates that the [current task] is now [resolved] and has dropped all borrowed handles lent to it during the call (trapping if otherwise). `task.cancel` can only be called after a request for cancellation has been [delivered][Cancellation]. Once this request is received, any of the task's threads may call `task.cancel` or `task.return`. For details, see [Cancellation] in the concurrency explainer and [`canon_task_cancel`] in the Canonical ABI explainer. ###### πŸ”€ `waitable-set.new` | Synopsis | | | -------------------------- | ------------------------ | | Approximate WIT signature | `func() -> waitable-set` | | Canonical ABI signature | `[] -> [i32]` | The `waitable-set.new` built-in returns the `i32` index of a new [waitable set]. The `waitable-set` type is not a true WIT-level type but instead serves to document associated built-ins below. Waitable sets start out empty and are populated explicitly with [waitables] by `waitable.join`. For details, see [Waitables and Waitable Sets] in the concurrency explainer and [`canon_waitable_set_new`] in the Canonical ABI explainer. ###### πŸ”€ `waitable-set.wait` | Synopsis | | | -------------------------- | ---------------------------------------------------------- | | Approximate WIT signature | `func(s: waitable-set) -> event` | | Canonical ABI signature | `[s:i32 payload-addr:memory.addrtype] -> [event-code:i32]` | where `event` is defined in WIT as: ```wit variant event { none, subtask(subtask-index, subtask-state), stream-read(stream-index, stream-result), stream-write(stream-index, stream-result), future-read(future-index, future-read-result), future-write(future-index, future-write-result), task-cancelled, } enum subtask-state { starting, started, returned, cancelled-before-started, cancelled-before-returned, } ``` The `waitable-set.wait` built-in suspends the [current thread] in a "pending" state until any one of the [waitables] in the given [waitable set] `s` has an event to deliver. At that point, the thread is in the "ready" state and can be nondeterministically resumed by the runtime's scheduler at which point `waitable-set.wait` will return the `event`. (The `none` `event` is used by `waitable-set.poll` and never returned by `waitable-set.wait`.) Waitable sets may be `wait`ed upon when empty, in which case the caller will necessarily block until another thread adds a waitable to the set. A `subtask` event notifies the supertask that its subtask is now in the given state (the meanings of which are described by the [concurrency explainer]). The meanings of the `{stream,future}-{read,write}` events/payloads are given as part [`stream.read` and `stream.write`](#-streamread-and-streamwrite) and [`future.read` and `future.write`](#-futureread-and-futurewrite) below. Lastly, the `task-cancelled` event is never returned by `waitable-set.wait` or `waitable-set.poll`; it may only be delivered as an event code to an `async` `callback` function to indicate [cancellation]. In the Canonical ABI, the `event-code` return value provides the `event` discriminant and the case payloads are stored as two contiguous `i32`s at the 4-byte-aligned address `payload-addr`, trapping if `payload-addr` is misaligned or out of bounds. For details, see [Waitables and Waitable Sets] in the concurrency explainer and [`canon_waitable_set_wait`] in the Canonical ABI explainer. ###### πŸ”€ `waitable-set.poll` | Synopsis | | | -------------------------- | ---------------------------------------------------------- | | Approximate WIT signature | `func(s: waitable-set) -> event` | | Canonical ABI signature | `[s:i32 payload-addr:memory.addrtype] -> [event-code:i32]` | where `event` is defined as in [`waitable-set.wait`](#-waitable-setwait). The `waitable-set.poll` built-in returns either an event from one of the waitables in `s` or, if there is none, the `none` `event`. The Canonical ABI of `waitable-set.poll` is the same as `waitable-set.wait` (with the `none` case indicated by returning `0`). For details, see [Waitables and Waitable Sets] in the concurrency explainer and [`canon_waitable_set_poll`] in the Canonical ABI explainer. ###### πŸ”€ `waitable-set.drop` | Synopsis | | | -------------------------- | ------------------------ | | Approximate WIT signature | `func(s: waitable-set)` | | Canonical ABI signature | `[s:i32] -> []` | The `waitable-set.drop` built-in removes the indicated [waitable set] from the current component instance's table, trapping if the waitable set is not empty or if another thread is concurrently `wait`ing on it. For details, see [Waitables and Waitable Sets] in the concurrency explainer and [`canon_waitable_set_drop`] in the Canonical ABI explainer. ###### πŸ”€ `waitable.join` | Synopsis | | | -------------------------- | ---------------------------------------------------- | | Approximate WIT signature | `func(w: waitable, maybe_set: option)` | | Canonical ABI signature | `[w:i32, maybe_set:i32] -> []` | The `waitable.join` built-in may be called given a [waitable] and an optional [waitable set]. `join` first removes `w` from any waitable set that it is a member of and then, if `maybe_set` is not `none`, `w` is added to that set. Thus, `join` can be used to arbitrarily add, change and remove waitables from waitable sets in the same component instance, preserving the invariant that a waitable can be in at most one set. In the Canonical ABI, `w` is an index into the current component instance's table and can be any type of waitable (`subtask` or `{readable,writable}-{stream,future}-end`). A value of `0` represents a `none` `maybe_set`, since `0` is not a valid table index. For details, see [Waitables and Waitable Sets] in the concurrency explainer and [`canon_waitable_join`] in the Canonical ABI explainer. ###### πŸ”€ `subtask.cancel` | Synopsis | | | -------------------------- | --------------------------------------------------------- | | Approximate WIT signature | `func(subtask: subtask) -> option` | | Canonical ABI signature | `[subtask:i32] -> [i32]` | The `subtask.cancel` built-in requests [cancellation] of the indicated subtask, trapping if the caller was already notified of resolution, cancellation has already been requested, or the subtask is already in a waitable set. If the `async` is present, `none` is returned (represented as `-1` in the Canonical ABI) to indicate that the subtask blocked before it was [resolved]. Otherwise, `subtask.cancel` returns the `subtask-state` that the subtask resolved to (which is one of `returned`, `cancelled-before-started` or `cancelled-before-returned`). The `async` immediate is gated on 🚝. Without `async`, the `none` case is not possible and `subtask.cancel` synchronously waits, if necessary, until the callee is resolved. For details, see [Cancellation] in the concurrency explainer and [`canon_subtask_cancel`] in the Canonical ABI explainer. ###### πŸ”€ `subtask.drop` | Synopsis | | | -------------------------- | ------------------------ | | Approximate WIT signature | `func(subtask: subtask)` | | Canonical ABI signature | `[subtask:i32] -> []` | The `subtask.drop` built-in removes the indicated [subtask] from the current component instance's table, trapping if wasm hasn't yet received the subtask's resolution (via `waitable-set.{wait,poll}` or `callback` event). For details, see [`canon_subtask_drop`] in the Canonical ABI explainer. ###### πŸ”€ `stream.new` and `future.new` | Synopsis | | | ------------------------------------------ | ------------------------------------------------------------------------------- | | Approximate WIT signature for `stream.new` | `func>() -> tuple, writable-stream-end>` | | Approximate WIT signature for `future.new` | `func>() -> tuple, writable-future-end>` | | Canonical ABI signature | `[] -> [packed-ends:i64]` | The `stream.new` and `future.new` built-ins return the [readable and writable ends] of a new `stream` or `future`. The readable and writable ends are added to the current component instance's table and then the two `i32` indices of the two ends are packed into a single `i64` return value (with the readable end in the low 32 bits). The types `readable-stream-end` and `writable-stream-end` are not WIT types; they are the conceptual lower-level types that describe how the canonical built-ins use the readable and writable ends of a `stream`. An analogous relationship exists among `readable-future-end`, `writable-future-end`, and the WIT `future`. For details, see [Streams and Futures] in the concurrency explainer and [`canon_stream_new`] in the Canonical ABI explainer. ###### πŸ”€ `stream.read` and `stream.write` | Synopsis | | | -------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | Approximate WIT signature for `stream.read` | `func,memory>(e: readable-stream-end, b: writable-buffer?) -> option` | | Approximate WIT signature for `stream.write` | `func,memory>(e: writable-stream-end, b: readable-buffer?) -> option` | | Canonical ABI signature | `[stream-end:i32 ptr:memory.addrtype num:memory.addrtype] -> [memory.addrtype]` | where `stream-result` is defined in WIT as: ```wit record stream-result { /// The number of elements read/written. progress: u32, /// The status of the read/write operation. result: copy-result } enum copy-result { /// The read/write completed successfully. /// /// The stream remains open for new reads/writes. completed, /// The other end was dropped and so this end must now be dropped. /// /// For `stream.read`, this means that the end of the stream was reached. /// /// For `stream.write`, this means that the consumer has no need for further /// data from this stream. This doesn't signify an error; it just instructs /// the producer to stop sending data. dropped, /// The read/write was cancelled by `stream.cancel-{read,write}`. /// /// The stream remains open for new reads/writes. cancelled } ``` The `stream.read` and `stream.write` built-ins take the matching [readable or writable end] of a stream as the first parameter and, if `T` is present, a buffer for the `T` values to be read from or written to. If `T` is not present, the buffer parameter is ignored. Otherwise, the buffer's alignment and bounds are checked even when its length is `0`. If the return value is a `stream-result`, then the `progress` field indicates how many `T` elements were read or written from the given buffer before the `copy-result` was reached. For example, a return value of `{progress: 4, result: dropped}` from a `stream.read` means that 16 bytes were copied into the given buffer before the writer end dropped the stream. The `cancelled` case can only arise as the result of a call to `stream.cancel-{read,write}`. If the return value is `none`, then the operation blocked and the caller needs to wait for progress (via [waitable set] and `waitable-set.{wait,poll}` or, if using a `callback`, by returning to the event loop) which will asynchronously produce an `event` containing a `stream-result`. If `stream.{read,write}` return `dropped` (synchronously or asynchronously), any subsequent operation on the stream other than `stream.drop-{readable,writable}` traps. In the Canonical ABI, the `{readable,writable}-stream-end` is passed as an `i32` index into the component instance's table followed by a pair of `memory.addrtype`s describing the linear memory offset and size-in-elements of the `{readable,writable}-buffer`. The `option` return value is bit-packed into a single `memory.addrtype` where: * all-ones represents `none`. * Otherwise, the `result` is in the low 4 bits and the `progress` is in the remaining high bits. For details, see [Streams and Futures] in the concurrency explainer and [`canon_stream_read`] in the Canonical ABI explainer. ###### πŸ”€ `future.read` and `future.write` | Synopsis | | | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | Approximate WIT signature for `future.read` | `func,memory>(e: readable-future-end, b: writable-buffer?) -> option` | | Approximate WIT signature for `future.write` | `func,memory>(e: writable-future-end, v: readable-buffer?) -> option` | | Canonical ABI signature | `[readable-future-end:i32 ptr:memory.addrtype] -> [i32]` | where `future-{read,write}-result` are defined in WIT as: ```wit enum future-read-result { /// The read completed and this readable end must now be dropped. completed, /// The read was cancelled by `future.cancel-read`. /// /// The future remains open for a new `future.read`. cancelled } enum future-write-result { /// The write completed successfully and this writable end must now be dropped. completed, /// The readable end was dropped and so the writable end must now be dropped. dropped, /// The write was cancelled by `future.cancel-write`. /// /// The future remains open for a new `future.write`. cancelled } ``` `future-read-result` is the same as the `copy-result` enum used in `stream-result` minus the `dropped` case (since futures do not allow the writer to drop their end before writing a value). `future-write-result` is the same as `copy-result`, including the `dropped` case (since the writer can be notified that the reader signalled loss of interest by dropping their end). The `future.{read,write}` built-ins takes the [readable or writable end] of a future as the first parameter and, if `T` is present, a single-element buffer that can be used to write or read a single `T` value. If the return value is `none`, then the call blocked and the caller needs to wait for progress (via [waitable set] and `waitable-set.{wait,poll}` or, if using a `callback`, by returning to the event loop) which will asynchronously produce an `event` containing a `future-{read,write}-result`. If `future.{read,write}` return `completed` or `dropped` (synchronously or asynchronously), any subsequent operation on the future other than `future.drop-{readable,writable}` traps. A component *may* call `future.drop-readable` *before* successfully reading a value to indicate a loss of interest. `future.drop-writable` will trap if called before successfully writing a value or being notified that the readable end was dropped. In the Canonical ABI, the `{readable,writable}-future-end` is passed as an `i32` index into the component instance's table followed by a single `memory.addrtype` describing the linear memory offset of the `{readable,writable}-buffer`. The `option` return value is bit-packed into the single `i32` return value where all-ones represents `none`. And, `future-read-result.cancelled` is encoded as the value of `future-write-result.cancelled`, rather than the value implied by the `enum` definition above. For details, see [Streams and Futures] in the concurrency explainer and [`canon_future_read`] in the Canonical ABI explainer. ###### πŸ”€ `stream.cancel-read`, `stream.cancel-write`, `future.cancel-read`, and `future.cancel-write` | Synopsis | | | --------------------------------------------------- | ----------------------------------------------------------------------------- | | Approximate WIT signature for `stream.cancel-read` | `func>(e: readable-stream-end) -> option` | | Approximate WIT signature for `stream.cancel-write` | `func>(e: writable-stream-end) -> option` | | Approximate WIT signature for `future.cancel-read` | `func>(e: readable-future-end) -> option` | | Approximate WIT signature for `future.cancel-write` | `func>(e: writable-future-end) -> option` | | Canonical ABI signature | `[e: i32] -> [i32]` | The `{stream,future}.cancel-{read,write}` built-ins take the matching [readable or writable end] of a stream or future that has a pending `async` `{stream,future}.{read,write}` (trapping otherwise). If cancellation finishes without blocking, the return value is a `stream-result` or `future-{read,write}-result`. If cancellation blocks, the return value is `none` and the caller must wait for a corresponding `{stream,future}-{read,write}` event via `waitable-set.{wait,poll}` or, when using a `callback`, returning to the event loop. In either case, the result may be `cancelled` but may also be `completed` or `dropped`, if one of these racily happened first. In the Canonical ABI, the optional result value is bit-packed into the single `i32` result in the same way as `{stream,future}.{read,write}`. For details, see [Streams and Futures] in the concurrency explainer and [`canon_stream_cancel_read`] in the Canonical ABI explainer. ###### πŸ”€ `stream.drop-readable`, `stream.drop-writable`, `future.drop-readable`, and `future.drop-writable` | Synopsis | | | ---------------------------------------------------- | ---------------------------------------------- | | Approximate WIT signature for `stream.drop-readable` | `func>(e: readable-stream-end)` | | Approximate WIT signature for `stream.drop-writable` | `func>(e: writable-stream-end)` | | Approximate WIT signature for `future.drop-readable` | `func>(e: readable-future-end)` | | Approximate WIT signature for `future.drop-writable` | `func>(e: writable-future-end)` | | Canonical ABI signature | `[end:i32] -> []` | The `{stream,future}.drop-{readable,writable}` built-ins remove the indicated [stream or future] from the current component instance's table, trapping if the stream or future has a mismatched direction or type or are in the middle of a `read` or `write` or, in the special case of `future.drop-writable`, if a value has not already been successfully written or the readable end has not already been dropped. For details, see [Streams and Futures] in the concurrency explainer and [`canon_stream_drop_readable`] in the Canonical ABI explainer. ###### ➑️ `stream.forward` and `future.forward` | Synopsis | | | ---------------------------------------------- | -------------------------------------------------------------------------- | | Approximate WIT signature for `stream.forward` | `func>(r: readable-stream-end, w: writable-stream-end)` | | Approximate WIT signature for `future.forward` | `func>(r: readable-future-end, w: writable-future-end)` | | Canonical ABI signature | `[ri:i32 wi:i32] -> []` | The `{stream,future}.forward` built-ins remove the given readable and writable ends from the caller's handle table and logically forward everything from the readable end into the writable end (propagating drops in both directions), but do so without an intermediate copy. The call traps if either end has a mismatched direction or element type, is in the middle of a read or write, is a member of a waitable set, or has received its final `dropped` or, for futures, `completed` result. For details, see [Streams and Futures] in the concurrency explainer and [`canon_stream_forward`] in the Canonical ABI explainer. ###### 🧡 `thread.index` | Synopsis | | | -------------------------- | --------------- | | Approximate WIT signature | `func() -> u32` | | Canonical ABI signature | `[] -> [i32]` | The `thread.index` built-in returns the index of the [current thread] in the component instance's table. While `thread.new-indirect` also returns the index of newly-created threads, threads created implicitly for export calls can only learn their index via `thread.index`. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_index`] in the Canonical ABI explainer. ###### 🧡 `thread.new-indirect` | Synopsis | | | -------------------------- | --------------------------------------------------------------------- | | Approximate WIT signature | `func(fi: table.addrtype, c: FuncT.params[0]) -> thread` | | Canonical ABI signature | `[fi:table.addrtype c: FuncT.params[0]] -> [i32]` | The `thread.new-indirect` built-in adds a new thread to the current component instance's table, returning the index of the new thread. The function table supplied via [`core:tableidx`] is indexed by the `fi` operand and then dynamically checked to match the type `FuncT` (in the same manner as `call_indirect`). Here the `table.addrtype` is either `i32` or `i64` as determined by the [`core:tabletype`] of the table. Lastly, the indexed function is called in the new thread with `c` as its first and only parameter. Currently, `FuncT` must be `(func (param i32))` (or, with 🐘, `(func (param i64))`) and thus `c` must always be an `i32` (or `i64`), but this restriction can be loosened in the future as the Canonical ABI is extended for [GC]. As explained in the [concurrency explainer], a thread created by `thread.new-indirect` is initially in a suspended state and must be resumed eagerly by [`thread.suspend-then-resume`](#-threadsuspend-then-resume) or [`thread.yield-then-resume`](#-threadyield-then-resume) or lazily by [`thread.resume-later`](#-threadresume-later) to begin execution. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_new_indirect`] in the Canonical ABI explainer. ###### 🧡 `thread.resume-later` | Synopsis | | | -------------------------- | ----------------- | | Approximate WIT signature | `func(t: thread)` | | Canonical ABI signature | `[t:i32] -> []` | The `thread.resume-later` built-in changes the state of thread `t` from "suspended" to "ready" (trapping if `t` is not in a "suspended" state, including if `t` is the current thread) so that the runtime can nondeterministically resume `t` at some point in the future. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_resume_later`] in the Canonical ABI explainer. ###### 🧡 `thread.suspend` | Synopsis | | | -------------------------- | ------------- | | Approximate WIT signature | `func()` | | Canonical ABI signature | `[] -> [i32]` | The `thread.suspend` built-in suspends the [current thread] until it is explicitly resumed by some other thread calling a built-in such as `thread.resume-later`. The returned `i32` is always `0` and may be removed in a future ABI revision. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_suspend`] in the Canonical ABI explainer. ###### πŸ”€ `thread.yield` | Synopsis | | | -------------------------- | ------------- | | Approximate WIT signature | `func()` | | Canonical ABI signature | `[] -> [i32]` | The `thread.yield` built-in allows the runtime to potentially switch to any other thread in the "ready" state, enabling a long-running computation to cooperatively interleave execution without specifically requesting another thread to be resumed (as with `thread.yield-then-resume`). The returned `i32` is always `0` and may be removed in a future ABI revision. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_yield`] in the Canonical ABI explainer. ###### 🧡 `thread.suspend-then-resume` | Synopsis | | | -------------------------- | ------------------ | | Approximate WIT signature | `func(t: thread)` | | Canonical ABI signature | `[t:i32] -> [i32]` | The `thread.suspend-then-resume` built-in suspends the [current thread] and immediately resumes execution of the thread `t`, trapping if `t` is not in a "suspended" state, which includes if `t` is the current thread. The returned `i32` is always `0` and may be removed in a future ABI revision. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_suspend_then_resume`] in the Canonical ABI explainer. ###### 🧡 `thread.yield-then-resume` | Synopsis | | | -------------------------- | ------------------ | | Approximate WIT signature | `func(t: thread)` | | Canonical ABI signature | `[t:i32] -> [i32]` | The `thread.yield-then-resume` built-in immediately resumes execution of the thread `t` (trapping if `t` is not in a "suspended" state, which includes if `t` is the current thread), leaving the [current thread] in a "ready" state so that the runtime can nondeterministically resume the current thread at some point in the future. The returned `i32` is always `0` and may be removed in a future ABI revision. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_yield_then_resume`] in the Canonical ABI explainer. ###### 🧡 `thread.suspend-then-promote` | Synopsis | | | -------------------------- | ------------------ | | Approximate WIT signature | `func(t: thread)` | | Canonical ABI signature | `[t:i32] -> [i32]` | The `thread.suspend-then-promote` built-in traps if `t` is the current thread and, otherwise, immediately resumes execution of the thread `t` if `t` is in a "ready" state, in any case leaving the current thread in a "suspended" state. The returned `i32` is always `0` and may be removed in a future ABI revision. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_suspend_then_promote`] in the Canonical ABI explainer. ###### 🧡 `thread.yield-then-promote` | Synopsis | | | -------------------------- | ------------------ | | Approximate WIT signature | `func(t: thread)` | | Canonical ABI signature | `[t:i32] -> [i32]` | The `thread.yield-then-promote` built-in traps if `t` is the current thread and, otherwise, immediately resumes execution of the thread `t` if `t` is in a "ready" state, in any case leaving the current thread in a "ready" state. The returned `i32` is always `0` and may be removed in a future ABI revision. For details, see [Thread Built-ins] in the concurrency explainer and [`canon_thread_yield_then_promote`] in the Canonical ABI explainer. ###### πŸ§΅β‘‘ `thread.spawn-ref` | Synopsis | | | -------------------------- | ------------------------------------------------------------------------------------------ | | Approximate WIT signature | `func(f: FuncT, c: FuncT.params[0]) -> thread` | | Canonical ABI signature | `shared? [f:(ref null (shared (func (param FuncT.params[0]))) c:FuncT.params[0]] -> [i32]` | The `thread.spawn-ref` built-in is an optimization, fusing a call to `thread.new_ref` (assuming `thread.new_ref` was added as part of adding a [GC ABI option] to the Canonical ABI) with a call to [`thread.resume-later`](#-threadresume-later). This optimization is more impactful once given [shared-everything-threads] and thus gated on πŸ§΅β‘‘. For details, see [`canon_thread_spawn_ref`] in the Canonical ABI explainer. ###### πŸ§΅β‘‘ `thread.spawn-indirect` | Synopsis | | | -------------------------- | ---------------------------------------------------------------------------- | | Approximate WIT signature | `func(i: table.addrtype, c: FuncT.params[0]) -> thread` | | Canonical ABI signature | `shared? [i:table.addrtype c:FuncT.params[0]] -> [i32]` | The `thread.spawn-indirect` built-in is an optimization, fusing a call to [`thread.new-indirect`](#-threadnew-indirect) with a call to [`thread.resume-later`](#-threadresume-later). This optimization is more impactful once given [shared-everything-threads] and thus gated on πŸ§΅β‘‘. For details, see [`canon_thread_spawn_indirect`] in the Canonical ABI explainer. ###### πŸ§΅β‘‘ `thread.available-parallelism` | Synopsis | | | -------------------------- | ------------------------ | | Approximate WIT signature | `func() -> u32` | | Canonical ABI signature | `shared? [] -> [i32]` | The `thread.available-parallelism` built-in returns the number of threads that can be expected to execute in parallel. The concept of "available parallelism" corresponds is sometimes referred to as "hardware concurrency", such as in [`navigator.hardwareConcurrency`] in JavaScript. For details, see [`canon_thread_available_parallelism`] in the Canonical ABI explainer. ##### πŸ“ Error Context built-ins ###### πŸ“ `error-context.new` | Synopsis | | | -------------------------------- | ---------------------------------------------------- | | Approximate WIT signature | `func(message: string) -> error-context` | | Canonical ABI signature | `[ptr:memory.addrtype len:memory.addrtype] -> [i32]` | The `error-context.new` built-in returns a new `error-context` value. The given string is nondeterministically transformed to produce the `error-context`'s internal [debug message](#error-context-type). In the Canonical ABI, the returned value is an index into the current component instance's table of a new error context value. For details, see [`canon_error_context_new`] in the Canonical ABI explainer. ###### πŸ“ `error-context.debug-message` | Synopsis | | | -------------------------------- | ----------------------------------------------- | | Approximate WIT signature | `func(errctx: error-context) -> string` | | Canonical ABI signature | `[errctxi:i32 ptr:memory.addrtype] -> []` | The `error-context.debug-message` built-in returns the [debug message](#error-context-type) of the given `error-context`. In the Canonical ABI, it writes the debug message into `ptr` as an 8-byte or 16-byte (`ptr`, `length`) pair, according to the Canonical ABI for `string`, given the `*` immediates, trapping if `ptr` is misaligned or out of bounds. For details, see [`canon_error_context_debug_message`] in the Canonical ABI explainer. ###### πŸ“ `error-context.drop` | Synopsis | | | -------------------------------- | ----------------------------- | | Approximate WIT signature | `func(errctx: error-context)` | | Canonical ABI signature | `[errctxi:i32] -> []` | The `error-context.drop` built-in drops the given `error-context` value from the component instance. In the Canonical ABI, `errctxi` is an index into the current component instance's table. For details, see [`canon_error_context_drop`] in the Canonical ABI explainer. ### πŸͺ™ Value Definitions Value definitions (in the value index space) are like immutable `global` definitions in Core WebAssembly except that validation requires them to be consumed exactly once at instantiation-time (i.e., they are [linear]). Components may define values in the value index space using following syntax: ```ebnf value ::= (value ? ) val ::= false | true | | | | "" | | (record +) | (variant ?) | (list *) | (tuple +) | (flags *) | (enum ) | none | (some ) | ok | (ok ) | error | (error ) | (map *) πŸ—ΊοΈ | (binary ) entryval ::= (entry ) πŸ—ΊοΈ fNcanon ::= excluding the `-nan` and `nan:0x` cases ``` where [`core:fN`], [`core:stringchar`] and [`core:datastring`] are as defined by the Core WebAssembly text format. The validation rules for `value` first reject any `valtype` that transitively contains a type constructor that doesn't have a corresponding `val` constructor. Currently this rejects `own`, `borrow`, `future`, `stream` and `error-context`. In particular, `(option (stream u8))` is rejected, even if the `none` case has a `val` constructor. In the future, `val` may be extended to support more cases. Next, validation requires the given `val` to match the `valtype`. In particular: * `fN` only matches `fNcanon` * `sN` and `uN` only match `core:i64` integers that fall within their natural signed range without wrapping (e.g., `(value s8 128)` and `(value u8 -1)` would be rejected) The `(binary ...)` expression form provides an alternative syntax allowing the binary contents of the value definition to be written directly in the text format, analogous to data segments, avoiding the need to understand type information when encoding or decoding. For example: ```wat (component (value $a bool true) (value $b u8 1) (value $c u16 2) (value $d u32 3) (value $e u64 4) (value $f s8 5) (value $g s16 6) (value $h s32 7) (value $i s64 8) (value $j f32 9.1) (value $k f64 9.2) (value $l char 'a') (value $m string "hello") (value $n (record (field "a" bool) (field "b" u8)) (record true 1)) (value $o (variant (case "a" bool) (case "b" u8)) (variant "b" 1)) (value $p (list (result (option u8))) (list error (ok (some 1)) (ok none) error (ok (some 2)) ) ) (value $q (tuple u8 u16 u32) (tuple 1 2 3)) (type $abc (flags "a" "b" "c")) (value $r $abc (flags "a" "c")) (value $s (enum "a" "b" "c") (enum "b")) (value $t bool (binary "\00")) (value $u string (binary "\07example")) ;; πŸ”§ fixed-length list: (value $v (list u8 3) (list 1 2 3)) ;; πŸ—ΊοΈ map: (value $w (map string u16) (map (entry "a" 1) (entry "b" 2) ) ) (type $complex (tuple (record (field "a" (option string)) (field "b" (tuple (option u8) string)) ) (list char) $abc string ) ) (value $complex1 (type $complex) (tuple (record none (tuple none "empty") ) (list) (flags) "" ) ) (value $complex2 (type $complex) (tuple (record (some "example") (tuple (some 42) "hello") ) (list 'a' 'b' 'c') (flags "b" "a") "hi" ) ) ) ``` As with all definition sorts, values may be imported and exported by components. As an example value import: ```wat (import "env" (value $env (record (field "locale" (option string))))) ``` As this example suggests, value imports can serve as generalized [environment variables], allowing not just `string`, but the full range of `valtype`. Values can also be exported. For example: ```wat (component (import "system-port" (value $port u16)) (value $url string "https://example.com") (export "default-url" (value $url)) (export "default-port" (value $port)) ) ``` The inferred type of this component is: ```wat (component (import "system-port" (value $port u16)) (value $url string "https://example.com") (export "default-url" (value (eq $url))) (export "default-port" (value (eq $port))) ) ``` Thus, by default, the precise constant or import being exported is propagated into the component's type and thus its public interface. In this way, value exports can act as semantic configuration data provided by the component to the host or other client tooling. Components can also keep the exact value being exported abstract (so that the precise value is not part of the type and public interface) using the "type ascription" feature mentioned in the [imports and exports](#import-and-export-definitions) section below. ### πŸͺ™ Start Definitions Like modules, components can have start functions that are called during instantiation. Unlike modules, components can call start functions at multiple points during instantiation with each such call having parameters and results. Thus, `start` definitions in components look like function calls: ```ebnf start ::= (start (value )* (result (value ?))*) ``` The `(value )*` list specifies the arguments passed to `funcidx` by indexing into the *value index space*. The arity and types of the two value lists are validated to match the signature of `funcidx`. With this, we can define a component that imports a string and computes a new exported string at instantiation time: ```wat (component (import "name" (value $name string)) (import "libc" (core module $Libc (export "memory" (memory 1)) (export "realloc" (func (param i32 i32 i32 i32) (result i32))) )) (core instance $libc (instantiate $Libc)) (core module $Main (import "libc" ...) (func (export "start") (param i32 i32) (result i32) ... general-purpose compute ) ) (core instance $main (instantiate $Main (with "libc" (instance $libc)))) (func $start (param string) (result string) (canon lift (core func $main "start") (memory (core memory $libc "mem")) (realloc (core func $libc "realloc")) )) (start $start (value $name) (result (value $greeting))) (export "greeting" (value $greeting)) ) ``` As this example shows, start functions reuse the same Canonical ABI machinery as normal imports and exports for getting component-level values into and out of core linear memory. ### Import and Export Definitions Import and export definitions are similar to Core WebAssembly import and export definitions, but different in a few ways: The first is that component-level imports have only a single name. (Two- and even N-level imports can be achieved by importing `instance` types). Second, component-level imports and exports can use all of the [component-level sorts](#index-spaces) (`func`, `value` πŸͺ™, `type`, `instance`, `component`) but just 1 core sort: `module`. This restriction is enforced by validation which assigns every component a [`componenttype`](#type-definitions) (which similarly only allows core types of the `module` type constructor). This restriction ensures that all cross-component calls transit through a [lift/lower trampoline](#canonical-abi), which allows the Component Model to create a "membrane" around all the core module instances contained by a component instance in order to provide various structural guarantees to the Core WebAssembly code running inside. A third difference is that not only import definitions, but also export definitions append a new element to the index space of the imported/exported `sort` which can be optionally bound to an identifier in the text format. In the case of imports, the identifier is bound just like Core WebAssembly, as part of the `externtype` (e.g., `(import "x" (func $x))` binds the identifier `$x`). In the case of exports, the `?` right after the `export` is bound while the `` inside the `` is a reference to the preceding definition being exported (e.g., `(export $x "x" (func $f))` binds a new identifier `$x`). Given this, the syntax of imports and exports are defined as follows: ```ebnf import ::= (import bind-id()) export ::= (export ? ?) attributes ::= ? ? ? implements ::= (implements ) 🏷️ versionsuffix ::= (version-suffix ) πŸ”— externid ::= (external-id ) 🏷️ ``` Imports and exports both have a *name* (`externnamelit`) and a list of *attributes* (`attributes`). Imports always include a type (`externtype`). Exports always refer to a preceding definition (`externidx`) whose type is used by default as the type of the export. However, this "inferred" type can be overridden with an optional type ascription (`externtype`) which must be compatible with the exported definition's type. Import and export names are used by hosts and [parent][Donut Wrapped] components to *identify* imports and exports. Names are expected to be bound to source language variable-, function- and type-names. Thus, names are required to be [strongly-unique] and have a more restrictive, structured syntax that provides bindings generators extra hints that allow more idiomatic bindings, as described next. In contrast, import and export attributes are not used to identify imports and exports and instead provide extra semantic information *about* imports and exports that hosts or tools can automatically interpret to determine *how* to supply imports and call exports. In particular: πŸ”— The `version-suffix` attribute provides the minor/patch/build information that was stripped from the [Canonical interface name](#-canonical-interface-name) so that this information can be used in error messages to reconstruct the full original semantic version. A `version-suffix` may only be attached to an `instance` import or export and applies to the `interfacename` of the `implements` attribute, if present, and otherwise to the `interfacename` of the import or export itself. For example: ```wat (component (import "wasi:http/types@0.2" (version-suffix ".6") (instance ...)) (import "primary" (implements "wasi:keyvalue/store@0.2") (version-suffix ".1") (instance ...)) ) ``` 🏷️ The `implements` attribute indicates that an imported or exported `instance` implements a particular WIT interface. This enables a component to semantically import or export the same `interfacename` multiple times (with different names). For example: ```wat (component (import "primary" (implements "wasi:keyvalue/store") (instance ...)) (import "secondary" (implements "wasi:keyvalue/store") (instance ...)) ) ``` This ensures that imports and exports continue to have unique names (so that, e.g., guest code executing inside this component has distinct `primary`- and `secondary`-scoped names for all `wasi:keyvalue/store` operations) while still providing the semantic information conveyed by the `interfacename` (so that, e.g., hosts can implement both imports with a standard static host `wasi:keyvalue/store` implementation that is dynamically parameterized by the store names `"primary"` and `"secondary"`). 🏷️ The `external-id` attribute addresses the naming-expressivity gap left between the restricted syntax of `externname` (shown next) and whatever preexisting identifier syntax a host needs. For example, in a [JavaScript embedding](#javascript-embedding), a [Module Specifier] can be any Unicode string (with URLs being a common use case) and so for components loaded via [ESM-integration], the `external-id` would be interpreted as the Module Specifier, thereby providing components the same expressivity as JavaScript modules. E.g.: ```wat (component $ESM (import "slugify" (external-id "https://esm.unpkg.com/slugify@1.6.6") (func (param "text" string) (result string))) ) ``` Used together, `implements` and `external-id` allow a single component to, e.g., import multiple `wasi:keyvalue/store`s using their platform's internal store naming scheme without needing to create a separate mapping or name-mangling scheme: ```wat (component (import "users" (implements "wasi:keyvalue/store") (external-id "user-db-prod:region-a") (instance ...)) (import "catalog" (implements "wasi:keyvalue/store") (external-id "catalog-db-prod:region-a") (instance ...)) ) ``` The following grammar defines the syntax of import and export names. Unlike all the other *parsing* rules in this document, the following are *lexical rules* for lexing individual characters into the top-level `-lit` tokens that are used by all the other parsing rules. Thus, in the following rules, whitespace is *not* inserted automatically, all terminals are single-quoted and everything unquoted is a meta-character. ```ebnf externnamelit ::= '"' '"' externname ::= | plainname ::=