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