wasmtime/runtime/component/
mod.rs

1//! # Embedding API for the Component Model
2//!
3//! This module contains the embedding API for the [Component Model] in
4//! Wasmtime. This module requires the `component-model` feature to be enabled,
5//! which is enabled by default. The embedding API here is mirrored after the
6//! core wasm embedding API at the crate root and is intended to have the same
7//! look-and-feel while handling concepts of the component model.
8//!
9//! [Component Model]: https://component-model.bytecodealliance.org
10//!
11//! The component model is a broad topic which can't be explained here fully, so
12//! it's recommended to read over individual items' documentation to see more
13//! about the capabilities of the embedding API. At a high-level, however,
14//! perhaps the most interesting items in this module are:
15//!
16//! * [`Component`] - a compiled component ready to be instantiated. Similar to
17//!   a [`Module`](crate::Module) for core wasm.
18//!
19//! * [`Linker`] - a component-style location for defining host functions. This
20//!   is not the same as [`wasmtime::Linker`](crate::Linker) for core wasm
21//!   modules.
22//!
23//! * [`bindgen!`] - a macro to generate Rust bindings for a [WIT] [world]. This
24//!   maps all WIT types into Rust automatically and generates traits for
25//!   embedders to implement.
26//!
27//! [WIT]: https://component-model.bytecodealliance.org/design/wit.html
28//! [world]: https://component-model.bytecodealliance.org/design/worlds.html
29//!
30//! Embedders of the component model will typically start by defining their API
31//! in [WIT]. This describes what will be available to guests and what needs to
32//! be provided to the embedder by the guest. This [`world`][world] that was
33//! created is then fed into [`bindgen!`] to generate types and traits for the
34//! embedder to use. The embedder then implements these traits, adds
35//! functionality via the generated `add_to_linker` method (see [`bindgen!`] for
36//! more info), and then instantiates/executes a component.
37//!
38//! It's recommended to read over the [documentation for the Component
39//! Model][Component Model] to get an overview about how to build components
40//! from various languages.
41//!
42//! ## Example Usage
43//!
44//! Imagine you have the following WIT package definition in a file called world.wit
45//! along with a component (my_component.wasm) that targets `my-world`:
46//!
47//! ```text,ignore
48//! package component:my-package;
49//!
50//! world my-world {
51//!     import name: func() -> string;
52//!     export greet: func() -> string;
53//! }
54//! ```
55//!
56//! You can instantiate and call the component like so:
57//!
58//! ```
59//! fn main() -> wasmtime::Result<()> {
60//!     #   if true { return Ok(()) }
61//!     // Instantiate the engine and store
62//!     let engine = wasmtime::Engine::default();
63//!     let mut store = wasmtime::Store::new(&engine, ());
64//!
65//!     // Load the component from disk
66//!     let bytes = std::fs::read("my_component.wasm")?;
67//!     let component = wasmtime::component::Component::new(&engine, bytes)?;
68//!
69//!     // Configure the linker
70//!     let mut linker = wasmtime::component::Linker::new(&engine);
71//!     // The component expects one import `name` that
72//!     // takes no params and returns a string
73//!     linker
74//!         .root()
75//!         .func_wrap("name", |_store, _params: ()| {
76//!             Ok((String::from("Alice"),))
77//!         })?;
78//!
79//!     // Instantiate the component
80//!     let instance = linker.instantiate(&mut store, &component)?;
81//!
82//!     // Call the `greet` function
83//!     let func = instance.get_func(&mut store, "greet").expect("greet export not found");
84//!     let mut result = [wasmtime::component::Val::String("".into())];
85//!     func.call(&mut store, &[], &mut result)?;
86//!
87//!     // This should print out `Greeting: [String("Hello, Alice!")]`
88//!     println!("Greeting: {:?}", result);
89//!
90//!     Ok(())
91//! }
92//! ```
93//!
94//! Manually configuring the linker and calling untyped component exports is
95//! a bit tedious and error prone. The [`bindgen!`] macro can be used to
96//! generate bindings eliminating much of this boilerplate.
97//!
98//! See the docs for [`bindgen!`] for more information on how to use it.
99
100// rustdoc appears to lie about a warning above, so squelch it for now.
101#![allow(rustdoc::redundant_explicit_links)]
102
103mod component;
104#[cfg(feature = "component-model-async")]
105pub(crate) mod concurrent;
106mod func;
107mod has_data;
108mod instance;
109mod linker;
110mod matching;
111mod resource_table;
112mod resources;
113mod storage;
114mod store;
115pub mod types;
116mod values;
117pub use self::component::{Component, ComponentExportIndex};
118#[cfg(feature = "component-model-async")]
119pub use self::concurrent::{
120    ErrorContext, FutureReader, Promise, PromisesUnordered, StreamReader, VMComponentAsyncStore,
121};
122pub use self::func::{
123    ComponentNamedList, ComponentType, Func, Lift, Lower, TypedFunc, WasmList, WasmStr,
124};
125pub use self::has_data::*;
126pub use self::instance::{Instance, InstanceExportLookup, InstancePre};
127pub use self::linker::{Linker, LinkerInstance};
128pub use self::resource_table::{ResourceTable, ResourceTableError};
129pub use self::resources::{Resource, ResourceAny};
130pub use self::types::{ResourceType, Type};
131pub use self::values::Val;
132
133pub(crate) use self::instance::RuntimeImport;
134pub(crate) use self::resources::HostResourceData;
135pub(crate) use self::store::ComponentInstanceId;
136
137// Re-export wasm_wave crate so the compatible version of this dep doesn't have to be
138// tracked separately from wasmtime.
139#[cfg(feature = "wave")]
140pub use wasm_wave;
141
142// These items are used by `#[derive(ComponentType, Lift, Lower)]`, but they are not part of
143// Wasmtime's API stability guarantees
144#[doc(hidden)]
145pub mod __internal {
146    pub use super::func::{
147        ComponentVariant, LiftContext, LowerContext, Options, bad_type_info, format_flags,
148        lower_payload, typecheck_enum, typecheck_flags, typecheck_record, typecheck_variant,
149    };
150    pub use super::matching::InstanceType;
151    pub use crate::MaybeUninitExt;
152    pub use crate::map_maybe_uninit;
153    pub use crate::store::StoreOpaque;
154    pub use alloc::boxed::Box;
155    pub use alloc::string::String;
156    pub use alloc::vec::Vec;
157    pub use anyhow;
158    pub use core::cell::RefCell;
159    pub use core::mem::transmute;
160    #[cfg(feature = "async")]
161    pub use trait_variant::make as trait_variant_make;
162    pub use wasmtime_environ;
163    pub use wasmtime_environ::component::{CanonicalAbiInfo, ComponentTypes, InterfaceType};
164}
165
166pub(crate) use self::store::ComponentStoreData;
167
168/// Generate bindings for a [WIT world].
169///
170/// [WIT world]: https://component-model.bytecodealliance.org/design/worlds.html
171/// [WIT package]: https://component-model.bytecodealliance.org/design/packages.html
172///
173/// This macro ingests a [WIT world] and will generate all the necessary
174/// bindings for instantiating components that ascribe to the `world`. This
175/// provides a higher-level representation of working with a component than the
176/// raw [`Instance`] type which must be manually-type-checked and manually have
177/// its imports provided via the [`Linker`] type.
178///
179/// # Examples
180///
181/// Examples for this macro can be found in the [`bindgen_examples`] module
182/// documentation. That module has a submodule-per-example which includes the
183/// source code, with WIT, used to generate the structures along with the
184/// generated code itself in documentation.
185///
186/// # Debugging and Exploring
187///
188/// If you need to debug the output of `bindgen!` you can try using the
189/// `WASMTIME_DEBUG_BINDGEN=1` environment variable. This will write the
190/// generated code to a file on disk so rustc can produce better error messages
191/// against the actual generated source instead of the macro invocation itself.
192/// This additionally can enable opening up the generated code in an editor and
193/// exploring it (through an error message).
194///
195/// The generated bindings can additionally be explored with `cargo doc` to see
196/// what's generated. It's also recommended to browse the [`bindgen_examples`]
197/// for example generated structures and example generated code.
198///
199/// # Syntax
200///
201/// This procedural macro accepts a few different syntaxes. The primary purpose
202/// of this macro is to locate a WIT package, parse it, and then extract a
203/// `world` from the parsed package. There are then codegen-specific options to
204/// the bindings themselves which can additionally be specified.
205///
206/// Usage of this macro looks like:
207///
208/// ```rust
209/// # macro_rules! bindgen { ($($t:tt)*) => () }
210/// // Parse the `wit/` folder adjacent to this crate's `Cargo.toml` and look
211/// // for a single `world` in it. There must be exactly one for this to
212/// // succeed.
213/// bindgen!();
214///
215/// // Parse the `wit/` folder adjacent to this crate's `Cargo.toml` and look
216/// // for the world `foo` contained in it.
217/// bindgen!("foo");
218///
219/// // Parse the folder `other/wit/folder` adjacent to `Cargo.toml`.
220/// bindgen!(in "other/wit/folder");
221/// bindgen!("foo" in "other/wit/folder");
222///
223/// // Parse the file `foo.wit` as a single-file WIT package with no
224/// // dependencies.
225/// bindgen!("foo" in "foo.wit");
226///
227/// // Specify a suite of options to the bindings generation, documented below
228/// bindgen!({
229///     world: "foo",
230///     path: "other/path/to/wit",
231///     // ...
232/// });
233/// ```
234///
235/// # Options Reference
236///
237/// This is an example listing of all options that this macro supports along
238/// with documentation for each option and example syntax for each option.
239///
240/// ```rust
241/// # macro_rules! bindgen { ($($t:tt)*) => () }
242/// bindgen!({
243///     world: "foo", // not needed if `path` has one `world`
244///
245///     // same as in `bindgen!(in "other/wit/folder")
246///     path: "other/wit/folder",
247///
248///     // Instead of `path` the WIT document can be provided inline if
249///     // desired.
250///     inline: "
251///         package my:inline;
252///
253///         world foo {
254///             // ...
255///         }
256///     ",
257///
258///     // Add calls to `tracing::span!` before each import or export is called
259///     // to log most arguments and return values. By default values
260///     // containing lists are excluded; enable `verbose_tracing` to include
261///     // them.
262///     //
263///     // This option defaults to `false`.
264///     tracing: true,
265///
266///     // Include all arguments and return values in the tracing output,
267///     // including values containing lists, which may be very large.
268///     //
269///     // This option defaults to `false`.
270///     verbose_tracing: false,
271///
272///     // Imports will be async functions and exports
273///     // are also invoked as async functions. Requires `Config::async_support`
274///     // to be `true`.
275///     //
276///     // Note that this is only async for the host as the guest will still
277///     // appear as if it's invoking blocking functions.
278///     //
279///     // This option defaults to `false`.
280///     async: true,
281///
282///     // Alternative mode of async configuration where this still implies
283///     // async instantiation happens, for example, but more control is
284///     // provided over which imports are async and which aren't.
285///     //
286///     // Note that in this mode all exports are still async.
287///     async: {
288///         // All imports are async except for functions with these names
289///         except_imports: ["foo", "bar"],
290///
291///         // All imports are synchronous except for functions with these names
292///         //
293///         // Note that this key cannot be specified with `except_imports`,
294///         // only one or the other is accepted.
295///         only_imports: ["foo", "bar"],
296///     },
297///
298///     // This option is used to indicate whether imports can trap.
299///     //
300///     // Imports that may trap have their return types wrapped in
301///     // `wasmtime::Result<T>` where the `Err` variant indicates that a
302///     // trap will be raised in the guest.
303///     //
304///     // By default imports cannot trap and the return value is the return
305///     // value from the WIT bindings itself. This value can be set to `true`
306///     // to indicate that any import can trap. This value can also be set to
307///     // an array-of-strings to indicate that only a set list of imports
308///     // can trap.
309///     trappable_imports: false,             // no imports can trap (default)
310///     // trappable_imports: true,           // all imports can trap
311///     // trappable_imports: ["foo", "bar"], // only these can trap
312///
313///     // This can be used to translate WIT return values of the form
314///     // `result<T, error-type>` into `Result<T, RustErrorType>` in Rust.
315///     // Users must define `RustErrorType` and the `Host` trait for the
316///     // interface which defines `error-type` will have a method
317///     // called `convert_error_type` which converts `RustErrorType`
318///     // into `wasmtime::Result<ErrorType>`. This conversion can either
319///     // return the raw WIT error (`ErrorType` here) or a trap.
320///     //
321///     // By default this option is not specified. This option only takes
322///     // effect when `trappable_imports` is set for some imports.
323///     trappable_error_type: {
324///         "wasi:io/streams/stream-error" => RustErrorType,
325///     },
326///
327///     // All generated bindgen types are "owned" meaning types like `String`
328///     // are used instead of `&str`, for example. This is the default and
329///     // ensures that the same type used in both imports and exports uses the
330///     // same generated type.
331///     ownership: Owning,
332///
333///     // Alternative to `Owning` above where borrowed types attempt to be used
334///     // instead. The `duplicate_if_necessary` configures whether duplicate
335///     // Rust types will be generated for the same WIT type if necessary, for
336///     // example when a type is used both as an import and an export.
337///     ownership: Borrowing {
338///         duplicate_if_necessary: true
339///     },
340///
341///     // Restrict the code generated to what's needed for the interface
342///     // imports in the inlined WIT document fragment.
343///     interfaces: "
344///         import wasi:cli/command;
345///     ",
346///
347///     // Remap imported interfaces or resources to types defined in Rust
348///     // elsewhere. Using this option will prevent any code from being
349///     // generated for interfaces mentioned here. Resources named here will
350///     // not have a type generated to represent the resource.
351///     //
352///     // Interfaces mapped with this option should be previously generated
353///     // with an invocation of this macro. Resources need to be mapped to a
354///     // Rust type name.
355///     with: {
356///         // This can be used to indicate that entire interfaces have
357///         // bindings generated elsewhere with a path pointing to the
358///         // bindinges-generated module.
359///         "wasi:random/random": wasmtime_wasi::p2::bindings::random::random,
360///
361///         // Similarly entire packages can also be specified.
362///         "wasi:cli": wasmtime_wasi::p2::bindings::cli,
363///
364///         // Or, if applicable, entire namespaces can additionally be mapped.
365///         "wasi": wasmtime_wasi::p2::bindings,
366///
367///         // Versions are supported if multiple versions are in play:
368///         "wasi:http/types@0.2.0": wasmtime_wasi_http::bindings::http::types,
369///         "wasi:http@0.2.0": wasmtime_wasi_http::bindings::http,
370///
371///         // The `with` key can also be used to specify the `T` used in
372///         // import bindings of `Resource<T>`. This can be done to configure
373///         // which typed resource shows up in generated bindings and can be
374///         // useful when working with the typed methods of `ResourceTable`.
375///         "wasi:filesystem/types/descriptor": MyDescriptorType,
376///     },
377///
378///     // Additional derive attributes to include on generated types (structs or enums).
379///     //
380///     // These are deduplicated and attached in a deterministic order.
381///     additional_derives: [
382///         Hash,
383///         serde::Deserialize,
384///         serde::Serialize,
385///     ],
386///
387///     // An niche configuration option to require that the `T` in `Store<T>`
388///     // is always `Send` in the generated bindings. Typically not needed
389///     // but if synchronous bindings depend on asynchronous bindings using
390///     // the `with` key then this may be required.
391///     require_store_data_send: false,
392///
393///     // If the `wasmtime` crate is depended on at a nonstandard location
394///     // or is renamed then this is the path to the root of the `wasmtime`
395///     // crate. Much of the generated code needs to refer to `wasmtime` so
396///     // this should be used if the `wasmtime` name is not wasmtime itself.
397///     //
398///     // By default this is `wasmtime`.
399///     wasmtime_crate: path::to::wasmtime,
400///
401///     // This is an in-source alternative to using `WASMTIME_DEBUG_BINDGEN`.
402///     //
403///     // Note that if this option is specified then the compiler will always
404///     // recompile your bindings. Cargo records the start time of when rustc
405///     // is spawned by this will write a file during compilation. To Cargo
406///     // that looks like a file was modified after `rustc` was spawned,
407///     // so Cargo will always think your project is "dirty" and thus always
408///     // recompile it. Recompiling will then overwrite the file again,
409///     // starting the cycle anew. This is only recommended for debugging.
410///     //
411///     // This option defaults to false.
412///     include_generated_code_from_file: false,
413/// });
414/// ```
415pub use wasmtime_component_macro::bindgen;
416
417/// Derive macro to generate implementations of the [`ComponentType`] trait.
418///
419/// This derive macro can be applied to `struct` and `enum` definitions and is
420/// used to bind either a `record`, `enum`, or `variant` in the component model.
421///
422/// Note you might be looking for [`bindgen!`] rather than this macro as that
423/// will generate the entire type for you rather than just a trait
424/// implementation.
425///
426/// This macro supports a `#[component]` attribute which is used to customize
427/// how the type is bound to the component model. A top-level `#[component]`
428/// attribute is required to specify either `record`, `enum`, or `variant`.
429///
430/// ## Records
431///
432/// `record`s in the component model correspond to `struct`s in Rust. An example
433/// is:
434///
435/// ```rust
436/// use wasmtime::component::ComponentType;
437///
438/// #[derive(ComponentType)]
439/// #[component(record)]
440/// struct Color {
441///     r: u8,
442///     g: u8,
443///     b: u8,
444/// }
445/// ```
446///
447/// which corresponds to the WIT type:
448///
449/// ```wit
450/// record color {
451///     r: u8,
452///     g: u8,
453///     b: u8,
454/// }
455/// ```
456///
457/// Note that the name `Color` here does not need to match the name in WIT.
458/// That's purely used as a name in Rust of what to refer to. The field names
459/// must match that in WIT, however. Field names can be customized with the
460/// `#[component]` attribute though.
461///
462/// ```rust
463/// use wasmtime::component::ComponentType;
464///
465/// #[derive(ComponentType)]
466/// #[component(record)]
467/// struct VerboseColor {
468///     #[component(name = "r")]
469///     red: u8,
470///     #[component(name = "g")]
471///     green: u8,
472///     #[component(name = "b")]
473///     blue: u8,
474/// }
475/// ```
476///
477/// Also note that field ordering is significant at this time and must match
478/// WIT.
479///
480/// ## Variants
481///
482/// `variant`s in the component model correspond to a subset of shapes of a Rust
483/// `enum`. Variants in the component model have a single optional payload type
484/// which means that not all Rust `enum`s correspond to component model
485/// `variant`s. An example variant is:
486///
487/// ```rust
488/// use wasmtime::component::ComponentType;
489///
490/// #[derive(ComponentType)]
491/// #[component(variant)]
492/// enum Filter {
493///     #[component(name = "none")]
494///     None,
495///     #[component(name = "all")]
496///     All,
497///     #[component(name = "some")]
498///     Some(Vec<String>),
499/// }
500/// ```
501///
502/// which corresponds to the WIT type:
503///
504/// ```wit
505/// variant filter {
506///     none,
507///     all,
508///     some(list<string>),
509/// }
510/// ```
511///
512/// The `variant` style of derive allows an optional payload on Rust `enum`
513/// variants but it must be a single unnamed field. Variants of the form `Foo(T,
514/// U)` or `Foo { name: T }` are not supported at this time.
515///
516/// Note that the order of variants in Rust must match the order of variants in
517/// WIT. Additionally it's likely that `#[component(name = "...")]` is required
518/// on all Rust `enum` variants because the name currently defaults to the Rust
519/// name which is typically UpperCamelCase whereas WIT uses kebab-case.
520///
521/// ## Enums
522///
523/// `enum`s in the component model correspond to C-like `enum`s in Rust. Note
524/// that a component model `enum` does not allow any payloads so the Rust `enum`
525/// must additionally have no payloads.
526///
527/// ```rust
528/// use wasmtime::component::ComponentType;
529///
530/// #[derive(ComponentType)]
531/// #[component(enum)]
532/// #[repr(u8)]
533/// enum Setting {
534///     #[component(name = "yes")]
535///     Yes,
536///     #[component(name = "no")]
537///     No,
538///     #[component(name = "auto")]
539///     Auto,
540/// }
541/// ```
542///
543/// which corresponds to the WIT type:
544///
545/// ```wit
546/// enum setting {
547///     yes,
548///     no,
549///     auto,
550/// }
551/// ```
552///
553/// Note that the order of variants in Rust must match the order of variants in
554/// WIT. Additionally it's likely that `#[component(name = "...")]` is required
555/// on all Rust `enum` variants because the name currently defaults to the Rust
556/// name which is typically UpperCamelCase whereas WIT uses kebab-case.
557pub use wasmtime_component_macro::ComponentType;
558
559/// A derive macro for generating implementations of the [`Lift`] trait.
560///
561/// This macro will likely be applied in conjunction with the
562/// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
563/// of `#[derive(ComponentType, Lift)]`. This trait enables reading values from
564/// WebAssembly.
565///
566/// Note you might be looking for [`bindgen!`] rather than this macro as that
567/// will generate the entire type for you rather than just a trait
568/// implementation.
569///
570/// At this time this derive macro has no configuration.
571///
572/// ## Examples
573///
574/// ```rust
575/// use wasmtime::component::{ComponentType, Lift};
576///
577/// #[derive(ComponentType, Lift)]
578/// #[component(record)]
579/// struct Color {
580///     r: u8,
581///     g: u8,
582///     b: u8,
583/// }
584/// ```
585pub use wasmtime_component_macro::Lift;
586
587/// A derive macro for generating implementations of the [`Lower`] trait.
588///
589/// This macro will likely be applied in conjunction with the
590/// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
591/// of `#[derive(ComponentType, Lower)]`. This trait enables passing values to
592/// WebAssembly.
593///
594/// Note you might be looking for [`bindgen!`] rather than this macro as that
595/// will generate the entire type for you rather than just a trait
596/// implementation.
597///
598/// At this time this derive macro has no configuration.
599///
600/// ## Examples
601///
602/// ```rust
603/// use wasmtime::component::{ComponentType, Lower};
604///
605/// #[derive(ComponentType, Lower)]
606/// #[component(record)]
607/// struct Color {
608///     r: u8,
609///     g: u8,
610///     b: u8,
611/// }
612/// ```
613pub use wasmtime_component_macro::Lower;
614
615/// A macro to generate a Rust type corresponding to WIT `flags`
616///
617/// This macro generates a type that implements the [`ComponentType`], [`Lift`],
618/// and [`Lower`] traits. The generated Rust type corresponds to the `flags`
619/// type in WIT.
620///
621/// Example usage of this looks like:
622///
623/// ```rust
624/// use wasmtime::component::flags;
625///
626/// flags! {
627///     Permissions {
628///         #[component(name = "read")]
629///         const READ;
630///         #[component(name = "write")]
631///         const WRITE;
632///         #[component(name = "execute")]
633///         const EXECUTE;
634///     }
635/// }
636///
637/// fn validate_permissions(permissions: &mut Permissions) {
638///     if permissions.contains(Permissions::EXECUTE | Permissions::WRITE) {
639///         panic!("cannot enable both writable and executable at the same time");
640///     }
641///
642///     if permissions.contains(Permissions::READ) {
643///         panic!("permissions must at least contain read");
644///     }
645/// }
646/// ```
647///
648/// which corresponds to the WIT type:
649///
650/// ```wit
651/// flags permissions {
652///     read,
653///     write,
654///     execute,
655/// }
656/// ```
657///
658/// This generates a structure which is similar to/inspired by the [`bitflags`
659/// crate](https://crates.io/crates/bitflags). The `Permissions` structure
660/// generated implements the [`PartialEq`], [`Eq`], [`Debug`], [`BitOr`],
661/// [`BitOrAssign`], [`BitAnd`], [`BitAndAssign`], [`BitXor`], [`BitXorAssign`],
662/// and [`Not`] traits - in addition to the Wasmtime-specific component ones
663/// [`ComponentType`], [`Lift`], and [`Lower`].
664///
665/// [`BitOr`]: std::ops::BitOr
666/// [`BitOrAssign`]: std::ops::BitOrAssign
667/// [`BitAnd`]: std::ops::BitAnd
668/// [`BitAndAssign`]: std::ops::BitAndAssign
669/// [`BitXor`]: std::ops::BitXor
670/// [`BitXorAssign`]: std::ops::BitXorAssign
671/// [`Not`]: std::ops::Not
672pub use wasmtime_component_macro::flags;
673
674#[cfg(any(docsrs, test, doctest))]
675pub mod bindgen_examples;
676
677// NB: needed for the links in the docs above to work in all `cargo doc`
678// configurations and avoid errors.
679#[cfg(not(any(docsrs, test, doctest)))]
680#[doc(hidden)]
681pub mod bindgen_examples {}