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