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