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