Skip to main content

wasmtime/runtime/component/
mod.rs

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