Skip to main content

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#![allow(
101    rustdoc::redundant_explicit_links,
102    reason = "rustdoc appears to lie about a warning above, so squelch it for now"
103)]
104
105mod component;
106#[cfg(feature = "component-model-async")]
107pub(crate) mod concurrent;
108mod func;
109mod has_data;
110mod instance;
111mod linker;
112mod matching;
113mod resource_table;
114mod resources;
115mod storage;
116pub(crate) mod store;
117pub mod types;
118mod values;
119pub use self::component::{Component, ComponentExportIndex, ExportLookup};
120#[cfg(feature = "task-group-hook")]
121pub use self::concurrent::TaskGroupHook;
122pub use self::concurrent::TaskGroupId;
123#[cfg(feature = "component-model-async")]
124pub use self::concurrent::{
125    Access, Accessor, AccessorTask, AsAccessor, Destination, DirectDestination, DirectSource,
126    ErrorContext, FuncCallConcurrent, FutureAny, FutureConsumer, FutureProducer, FutureReader,
127    GuardedFutureReader, GuardedStreamReader, JoinHandle, ReadBuffer, Source, StreamAny,
128    StreamConsumer, StreamProducer, StreamReader, StreamResult, TypedFuncCallConcurrent,
129    VMComponentAsyncStore, VecBuffer, WriteBuffer,
130};
131pub use self::func::{
132    ComponentNamedList, ComponentType, Func, Lift, Lower, TypedFunc, WasmList, WasmStr,
133};
134pub use self::has_data::*;
135pub use self::instance::{Instance, InstancePre};
136pub use self::linker::{Linker, LinkerInstance};
137pub use self::resource_table::{ResourceTable, ResourceTableError};
138pub use self::resources::{Resource, ResourceAny, ResourceDynamic};
139pub use self::types::{ResourceType, Type};
140pub use self::values::Val;
141
142pub(crate) use self::instance::RuntimeImport;
143pub(crate) use self::resources::HostResourceData;
144pub(crate) use self::store::{ComponentInstanceId, RuntimeInstance};
145
146// Re-export wasm_wave crate so the compatible version of this dep doesn't have to be
147// tracked separately from wasmtime.
148#[cfg(feature = "wave")]
149pub use wasm_wave;
150
151// Re-export wit-parser crate so the compatible version of this dep doesn't have to be
152// tracked separately from wasmtime.
153#[cfg(feature = "wit-parser")]
154pub use wit_parser;
155
156// These items are used by `#[derive(ComponentType, Lift, Lower)]`, but they are not part of
157// Wasmtime's API stability guarantees
158#[doc(hidden)]
159pub mod __internal {
160    pub use super::func::{
161        ComponentVariant, LiftContext, LowerContext, bad_type_info, format_flags, lower_payload,
162        typecheck_enum, typecheck_flags, typecheck_record, typecheck_variant,
163    };
164    pub use super::matching::InstanceType;
165    pub use crate::MaybeUninitExt;
166    pub use crate::map_maybe_uninit;
167    pub use crate::store::StoreOpaque;
168    pub use alloc::boxed::Box;
169    pub use alloc::string::String;
170    pub use alloc::vec::Vec;
171    pub use core::cell::RefCell;
172    pub use core::future::Future;
173    pub use core::mem::transmute;
174    pub use wasmtime_environ;
175    pub use wasmtime_environ::component::{CanonicalAbiInfo, ComponentTypes, InterfaceType};
176}
177
178pub(crate) use self::store::ComponentStoreData;
179
180/// Generate bindings for a [WIT world].
181///
182/// [WIT world]: https://component-model.bytecodealliance.org/design/worlds.html
183/// [WIT package]: https://component-model.bytecodealliance.org/design/packages.html
184///
185/// This macro ingests a [WIT world] and will generate all the necessary
186/// bindings for instantiating components that ascribe to the `world`. This
187/// provides a higher-level representation of working with a component than the
188/// raw [`Instance`] type which must be manually-type-checked and manually have
189/// its imports provided via the [`Linker`] type.
190///
191/// # Examples
192///
193/// Examples for this macro can be found in the [`bindgen_examples`] module
194/// documentation. That module has a submodule-per-example which includes the
195/// source code, with WIT, used to generate the structures along with the
196/// generated code itself in documentation.
197///
198/// # Debugging and Exploring
199///
200/// If you need to debug the output of `bindgen!` you can try using the
201/// `WASMTIME_DEBUG_BINDGEN=1` environment variable. This will write the
202/// generated code to a file on disk so rustc can produce better error messages
203/// against the actual generated source instead of the macro invocation itself.
204/// This additionally can enable opening up the generated code in an editor and
205/// exploring it (through an error message).
206///
207/// The generated bindings can additionally be explored with `cargo doc` to see
208/// what's generated. It's also recommended to browse the [`bindgen_examples`]
209/// for example generated structures and example generated code.
210///
211/// # Syntax
212///
213/// This procedural macro accepts a few different syntaxes. The primary purpose
214/// of this macro is to locate a WIT package, parse it, and then extract a
215/// `world` from the parsed package. There are then codegen-specific options to
216/// the bindings themselves which can additionally be specified.
217///
218/// Usage of this macro looks like:
219///
220/// ```rust
221/// # macro_rules! bindgen { ($($t:tt)*) => () }
222/// // Parse the `wit/` folder adjacent to this crate's `Cargo.toml` and look
223/// // for a single `world` in it. There must be exactly one for this to
224/// // succeed.
225/// bindgen!();
226///
227/// // Parse the `wit/` folder adjacent to this crate's `Cargo.toml` and look
228/// // for the world `foo` contained in it.
229/// bindgen!("foo");
230///
231/// // Parse the folder `other/wit/folder` adjacent to `Cargo.toml`.
232/// bindgen!(in "other/wit/folder");
233/// bindgen!("foo" in "other/wit/folder");
234///
235/// // Parse the file `foo.wit` as a single-file WIT package with no
236/// // dependencies.
237/// bindgen!("foo" in "foo.wit");
238///
239/// // Specify a suite of options to the bindings generation, documented below
240/// bindgen!({
241///     world: "foo",
242///     path: "other/path/to/wit",
243///     // ...
244/// });
245/// ```
246///
247/// # Options Reference
248///
249/// This is an example listing of all options that this macro supports along
250/// with documentation for each option and example syntax for each option.
251///
252/// ```rust
253/// # macro_rules! bindgen { ($($t:tt)*) => () }
254/// bindgen!({
255///     world: "foo", // not needed if `path` has one `world`
256///
257///     // same as in `bindgen!(in "other/wit/folder")
258///     path: "other/wit/folder",
259///
260///     // Instead of `path` the WIT document can be provided inline if
261///     // desired.
262///     inline: "
263///         package my:inline;
264///
265///         world foo {
266///             // ...
267///         }
268///     ",
269///
270///     // Further configuration of imported functions. This can be used to add
271///     // functionality per-function or by default for all imports. Note that
272///     // exports are also supported via the `exports` key below.
273///     //
274///     // Functions in this list are specified as their interface first then
275///     // the raw wasm name of the function. Interface versions can be
276///     // optionally omitted and prefixes are also supported to configure
277///     // entire interfaces at once for example. Only the first matching item
278///     // in this list is used to configure a function.
279///     //
280///     // Configuration for a function is a set of flags which can be added
281///     // per-function. Each flag's meaning is documented below and the final
282///     // set of flags for a function are calculated by the first matching
283///     // rule below unioned with the default flags inferred from the WIT
284///     // signature itself (unless below configures the `ignore_wit` flag).
285///     //
286///     // Specifically the defaults for a normal WIT function are empty,
287///     // meaning all flags below are disabled. For a WIT `async` function the
288///     // `async | store` flags are enabled by default, but all others are
289///     // still disabled.
290///     //
291///     // Note that unused keys in this map are a compile-time error. All
292///     // keys are required to be used and consulted.
293///     imports: {
294///         // The `async` flag is used to indicate that a Rust-level `async`
295///         // function is used on the host. This means that the host is allowed
296///         // to do async I/O. Note though that to WebAssembly itself the
297///         // function will still be blocking.
298///         "wasi:io/poll.poll": async,
299///
300///         // The `store` flag means that the host function will have access
301///         // to the store during its execution. By default host functions take
302///         // `&mut self` which only has access to the data in question
303///         // implementing the generated traits from `bindgen!`. This
304///         // configuration means that in addition to `Self` the entire store
305///         // will be accessible if necessary.
306///         //
307///         // Functions that have access to a `store` are generated in a
308///         // `HostWithStore` trait. Functions without a `store` are generated
309///         // in a `Host` trait.
310///         //
311///         // If the WIT function itself is `async`, then the function will
312///         // already have this flag and will take an `&Accessor<T, Self>`. If
313///         // the WIT function is not `async`, however, then the function will
314///         // take `Access<T, Self>`.
315///         "wasi:clocks/monotonic-clock.now": store,
316///
317///         // This is an example of combining flags where the `async` and
318///         // `store` flags are combined. This means that the generated
319///         // host function is both `async` and additionally has access to
320///         // the `store`. Note though that this configuration is not necessary
321///         // as the WIT function is itself already marked as `async`. That
322///         // means that this is the default already applied meaning that
323///         // specifying it here would be redundant.
324///         //
325///         // "wasi:clocks/monotonic-clock.wait-until": async | store,
326///
327///         // The `tracing` flag indicates that `tracing!` will be used to log
328///         // entries and exits into this host API. This can assist with
329///         // debugging or just generally be used to provide logs for the host.
330///         //
331///         // By default values are traced unless they contain lists, but
332///         // tracing of lists can be enabled with `verbose_tracing` below.
333///         "my:local/api.foo": tracing,
334///
335///         // The `verbose_tracing` flag indicates that when combined with
336///         // `tracing` the values of parameters/results are added to logs.
337///         // This may include lists which may be very large.
338///         "my:local/api.other-function": tracing | verbose_tracing,
339///
340///         // The `trappable` flag indicates that this import is allowed to
341///         // generate a trap.
342///         //
343///         // Imports that may trap have their return types wrapped in
344///         // `wasmtime::Result<T>` where the `Err` variant indicates that a
345///         // trap will be raised in the guest.
346///         //
347///         // By default imports cannot trap and the return value is the return
348///         // value from the WIT bindings itself.
349///         //
350///         // Note that the `trappable` configuration can be combined with the
351///         // `trappable_error_type` configuration below to avoid having a
352///         // host function return `wasmtime::Result<Result<WitOk, WitErr>>`
353///         // for example and instead return `Result<WitOk, RustErrorType>`.
354///         "my:local/api.fallible": trappable,
355///
356///         // The `exact` flag ensures that the filter, here "f", only matches
357///         // functions exactly. For example "f" here would only refer to
358///         // `import f: func()` in a world. Without this flag then "f"
359///         // would also configure any package `f:*/*/*` for example.
360///         "f": exact,
361///
362///         // This is used to configure the defaults of all functions if no
363///         // other key above matches a function. Note that if specific
364///         // functions mentioned above want these flags too then the flags
365///         // must be added there too because only one matching rule in this
366///         // map is used per-function.
367///         default: async | trappable,
368///     },
369///
370///     // Mostly the same as `imports` above, but applies to exported functions.
371///     //
372///     // The one difference here is that, whereas the `task_exit` flag has no
373///     // effect for `imports`, it changes how bindings are generated for
374///     // exported functions as described below.
375///     exports: {
376///         /* ... */
377///
378///         // The `task_exit` flag indicates that the generated binding for
379///         // this function should return a tuple of the result produced by the
380///         // callee and a `TaskExit` future which will resolve when the task
381///         // (and any transitively created subtasks) have exited.
382///         "my:local/api.does-stuff-after-returning": task_exit,
383///     },
384///
385///     // This can be used to translate WIT return values of the form
386///     // `result<T, error-type>` into `Result<T, RustErrorType>` in Rust.
387///     // Users must define `RustErrorType` and the `Host` trait for the
388///     // interface which defines `error-type` will have a method
389///     // called `convert_error_type` which converts `RustErrorType`
390///     // into `wasmtime::Result<ErrorType>`. This conversion can either
391///     // return the raw WIT error (`ErrorType` here) or a trap.
392///     //
393///     // By default this option is not specified. This option only takes
394///     // effect when `trappable` is set for some imports.
395///     trappable_error_type: {
396///         "wasi:io/streams.stream-error" => RustErrorType,
397///     },
398///
399///     // All generated bindgen types are "owned" meaning types like `String`
400///     // are used instead of `&str`, for example. This is the default and
401///     // ensures that the same type used in both imports and exports uses the
402///     // same generated type.
403///     ownership: Owning,
404///
405///     // Alternative to `Owning` above where borrowed types attempt to be used
406///     // instead. The `duplicate_if_necessary` configures whether duplicate
407///     // Rust types will be generated for the same WIT type if necessary, for
408///     // example when a type is used both as an import and an export.
409///     ownership: Borrowing {
410///         duplicate_if_necessary: true
411///     },
412///
413///     // Restrict the code generated to what's needed for the interface
414///     // imports in the inlined WIT document fragment.
415///     interfaces: "
416///         import wasi:cli/command;
417///     ",
418///
419///     // Remap imported interfaces or resources to types defined in Rust
420///     // elsewhere. Using this option will prevent any code from being
421///     // generated for interfaces mentioned here. Resources named here will
422///     // not have a type generated to represent the resource.
423///     //
424///     // Interfaces mapped with this option should be previously generated
425///     // with an invocation of this macro. Resources need to be mapped to a
426///     // Rust type name.
427///     with: {
428///         // This can be used to indicate that entire interfaces have
429///         // bindings generated elsewhere with a path pointing to the
430///         // bindinges-generated module.
431///         "wasi:random/random": wasmtime_wasi::p2::bindings::random::random,
432///
433///         // Similarly entire packages can also be specified.
434///         "wasi:cli": wasmtime_wasi::p2::bindings::cli,
435///
436///         // Or, if applicable, entire namespaces can additionally be mapped.
437///         "wasi": wasmtime_wasi::p2::bindings,
438///
439///         // Versions are supported if multiple versions are in play:
440///         "wasi:http/types@0.2.0": wasmtime_wasi_http::bindings::http::types,
441///         "wasi:http@0.2.0": wasmtime_wasi_http::bindings::http,
442///
443///         // The `with` key can also be used to specify the `T` used in
444///         // import bindings of `Resource<T>`. This can be done to configure
445///         // which typed resource shows up in generated bindings and can be
446///         // useful when working with the typed methods of `ResourceTable`.
447///         "wasi:filesystem/types.descriptor": MyDescriptorType,
448///     },
449///
450///     // Generate an additional set of "named imports" bindings for the listed
451///     // interfaces, used together with the component model's
452///     // `(implements "...")` annotation.
453///     //
454///     // For each interface listed here an extra `Host` trait is generated
455///     // under a top-level `named_imports` module (mirroring the interface's
456///     // normal module path) whose methods each take an additional first
457///     // argument: a reference to the host-chosen "id" type given as the value
458///     // (here `MyHandlerId`). Alongside the trait a reflection-based
459///     // `add_to_linker` is generated:
460///     //
461///     // ```ignore
462///     // fn add_to_linker<T, D>(
463///     //     linker: &mut Linker<T>,
464///     //     component: &Component,
465///     //     lookup: impl FnMut(&str) -> Result<MyHandlerId>,
466///     //     host_getter: fn(&mut T) -> D::Data<'_>,
467///     // ) -> Result<()>;
468///     // ```
469///     //
470///     // This inspects `component`'s imports, and for each one annotated with
471///     // `(implements "wasi:http/handler")` calls `lookup` with the import's
472///     // name to obtain an id. That id is then cloned into each linker closure
473///     // and passed as the first argument to every method call, letting a
474///     // single `Host` implementation distinguish between multiple imports
475///     // of the same interface.
476///     //
477///     // The id type must be `Clone + Send + Sync + 'static`. Interfaces that
478///     // define a resource are not supported here and cause a compile error.
479///     named_imports: {
480///         "wasi:http/handler": MyHandlerId,
481///     },
482///
483///     // Additional derive attributes to include on generated types (structs or enums).
484///     //
485///     // These are deduplicated and attached in a deterministic order.
486///     additional_derives: [
487///         Hash,
488///         serde::Deserialize,
489///         serde::Serialize,
490///     ],
491///
492///     // An niche configuration option to require that the `T` in `Store<T>`
493///     // is always `Send` in the generated bindings. Typically not needed
494///     // but if synchronous bindings depend on asynchronous bindings using
495///     // the `with` key then this may be required.
496///     require_store_data_send: false,
497///
498///     // If the `wasmtime` crate is depended on at a nonstandard location
499///     // or is renamed then this is the path to the root of the `wasmtime`
500///     // crate. Much of the generated code needs to refer to `wasmtime` so
501///     // this should be used if the `wasmtime` name is not wasmtime itself.
502///     //
503///     // By default this is `wasmtime`.
504///     wasmtime_crate: path::to::wasmtime,
505///
506///     // Whether to use `anyhow::Result` for trappable host-defined function
507///     // imports, rather than `wasmtime::Result`.
508///     //
509///     // By default, this is false and `wasmtime::Result` is used instead of
510///     // `anyhow::Result`.
511///     //
512///     // When enabled, the generated code requires the `"anyhow"` cargo feature
513///     // to also be enabled in the `wasmtime` crate.
514///     anyhow: false,
515///
516///     // This is an in-source alternative to using `WASMTIME_DEBUG_BINDGEN`.
517///     //
518///     // Note that if this option is specified then the compiler will always
519///     // recompile your bindings. Cargo records the start time of when rustc
520///     // is spawned by this will write a file during compilation. To Cargo
521///     // that looks like a file was modified after `rustc` was spawned,
522///     // so Cargo will always think your project is "dirty" and thus always
523///     // recompile it. Recompiling will then overwrite the file again,
524///     // starting the cycle anew. This is only recommended for debugging.
525///     //
526///     // This option defaults to false.
527///     include_generated_code_from_file: false,
528///
529///     // Whether to generate a `COMPONENT_TYPE` constant containing a
530///     // binary-encoded description of the WIT world that bindings
531///     // were generated for.
532///     //
533///     // This can be decoded with the `wit_parser::decoding::decode_world`
534///     // function to recover the WIT `Resolve` and `WorldId` used to
535///     // generate the bindings, for example to type-check components
536///     // against the world without keeping the original WIT files around.
537///     //
538///     // This option defaults to false as the encoded world adds a
539///     // nontrivial amount of data to the generated code.
540///     include_component_type: false,
541/// });
542/// ```
543pub use wasmtime_component_macro::bindgen;
544
545/// Derive macro to generate implementations of the [`ComponentType`] trait.
546///
547/// This derive macro can be applied to `struct` and `enum` definitions and is
548/// used to bind either a `record`, `enum`, or `variant` in the component model.
549///
550/// Note you might be looking for [`bindgen!`] rather than this macro as that
551/// will generate the entire type for you rather than just a trait
552/// implementation.
553///
554/// This macro supports a `#[component]` attribute which is used to customize
555/// how the type is bound to the component model. A top-level `#[component]`
556/// attribute is required to specify either `record`, `enum`, or `variant`.
557///
558/// ## Records
559///
560/// `record`s in the component model correspond to `struct`s in Rust. An example
561/// is:
562///
563/// ```rust
564/// use wasmtime::component::ComponentType;
565///
566/// #[derive(ComponentType)]
567/// #[component(record)]
568/// struct Color {
569///     r: u8,
570///     g: u8,
571///     b: u8,
572/// }
573/// ```
574///
575/// which corresponds to the WIT type:
576///
577/// ```wit
578/// record color {
579///     r: u8,
580///     g: u8,
581///     b: u8,
582/// }
583/// ```
584///
585/// Note that the name `Color` here does not need to match the name in WIT.
586/// That's purely used as a name in Rust of what to refer to. The field names
587/// must match that in WIT, however. Field names can be customized with the
588/// `#[component]` attribute though.
589///
590/// ```rust
591/// use wasmtime::component::ComponentType;
592///
593/// #[derive(ComponentType)]
594/// #[component(record)]
595/// struct VerboseColor {
596///     #[component(name = "r")]
597///     red: u8,
598///     #[component(name = "g")]
599///     green: u8,
600///     #[component(name = "b")]
601///     blue: u8,
602/// }
603/// ```
604///
605/// Also note that field ordering is significant at this time and must match
606/// WIT.
607///
608/// ## Variants
609///
610/// `variant`s in the component model correspond to a subset of shapes of a Rust
611/// `enum`. Variants in the component model have a single optional payload type
612/// which means that not all Rust `enum`s correspond to component model
613/// `variant`s. An example variant is:
614///
615/// ```rust
616/// use wasmtime::component::ComponentType;
617///
618/// #[derive(ComponentType)]
619/// #[component(variant)]
620/// enum Filter {
621///     #[component(name = "none")]
622///     None,
623///     #[component(name = "all")]
624///     All,
625///     #[component(name = "some")]
626///     Some(Vec<String>),
627/// }
628/// ```
629///
630/// which corresponds to the WIT type:
631///
632/// ```wit
633/// variant filter {
634///     none,
635///     all,
636///     some(list<string>),
637/// }
638/// ```
639///
640/// The `variant` style of derive allows an optional payload on Rust `enum`
641/// variants but it must be a single unnamed field. Variants of the form `Foo(T,
642/// U)` or `Foo { name: T }` are not supported at this time.
643///
644/// Note that the order of variants in Rust must match the order of variants in
645/// WIT. Additionally it's likely that `#[component(name = "...")]` is required
646/// on all Rust `enum` variants because the name currently defaults to the Rust
647/// name which is typically UpperCamelCase whereas WIT uses kebab-case.
648///
649/// ## Enums
650///
651/// `enum`s in the component model correspond to C-like `enum`s in Rust. Note
652/// that a component model `enum` does not allow any payloads so the Rust `enum`
653/// must additionally have no payloads.
654///
655/// ```rust
656/// use wasmtime::component::ComponentType;
657///
658/// #[derive(ComponentType)]
659/// #[component(enum)]
660/// #[repr(u8)]
661/// enum Setting {
662///     #[component(name = "yes")]
663///     Yes,
664///     #[component(name = "no")]
665///     No,
666///     #[component(name = "auto")]
667///     Auto,
668/// }
669/// ```
670///
671/// which corresponds to the WIT type:
672///
673/// ```wit
674/// enum setting {
675///     yes,
676///     no,
677///     auto,
678/// }
679/// ```
680///
681/// Note that the order of variants in Rust must match the order of variants in
682/// WIT. Additionally it's likely that `#[component(name = "...")]` is required
683/// on all Rust `enum` variants because the name currently defaults to the Rust
684/// name which is typically UpperCamelCase whereas WIT uses kebab-case.
685pub use wasmtime_component_macro::ComponentType;
686
687/// A derive macro for generating implementations of the [`Lift`] trait.
688///
689/// This macro will likely be applied in conjunction with the
690/// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
691/// of `#[derive(ComponentType, Lift)]`. This trait enables reading values from
692/// WebAssembly.
693///
694/// Note you might be looking for [`bindgen!`] rather than this macro as that
695/// will generate the entire type for you rather than just a trait
696/// implementation.
697///
698/// At this time this derive macro has no configuration.
699///
700/// ## Examples
701///
702/// ```rust
703/// use wasmtime::component::{ComponentType, Lift};
704///
705/// #[derive(ComponentType, Lift)]
706/// #[component(record)]
707/// struct Color {
708///     r: u8,
709///     g: u8,
710///     b: u8,
711/// }
712/// ```
713pub use wasmtime_component_macro::Lift;
714
715/// A derive macro for generating implementations of the [`Lower`] trait.
716///
717/// This macro will likely be applied in conjunction with the
718/// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
719/// of `#[derive(ComponentType, Lower)]`. This trait enables passing values to
720/// WebAssembly.
721///
722/// Note you might be looking for [`bindgen!`] rather than this macro as that
723/// will generate the entire type for you rather than just a trait
724/// implementation.
725///
726/// At this time this derive macro has no configuration.
727///
728/// ## Examples
729///
730/// ```rust
731/// use wasmtime::component::{ComponentType, Lower};
732///
733/// #[derive(ComponentType, Lower)]
734/// #[component(record)]
735/// struct Color {
736///     r: u8,
737///     g: u8,
738///     b: u8,
739/// }
740/// ```
741pub use wasmtime_component_macro::Lower;
742
743/// A macro to generate a Rust type corresponding to WIT `flags`
744///
745/// This macro generates a type that implements the [`ComponentType`], [`Lift`],
746/// and [`Lower`] traits. The generated Rust type corresponds to the `flags`
747/// type in WIT.
748///
749/// Example usage of this looks like:
750///
751/// ```rust
752/// use wasmtime::component::flags;
753///
754/// flags! {
755///     Permissions {
756///         #[component(name = "read")]
757///         const READ;
758///         #[component(name = "write")]
759///         const WRITE;
760///         #[component(name = "execute")]
761///         const EXECUTE;
762///     }
763/// }
764///
765/// fn validate_permissions(permissions: &mut Permissions) {
766///     if permissions.contains(Permissions::EXECUTE | Permissions::WRITE) {
767///         panic!("cannot enable both writable and executable at the same time");
768///     }
769///
770///     if permissions.contains(Permissions::READ) {
771///         panic!("permissions must at least contain read");
772///     }
773/// }
774/// ```
775///
776/// which corresponds to the WIT type:
777///
778/// ```wit
779/// flags permissions {
780///     read,
781///     write,
782///     execute,
783/// }
784/// ```
785///
786/// This generates a structure which is similar to/inspired by the [`bitflags`
787/// crate](https://crates.io/crates/bitflags). The `Permissions` structure
788/// generated implements the [`PartialEq`], [`Eq`], [`Debug`], [`BitOr`],
789/// [`BitOrAssign`], [`BitAnd`], [`BitAndAssign`], [`BitXor`], [`BitXorAssign`],
790/// and [`Not`] traits - in addition to the Wasmtime-specific component ones
791/// [`ComponentType`], [`Lift`], and [`Lower`].
792///
793/// [`BitOr`]: std::ops::BitOr
794/// [`BitOrAssign`]: std::ops::BitOrAssign
795/// [`BitAnd`]: std::ops::BitAnd
796/// [`BitAndAssign`]: std::ops::BitAndAssign
797/// [`BitXor`]: std::ops::BitXor
798/// [`BitXorAssign`]: std::ops::BitXorAssign
799/// [`Not`]: std::ops::Not
800pub use wasmtime_component_macro::flags;
801
802#[cfg(any(docsrs, test, doctest))]
803pub mod bindgen_examples;
804
805// NB: needed for the links in the docs above to work in all `cargo doc`
806// configurations and avoid errors.
807#[cfg(not(any(docsrs, test, doctest)))]
808#[doc(hidden)]
809pub mod bindgen_examples {}
810
811#[cfg(not(feature = "component-model-async"))]
812pub(crate) mod concurrent_disabled;
813
814#[cfg(not(feature = "component-model-async"))]
815pub(crate) use concurrent_disabled as concurrent;