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///         // If the WIT function itself is `async`, then the function will
309///         // already have this flag and will take an `&Accessor<T, Self>`. If
310///         // the WIT function is not `async`, however, then the function will
311///         // take `Access<T, Self>`.
312///         "wasi:clocks/monotonic-clock.now": store,
313///
314///         // This is an example of combining flags where the `async` and
315///         // `store` flags are combined. This means that the generated
316///         // host function is both `async` and additionally has access to
317///         // the `store`. Note though that this configuration is not necessary
318///         // as the WIT function is itself already marked as `async`. That
319///         // means that this is the default already applied meaning that
320///         // specifying it here would be redundant.
321///         //
322///         // "wasi:clocks/monotonic-clock.wait-until": async | store,
323///
324///         // The `tracing` flag indicates that `tracing!` will be used to log
325///         // entries and exits into this host API. This can assist with
326///         // debugging or just generally be used to provide logs for the host.
327///         //
328///         // By default values are traced unless they contain lists, but
329///         // tracing of lists can be enabled with `verbose_tracing` below.
330///         "my:local/api.foo": tracing,
331///
332///         // The `verbose_tracing` flag indicates that when combined with
333///         // `tracing` the values of parameters/results are added to logs.
334///         // This may include lists which may be very large.
335///         "my:local/api.other-function": tracing | verbose_tracing,
336///
337///         // The `trappable` flag indicates that this import is allowed to
338///         // generate a trap.
339///         //
340///         // Imports that may trap have their return types wrapped in
341///         // `wasmtime::Result<T>` where the `Err` variant indicates that a
342///         // trap will be raised in the guest.
343///         //
344///         // By default imports cannot trap and the return value is the return
345///         // value from the WIT bindings itself.
346///         //
347///         // Note that the `trappable` configuration can be combined with the
348///         // `trappable_error_type` configuration below to avoid having a
349///         // host function return `wasmtime::Result<Result<WitOk, WitErr>>`
350///         // for example and instead return `Result<WitOk, RustErrorType>`.
351///         "my:local/api.fallible": trappable,
352///
353///         // The `exact` flag ensures that the filter, here "f", only matches
354///         // functions exactly. For example "f" here would only refer to
355///         // `import f: func()` in a world. Without this flag then "f"
356///         // would also configure any package `f:*/*/*` for example.
357///         "f": exact,
358///
359///         // This is used to configure the defaults of all functions if no
360///         // other key above matches a function. Note that if specific
361///         // functions mentioned above want these flags too then the flags
362///         // must be added there too because only one matching rule in this
363///         // map is used per-function.
364///         default: async | trappable,
365///     },
366///
367///     // Mostly the same as `imports` above, but applies to exported functions.
368///     //
369///     // The one difference here is that, whereas the `task_exit` flag has no
370///     // effect for `imports`, it changes how bindings are generated for
371///     // exported functions as described below.
372///     exports: {
373///         /* ... */
374///
375///         // The `task_exit` flag indicates that the generated binding for
376///         // this function should return a tuple of the result produced by the
377///         // callee and a `TaskExit` future which will resolve when the task
378///         // (and any transitively created subtasks) have exited.
379///         "my:local/api.does-stuff-after-returning": task_exit,
380///     },
381///
382///     // This can be used to translate WIT return values of the form
383///     // `result<T, error-type>` into `Result<T, RustErrorType>` in Rust.
384///     // Users must define `RustErrorType` and the `Host` trait for the
385///     // interface which defines `error-type` will have a method
386///     // called `convert_error_type` which converts `RustErrorType`
387///     // into `wasmtime::Result<ErrorType>`. This conversion can either
388///     // return the raw WIT error (`ErrorType` here) or a trap.
389///     //
390///     // By default this option is not specified. This option only takes
391///     // effect when `trappable` is set for some imports.
392///     trappable_error_type: {
393///         "wasi:io/streams.stream-error" => RustErrorType,
394///     },
395///
396///     // All generated bindgen types are "owned" meaning types like `String`
397///     // are used instead of `&str`, for example. This is the default and
398///     // ensures that the same type used in both imports and exports uses the
399///     // same generated type.
400///     ownership: Owning,
401///
402///     // Alternative to `Owning` above where borrowed types attempt to be used
403///     // instead. The `duplicate_if_necessary` configures whether duplicate
404///     // Rust types will be generated for the same WIT type if necessary, for
405///     // example when a type is used both as an import and an export.
406///     ownership: Borrowing {
407///         duplicate_if_necessary: true
408///     },
409///
410///     // Restrict the code generated to what's needed for the interface
411///     // imports in the inlined WIT document fragment.
412///     interfaces: "
413///         import wasi:cli/command;
414///     ",
415///
416///     // Remap imported interfaces or resources to types defined in Rust
417///     // elsewhere. Using this option will prevent any code from being
418///     // generated for interfaces mentioned here. Resources named here will
419///     // not have a type generated to represent the resource.
420///     //
421///     // Interfaces mapped with this option should be previously generated
422///     // with an invocation of this macro. Resources need to be mapped to a
423///     // Rust type name.
424///     with: {
425///         // This can be used to indicate that entire interfaces have
426///         // bindings generated elsewhere with a path pointing to the
427///         // bindinges-generated module.
428///         "wasi:random/random": wasmtime_wasi::p2::bindings::random::random,
429///
430///         // Similarly entire packages can also be specified.
431///         "wasi:cli": wasmtime_wasi::p2::bindings::cli,
432///
433///         // Or, if applicable, entire namespaces can additionally be mapped.
434///         "wasi": wasmtime_wasi::p2::bindings,
435///
436///         // Versions are supported if multiple versions are in play:
437///         "wasi:http/types@0.2.0": wasmtime_wasi_http::bindings::http::types,
438///         "wasi:http@0.2.0": wasmtime_wasi_http::bindings::http,
439///
440///         // The `with` key can also be used to specify the `T` used in
441///         // import bindings of `Resource<T>`. This can be done to configure
442///         // which typed resource shows up in generated bindings and can be
443///         // useful when working with the typed methods of `ResourceTable`.
444///         "wasi:filesystem/types.descriptor": MyDescriptorType,
445///     },
446///
447///     // Generate an additional set of "named imports" bindings for the listed
448///     // interfaces, used together with the component model's
449///     // `(implements "...")` annotation.
450///     //
451///     // For each interface listed here an extra `Host` trait is generated
452///     // under a top-level `named_imports` module (mirroring the interface's
453///     // normal module path) whose methods each take an additional first
454///     // argument: a reference to the host-chosen "id" type given as the value
455///     // (here `MyHandlerId`). Alongside the trait a reflection-based
456///     // `add_to_linker` is generated:
457///     //
458///     // ```ignore
459///     // fn add_to_linker<T, D>(
460///     //     linker: &mut Linker<T>,
461///     //     component: &Component,
462///     //     lookup: impl FnMut(&str) -> Result<MyHandlerId>,
463///     //     host_getter: fn(&mut T) -> D::Data<'_>,
464///     // ) -> Result<()>;
465///     // ```
466///     //
467///     // This inspects `component`'s imports, and for each one annotated with
468///     // `(implements "wasi:http/handler")` calls `lookup` with the import's
469///     // name to obtain an id. That id is then cloned into each linker closure
470///     // and passed as the first argument to every method call, letting a
471///     // single `Host` implementation distinguish between multiple imports
472///     // of the same interface.
473///     //
474///     // The id type must be `Clone + Send + Sync + 'static`. Interfaces that
475///     // define a resource are not supported here and cause a compile error.
476///     named_imports: {
477///         "wasi:http/handler": MyHandlerId,
478///     },
479///
480///     // Additional derive attributes to include on generated types (structs or enums).
481///     //
482///     // These are deduplicated and attached in a deterministic order.
483///     additional_derives: [
484///         Hash,
485///         serde::Deserialize,
486///         serde::Serialize,
487///     ],
488///
489///     // An niche configuration option to require that the `T` in `Store<T>`
490///     // is always `Send` in the generated bindings. Typically not needed
491///     // but if synchronous bindings depend on asynchronous bindings using
492///     // the `with` key then this may be required.
493///     require_store_data_send: false,
494///
495///     // If the `wasmtime` crate is depended on at a nonstandard location
496///     // or is renamed then this is the path to the root of the `wasmtime`
497///     // crate. Much of the generated code needs to refer to `wasmtime` so
498///     // this should be used if the `wasmtime` name is not wasmtime itself.
499///     //
500///     // By default this is `wasmtime`.
501///     wasmtime_crate: path::to::wasmtime,
502///
503///     // Whether to use `anyhow::Result` for trappable host-defined function
504///     // imports, rather than `wasmtime::Result`.
505///     //
506///     // By default, this is false and `wasmtime::Result` is used instead of
507///     // `anyhow::Result`.
508///     //
509///     // When enabled, the generated code requires the `"anyhow"` cargo feature
510///     // to also be enabled in the `wasmtime` crate.
511///     anyhow: false,
512///
513///     // This is an in-source alternative to using `WASMTIME_DEBUG_BINDGEN`.
514///     //
515///     // Note that if this option is specified then the compiler will always
516///     // recompile your bindings. Cargo records the start time of when rustc
517///     // is spawned by this will write a file during compilation. To Cargo
518///     // that looks like a file was modified after `rustc` was spawned,
519///     // so Cargo will always think your project is "dirty" and thus always
520///     // recompile it. Recompiling will then overwrite the file again,
521///     // starting the cycle anew. This is only recommended for debugging.
522///     //
523///     // This option defaults to false.
524///     include_generated_code_from_file: false,
525/// });
526/// ```
527pub use wasmtime_component_macro::bindgen;
528
529/// Derive macro to generate implementations of the [`ComponentType`] trait.
530///
531/// This derive macro can be applied to `struct` and `enum` definitions and is
532/// used to bind either a `record`, `enum`, or `variant` in the component model.
533///
534/// Note you might be looking for [`bindgen!`] rather than this macro as that
535/// will generate the entire type for you rather than just a trait
536/// implementation.
537///
538/// This macro supports a `#[component]` attribute which is used to customize
539/// how the type is bound to the component model. A top-level `#[component]`
540/// attribute is required to specify either `record`, `enum`, or `variant`.
541///
542/// ## Records
543///
544/// `record`s in the component model correspond to `struct`s in Rust. An example
545/// is:
546///
547/// ```rust
548/// use wasmtime::component::ComponentType;
549///
550/// #[derive(ComponentType)]
551/// #[component(record)]
552/// struct Color {
553///     r: u8,
554///     g: u8,
555///     b: u8,
556/// }
557/// ```
558///
559/// which corresponds to the WIT type:
560///
561/// ```wit
562/// record color {
563///     r: u8,
564///     g: u8,
565///     b: u8,
566/// }
567/// ```
568///
569/// Note that the name `Color` here does not need to match the name in WIT.
570/// That's purely used as a name in Rust of what to refer to. The field names
571/// must match that in WIT, however. Field names can be customized with the
572/// `#[component]` attribute though.
573///
574/// ```rust
575/// use wasmtime::component::ComponentType;
576///
577/// #[derive(ComponentType)]
578/// #[component(record)]
579/// struct VerboseColor {
580///     #[component(name = "r")]
581///     red: u8,
582///     #[component(name = "g")]
583///     green: u8,
584///     #[component(name = "b")]
585///     blue: u8,
586/// }
587/// ```
588///
589/// Also note that field ordering is significant at this time and must match
590/// WIT.
591///
592/// ## Variants
593///
594/// `variant`s in the component model correspond to a subset of shapes of a Rust
595/// `enum`. Variants in the component model have a single optional payload type
596/// which means that not all Rust `enum`s correspond to component model
597/// `variant`s. An example variant is:
598///
599/// ```rust
600/// use wasmtime::component::ComponentType;
601///
602/// #[derive(ComponentType)]
603/// #[component(variant)]
604/// enum Filter {
605///     #[component(name = "none")]
606///     None,
607///     #[component(name = "all")]
608///     All,
609///     #[component(name = "some")]
610///     Some(Vec<String>),
611/// }
612/// ```
613///
614/// which corresponds to the WIT type:
615///
616/// ```wit
617/// variant filter {
618///     none,
619///     all,
620///     some(list<string>),
621/// }
622/// ```
623///
624/// The `variant` style of derive allows an optional payload on Rust `enum`
625/// variants but it must be a single unnamed field. Variants of the form `Foo(T,
626/// U)` or `Foo { name: T }` are not supported at this time.
627///
628/// Note that the order of variants in Rust must match the order of variants in
629/// WIT. Additionally it's likely that `#[component(name = "...")]` is required
630/// on all Rust `enum` variants because the name currently defaults to the Rust
631/// name which is typically UpperCamelCase whereas WIT uses kebab-case.
632///
633/// ## Enums
634///
635/// `enum`s in the component model correspond to C-like `enum`s in Rust. Note
636/// that a component model `enum` does not allow any payloads so the Rust `enum`
637/// must additionally have no payloads.
638///
639/// ```rust
640/// use wasmtime::component::ComponentType;
641///
642/// #[derive(ComponentType)]
643/// #[component(enum)]
644/// #[repr(u8)]
645/// enum Setting {
646///     #[component(name = "yes")]
647///     Yes,
648///     #[component(name = "no")]
649///     No,
650///     #[component(name = "auto")]
651///     Auto,
652/// }
653/// ```
654///
655/// which corresponds to the WIT type:
656///
657/// ```wit
658/// enum setting {
659///     yes,
660///     no,
661///     auto,
662/// }
663/// ```
664///
665/// Note that the order of variants in Rust must match the order of variants in
666/// WIT. Additionally it's likely that `#[component(name = "...")]` is required
667/// on all Rust `enum` variants because the name currently defaults to the Rust
668/// name which is typically UpperCamelCase whereas WIT uses kebab-case.
669pub use wasmtime_component_macro::ComponentType;
670
671/// A derive macro for generating implementations of the [`Lift`] trait.
672///
673/// This macro will likely be applied in conjunction with the
674/// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
675/// of `#[derive(ComponentType, Lift)]`. This trait enables reading values from
676/// WebAssembly.
677///
678/// Note you might be looking for [`bindgen!`] rather than this macro as that
679/// will generate the entire type for you rather than just a trait
680/// implementation.
681///
682/// At this time this derive macro has no configuration.
683///
684/// ## Examples
685///
686/// ```rust
687/// use wasmtime::component::{ComponentType, Lift};
688///
689/// #[derive(ComponentType, Lift)]
690/// #[component(record)]
691/// struct Color {
692///     r: u8,
693///     g: u8,
694///     b: u8,
695/// }
696/// ```
697pub use wasmtime_component_macro::Lift;
698
699/// A derive macro for generating implementations of the [`Lower`] trait.
700///
701/// This macro will likely be applied in conjunction with the
702/// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
703/// of `#[derive(ComponentType, Lower)]`. This trait enables passing values to
704/// WebAssembly.
705///
706/// Note you might be looking for [`bindgen!`] rather than this macro as that
707/// will generate the entire type for you rather than just a trait
708/// implementation.
709///
710/// At this time this derive macro has no configuration.
711///
712/// ## Examples
713///
714/// ```rust
715/// use wasmtime::component::{ComponentType, Lower};
716///
717/// #[derive(ComponentType, Lower)]
718/// #[component(record)]
719/// struct Color {
720///     r: u8,
721///     g: u8,
722///     b: u8,
723/// }
724/// ```
725pub use wasmtime_component_macro::Lower;
726
727/// A macro to generate a Rust type corresponding to WIT `flags`
728///
729/// This macro generates a type that implements the [`ComponentType`], [`Lift`],
730/// and [`Lower`] traits. The generated Rust type corresponds to the `flags`
731/// type in WIT.
732///
733/// Example usage of this looks like:
734///
735/// ```rust
736/// use wasmtime::component::flags;
737///
738/// flags! {
739///     Permissions {
740///         #[component(name = "read")]
741///         const READ;
742///         #[component(name = "write")]
743///         const WRITE;
744///         #[component(name = "execute")]
745///         const EXECUTE;
746///     }
747/// }
748///
749/// fn validate_permissions(permissions: &mut Permissions) {
750///     if permissions.contains(Permissions::EXECUTE | Permissions::WRITE) {
751///         panic!("cannot enable both writable and executable at the same time");
752///     }
753///
754///     if permissions.contains(Permissions::READ) {
755///         panic!("permissions must at least contain read");
756///     }
757/// }
758/// ```
759///
760/// which corresponds to the WIT type:
761///
762/// ```wit
763/// flags permissions {
764///     read,
765///     write,
766///     execute,
767/// }
768/// ```
769///
770/// This generates a structure which is similar to/inspired by the [`bitflags`
771/// crate](https://crates.io/crates/bitflags). The `Permissions` structure
772/// generated implements the [`PartialEq`], [`Eq`], [`Debug`], [`BitOr`],
773/// [`BitOrAssign`], [`BitAnd`], [`BitAndAssign`], [`BitXor`], [`BitXorAssign`],
774/// and [`Not`] traits - in addition to the Wasmtime-specific component ones
775/// [`ComponentType`], [`Lift`], and [`Lower`].
776///
777/// [`BitOr`]: std::ops::BitOr
778/// [`BitOrAssign`]: std::ops::BitOrAssign
779/// [`BitAnd`]: std::ops::BitAnd
780/// [`BitAndAssign`]: std::ops::BitAndAssign
781/// [`BitXor`]: std::ops::BitXor
782/// [`BitXorAssign`]: std::ops::BitXorAssign
783/// [`Not`]: std::ops::Not
784pub use wasmtime_component_macro::flags;
785
786#[cfg(any(docsrs, test, doctest))]
787pub mod bindgen_examples;
788
789// NB: needed for the links in the docs above to work in all `cargo doc`
790// configurations and avoid errors.
791#[cfg(not(any(docsrs, test, doctest)))]
792#[doc(hidden)]
793pub mod bindgen_examples {}
794
795#[cfg(not(feature = "component-model-async"))]
796pub(crate) mod concurrent_disabled;
797
798#[cfg(not(feature = "component-model-async"))]
799pub(crate) use concurrent_disabled as concurrent;