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 // rustdoc appears to lie about a warning above, so squelch it for now.
101 #![allow(rustdoc::redundant_explicit_links)]
102 
103 mod component;
104 mod func;
105 mod instance;
106 mod linker;
107 mod matching;
108 mod resource_table;
109 mod resources;
110 mod storage;
111 mod store;
112 pub mod types;
113 mod values;
114 pub use self::component::Component;
115 pub use self::func::{
116     ComponentNamedList, ComponentType, Func, Lift, Lower, TypedFunc, WasmList, WasmStr,
117 };
118 pub use self::instance::{ExportInstance, Exports, Instance, InstancePre};
119 pub use self::linker::{Linker, LinkerInstance};
120 pub use self::resource_table::{ResourceTable, ResourceTableError};
121 pub use self::resources::{Resource, ResourceAny};
122 pub use self::types::{ResourceType, Type};
123 pub use self::values::Val;
124 
125 pub(crate) use self::resources::HostResourceData;
126 
127 // These items are expected to be used by an eventual
128 // `#[derive(ComponentType)]`, they are not part of Wasmtime's API stability
129 // guarantees
130 #[doc(hidden)]
131 pub mod __internal {
132     pub use super::func::{
133         bad_type_info, format_flags, lower_payload, typecheck_enum, typecheck_flags,
134         typecheck_record, typecheck_variant, ComponentVariant, LiftContext, LowerContext,
135         MaybeUninitExt, Options,
136     };
137     pub use super::matching::InstanceType;
138     pub use crate::map_maybe_uninit;
139     pub use crate::store::StoreOpaque;
140     pub use alloc::boxed::Box;
141     pub use alloc::string::String;
142     pub use alloc::vec::Vec;
143     pub use anyhow;
144     #[cfg(feature = "async")]
145     pub use async_trait::async_trait;
146     pub use wasmtime_environ;
147     pub use wasmtime_environ::component::{CanonicalAbiInfo, ComponentTypes, InterfaceType};
148 }
149 
150 pub(crate) use self::store::ComponentStoreData;
151 
152 /// Generate bindings for a [WIT world].
153 ///
154 /// [WIT world]: https://component-model.bytecodealliance.org/design/worlds.html
155 /// [WIT package]: https://component-model.bytecodealliance.org/design/packages.html
156 ///
157 /// This macro ingests a [WIT world] and will generate all the necessary
158 /// bindings for instantiating components that ascribe to the `world`. This
159 /// provides a higher-level representation of working with a component than the
160 /// raw [`Instance`] type which must be manually-type-checked and manually have
161 /// its imports provided via the [`Linker`] type.
162 ///
163 /// The most basic usage of this macro is:
164 ///
165 /// ```rust,ignore
166 /// wasmtime::component::bindgen!();
167 /// ```
168 ///
169 /// This will parse your projects [WIT package] in a `wit` directory adjacent to
170 /// your crate's `Cargo.toml`. All of the `*.wit` files in that directory are
171 /// parsed and then the single `world` found will be used for bindings.
172 ///
173 /// For example if your project contained:
174 ///
175 /// ```text,ignore
176 /// // wit/my-component.wit
177 ///
178 /// package my:project;
179 ///
180 /// world hello-world {
181 ///     import name: func() -> string;
182 ///     export greet: func();
183 /// }
184 /// ```
185 ///
186 /// Then you can interact with the generated bindings like so:
187 ///
188 /// ```rust
189 /// use wasmtime::component::*;
190 /// use wasmtime::{Config, Engine, Store};
191 ///
192 /// # const _: () = { macro_rules! bindgen { () => () }
193 /// bindgen!();
194 /// # };
195 /// # bindgen!({
196 /// #   inline: r#"
197 /// #       package my:project;
198 /// #       world hello-world {
199 /// #           import name: func() -> string;
200 /// #           export greet: func();
201 /// #       }
202 /// #   "#,
203 /// # });
204 ///
205 /// struct MyState {
206 ///     name: String,
207 /// }
208 ///
209 /// // Imports into the world, like the `name` import for this world, are
210 /// // satisfied through traits.
211 /// impl HelloWorldImports for MyState {
212 ///     // Note the `Result` return value here where `Ok` is returned back to
213 ///     // the component and `Err` will raise a trap.
214 ///     fn name(&mut self) -> String {
215 ///         self.name.clone()
216 ///     }
217 /// }
218 ///
219 /// fn main() -> wasmtime::Result<()> {
220 /// #   if true { return Ok(()) }
221 ///     // Configure an `Engine` and compile the `Component` that is being run for
222 ///     // the application.
223 ///     let mut config = Config::new();
224 ///     config.wasm_component_model(true);
225 ///     let engine = Engine::new(&config)?;
226 ///     let component = Component::from_file(&engine, "./your-component.wasm")?;
227 ///
228 ///     // Instantiation of bindings always happens through a `Linker`.
229 ///     // Configuration of the linker is done through a generated `add_to_linker`
230 ///     // method on the bindings structure.
231 ///     //
232 ///     // Note that the closure provided here is a projection from `T` in
233 ///     // `Store<T>` to `&mut U` where `U` implements the `HelloWorldImports`
234 ///     // trait. In this case the `T`, `MyState`, is stored directly in the
235 ///     // structure so no projection is necessary here.
236 ///     let mut linker = Linker::new(&engine);
237 ///     HelloWorld::add_to_linker(&mut linker, |state: &mut MyState| state)?;
238 ///
239 ///     // As with the core wasm API of Wasmtime instantiation occurs within a
240 ///     // `Store`. The bindings structure contains an `instantiate` method which
241 ///     // takes the store, component, and linker. This returns the `bindings`
242 ///     // structure which is an instance of `HelloWorld` and supports typed access
243 ///     // to the exports of the component.
244 ///     let mut store = Store::new(
245 ///         &engine,
246 ///         MyState {
247 ///             name: "me".to_string(),
248 ///         },
249 ///     );
250 ///     let (bindings, _) = HelloWorld::instantiate(&mut store, &component, &linker)?;
251 ///
252 ///     // Here our `greet` function doesn't take any parameters for the component,
253 ///     // but in the Wasmtime embedding API the first argument is always a `Store`.
254 ///     bindings.call_greet(&mut store)?;
255 ///     Ok(())
256 /// }
257 /// ```
258 ///
259 /// The function signatures within generated traits and on generated exports
260 /// match the component-model signatures as specified in the WIT `world` item.
261 /// Note that WIT also has support for importing and exports interfaces within
262 /// worlds, which can be bound here as well:
263 ///
264 /// For example this WIT input
265 ///
266 /// ```text,ignore
267 /// // wit/my-component.wit
268 ///
269 /// package my:project;
270 ///
271 /// interface host {
272 ///     gen-random-integer: func() -> u32;
273 ///     sha256: func(bytes: list<u8>) -> string;
274 /// }
275 ///
276 /// world hello-world {
277 ///     import host;
278 ///
279 ///     export demo: interface {
280 ///         run: func();
281 ///     }
282 /// }
283 /// ```
284 ///
285 /// Then you can interact with the generated bindings like so:
286 ///
287 /// ```rust
288 /// use wasmtime::component::*;
289 /// use wasmtime::{Config, Engine, Store};
290 /// use my::project::host::Host;
291 ///
292 /// # const _: () = { macro_rules! bindgen { () => () }
293 /// bindgen!();
294 /// # };
295 /// # bindgen!({
296 /// #   inline: r#"
297 /// # package my:project;
298 /// #
299 /// # interface host {
300 /// #     gen-random-integer: func() -> u32;
301 /// #     sha256: func(bytes: list<u8>) -> string;
302 /// # }
303 /// #
304 /// # world hello-world {
305 /// #     import host;
306 /// #
307 /// #     export demo: interface {
308 /// #         run: func();
309 /// #     }
310 /// # }
311 /// #   "#,
312 /// # });
313 ///
314 /// struct MyState {
315 ///     // ...
316 /// }
317 ///
318 /// // Note that the trait here is per-interface and within a submodule now.
319 /// impl Host for MyState {
320 ///     fn gen_random_integer(&mut self) -> u32 {
321 /// #       panic!();
322 /// #       #[cfg(FALSE)]
323 ///         rand::thread_rng().gen()
324 ///     }
325 ///
326 ///     fn sha256(&mut self, bytes: Vec<u8>) -> String {
327 ///         // ...
328 /// #       panic!()
329 ///     }
330 /// }
331 ///
332 /// fn main() -> wasmtime::Result<()> {
333 /// #   if true { return Ok(()) }
334 ///     let mut config = Config::new();
335 ///     config.wasm_component_model(true);
336 ///     let engine = Engine::new(&config)?;
337 ///     let component = Component::from_file(&engine, "./your-component.wasm")?;
338 ///
339 ///     let mut linker = Linker::new(&engine);
340 ///     HelloWorld::add_to_linker(&mut linker, |state: &mut MyState| state)?;
341 ///
342 ///     let mut store = Store::new(
343 ///         &engine,
344 ///         MyState { /* ... */ },
345 ///     );
346 ///     let (bindings, _) = HelloWorld::instantiate(&mut store, &component, &linker)?;
347 ///
348 ///     // Note that the `demo` method returns a `&Demo` through which we can
349 ///     // run the methods on that interface.
350 ///     bindings.demo().call_run(&mut store)?;
351 ///     Ok(())
352 /// }
353 /// ```
354 ///
355 /// The generated bindings can additionally be explored more fully with `cargo
356 /// doc` to see what types and traits and such are generated.
357 ///
358 /// # Syntax
359 ///
360 /// This procedural macro accepts a few different syntaxes. The primary purpose
361 /// of this macro is to locate a WIT package, parse it, and then extract a
362 /// `world` from the parsed package. There are then codegen-specific options to
363 /// the bindings themselves which can additionally be specified.
364 ///
365 /// Usage of this macro looks like:
366 ///
367 /// ```rust,ignore
368 /// // Parse the `wit/` folder adjacent to this crate's `Cargo.toml` and look
369 /// // for a single `world` in it. There must be exactly one for this to
370 /// // succeed.
371 /// bindgen!();
372 ///
373 /// // Parse the `wit/` folder adjacent to this crate's `Cargo.toml` and look
374 /// // for the world `foo` contained in it.
375 /// bindgen!("foo");
376 ///
377 /// // Parse the folder `other/wit/folder` adjacent to `Cargo.toml`.
378 /// bindgen!(in "other/wit/folder");
379 /// bindgen!("foo" in "other/wit/folder");
380 ///
381 /// // Parse the file `foo.wit` as a single-file WIT package with no
382 /// // dependencies.
383 /// bindgen!("foo" in "foo.wit");
384 /// ```
385 ///
386 /// A more configured version of invoking this macro looks like:
387 ///
388 /// ```rust,ignore
389 /// bindgen!({
390 ///     world: "foo", // not needed if `path` has one `world`
391 ///
392 ///     // same as in `bindgen!(in "other/wit/folder")
393 ///     path: "other/wit/folder",
394 ///
395 ///     // Instead of `path` the WIT document can be provided inline if
396 ///     // desired.
397 ///     inline: "
398 ///         package my:inline;
399 ///
400 ///         world foo {
401 ///             // ...
402 ///         }
403 ///     ",
404 ///
405 ///     // Add calls to `tracing::span!` before each import or export is called
406 ///     // to log arguments and return values.
407 ///     //
408 ///     // This option defaults to `false`.
409 ///     tracing: true,
410 ///
411 ///     // Imports will be async functions through #[async_trait] and exports
412 ///     // are also invoked as async functions. Requires `Config::async_support`
413 ///     // to be `true`.
414 ///     //
415 ///     // Note that this is only async for the host as the guest will still
416 ///     // appear as if it's invoking blocking functions.
417 ///     //
418 ///     // This option defaults to `false`.
419 ///     async: true,
420 ///
421 ///     // Alternative mode of async configuration where this still implies
422 ///     // async instantiation happens, for example, but more control is
423 ///     // provided over which imports are async and which aren't.
424 ///     //
425 ///     // Note that in this mode all exports are still async.
426 ///     async: {
427 ///         // All imports are async except for functions with these names
428 ///         except_imports: ["foo", "bar"],
429 ///
430 ///         // All imports are synchronous except for functions with these names
431 ///         //
432 ///         // Note that this key cannot be specified with `except_imports`,
433 ///         // only one or the other is accepted.
434 ///         only_imports: ["foo", "bar"],
435 ///     },
436 ///
437 ///     // This option is used to indicate whether imports can trap.
438 ///     //
439 ///     // Imports that may trap have their return types wrapped in
440 ///     // `wasmtime::Result<T>` where the `Err` variant indicates that a
441 ///     // trap will be raised in the guest.
442 ///     //
443 ///     // By default imports cannot trap and the return value is the return
444 ///     // value from the WIT bindings itself. This value can be set to `true`
445 ///     // to indicate that any import can trap. This value can also be set to
446 ///     // an array-of-strings to indicate that only a set list of imports
447 ///     // can trap.
448 ///     trappable_imports: false,             // no imports can trap (default)
449 ///     // trappable_imports: true,           // all imports can trap
450 ///     // trappable_imports: ["foo", "bar"], // only these can trap
451 ///
452 ///     // This can be used to translate WIT return values of the form
453 ///     // `result<T, error-type>` into `Result<T, RustErrorType>` in Rust.
454 ///     // Users must define `RustErrorType` and the `Host` trait for the
455 ///     // interface which defines `error-type` will have a method
456 ///     // called `convert_error_type` which converts `RustErrorType`
457 ///     // into `wasmtime::Result<ErrorType>`. This conversion can either
458 ///     // return the raw WIT error (`ErrorType` here) or a trap.
459 ///     //
460 ///     // By default this option is not specified. This option only takes
461 ///     // effect when `trappable_imports` is set for some imports.
462 ///     trappable_error_type: {
463 ///         "wasi:io/streams/stream-error" => RustErrorType,
464 ///     },
465 ///
466 ///     // All generated bindgen types are "owned" meaning types like `String`
467 ///     // are used instead of `&str`, for example. This is the default and
468 ///     // ensures that the same type used in both imports and exports uses the
469 ///     // same generated type.
470 ///     ownership: Owning,
471 ///
472 ///     // Alternative to `Owning` above where borrowed types attempt to be used
473 ///     // instead. The `duplicate_if_necessary` configures whether duplicate
474 ///     // Rust types will be generated for the same WIT type if necessary, for
475 ///     // example when a type is used both as an import and an export.
476 ///     ownership: Borrowing {
477 ///         duplicate_if_necessary: true
478 ///     },
479 ///
480 ///     // Restrict the code generated to what's needed for the interface
481 ///     // imports in the inlined WIT document fragment.
482 ///     interfaces: "
483 ///         import wasi:cli/command;
484 ///     ",
485 ///
486 ///     // Remap imported interfaces or resources to types defined in Rust
487 ///     // elsewhere. Using this option will prevent any code from being
488 ///     // generated for interfaces mentioned here. Resources named here will
489 ///     // not have a type generated to represent the resource.
490 ///     //
491 ///     // Interfaces mapped with this option should be previously generated
492 ///     // with an invocation of this macro. Resources need to be mapped to a
493 ///     // Rust type name.
494 ///     with: {
495 ///         // This can be used to indicate that entire interfaces have
496 ///         // bindings generated elsewhere with a path pointing to the
497 ///         // bindinges-generated module.
498 ///         "wasi:random/random": wasmtime_wasi::bindings::random::random,
499 ///
500 ///         // Similarly entire packages can also be specified.
501 ///         "wasi:cli": wasmtime_wasi::bindings::cli,
502 ///
503 ///         // Or, if applicable, entire namespaces can additionally be mapped.
504 ///         "wasi": wasmtime_wasi::bindings,
505 ///
506 ///         // Versions are supported if multiple versions are in play:
507 ///         "wasi:http/types@0.2.0": wasmtime_wasi_http::bindings::http::types,
508 ///         "wasi:[email protected]": wasmtime_wasi_http::bindings::http,
509 ///
510 ///         // The `with` key can also be used to specify the `T` used in
511 ///         // import bindings of `Resource<T>`. This can be done to configure
512 ///         // which typed resource shows up in generated bindings and can be
513 ///         // useful when working with the typed methods of `ResourceTable`.
514 ///         "wasi:filesystem/types/descriptor": MyDescriptorType,
515 ///     },
516 ///
517 ///     // Addtional derive attributes to include on generated types (structs or enums).
518 ///     //
519 ///     // These are deduplicated and attached in a deterministic order.
520 ///     additional_derives: [
521 ///         Hash,
522 ///         serde::Deserialize,
523 ///         serde::Serialize,
524 ///     ]
525 /// });
526 /// ```
527 pub use wasmtime_component_macro::bindgen;
528 
529 /// Derive macro to generate implementations of the [`ComponentType`] trait.
530 ///
531 /// This derive macro can be applied to `struct` and `enum` definitions and is
532 /// used to bind either a `record`, `enum`, or `variant` in the component model.
533 ///
534 /// Note you might be looking for [`bindgen!`] rather than this macro as that
535 /// will generate the entire type for you rather than just a trait
536 /// implementation.
537 ///
538 /// This macro supports a `#[component]` attribute which is used to customize
539 /// how the type is bound to the component model. A top-level `#[component]`
540 /// attribute is required to specify either `record`, `enum`, or `variant`.
541 ///
542 /// ## Records
543 ///
544 /// `record`s in the component model correspond to `struct`s in Rust. An example
545 /// is:
546 ///
547 /// ```rust
548 /// use wasmtime::component::ComponentType;
549 ///
550 /// #[derive(ComponentType)]
551 /// #[component(record)]
552 /// struct Color {
553 ///     r: u8,
554 ///     g: u8,
555 ///     b: u8,
556 /// }
557 /// ```
558 ///
559 /// which corresponds to the WIT type:
560 ///
561 /// ```wit
562 /// record color {
563 ///     r: u8,
564 ///     g: u8,
565 ///     b: u8,
566 /// }
567 /// ```
568 ///
569 /// Note that the name `Color` here does not need to match the name in WIT.
570 /// That's purely used as a name in Rust of what to refer to. The field names
571 /// must match that in WIT, however. Field names can be customized with the
572 /// `#[component]` attribute though.
573 ///
574 /// ```rust
575 /// use wasmtime::component::ComponentType;
576 ///
577 /// #[derive(ComponentType)]
578 /// #[component(record)]
579 /// struct VerboseColor {
580 ///     #[component(name = "r")]
581 ///     red: u8,
582 ///     #[component(name = "g")]
583 ///     green: u8,
584 ///     #[component(name = "b")]
585 ///     blue: u8,
586 /// }
587 /// ```
588 ///
589 /// Also note that field ordering is significant at this time and must match
590 /// WIT.
591 ///
592 /// ## Variants
593 ///
594 /// `variant`s in the component model correspond to a subset of shapes of a Rust
595 /// `enum`. Variants in the component model have a single optional payload type
596 /// which means that not all Rust `enum`s correspond to component model
597 /// `variant`s. An example variant is:
598 ///
599 /// ```rust
600 /// use wasmtime::component::ComponentType;
601 ///
602 /// #[derive(ComponentType)]
603 /// #[component(variant)]
604 /// enum Filter {
605 ///     #[component(name = "none")]
606 ///     None,
607 ///     #[component(name = "all")]
608 ///     All,
609 ///     #[component(name = "some")]
610 ///     Some(Vec<String>),
611 /// }
612 /// ```
613 ///
614 /// which corresponds to the WIT type:
615 ///
616 /// ```wit
617 /// variant filter {
618 ///     none,
619 ///     all,
620 ///     some(list<string>),
621 /// }
622 /// ```
623 ///
624 /// The `variant` style of derive allows an optional payload on Rust `enum`
625 /// variants but it must be a single unnamed field. Variants of the form `Foo(T,
626 /// U)` or `Foo { name: T }` are not supported at this time.
627 ///
628 /// Note that the order of variants in Rust must match the order of variants in
629 /// WIT. Additionally it's likely that `#[component(name = "...")]` is required
630 /// on all Rust `enum` variants because the name currently defaults to the Rust
631 /// name which is typically UpperCamelCase whereas WIT uses kebab-case.
632 ///
633 /// ## Enums
634 ///
635 /// `enum`s in the component model correspond to C-like `enum`s in Rust. Note
636 /// that a component model `enum` does not allow any payloads so the Rust `enum`
637 /// must additionally have no payloads.
638 ///
639 /// ```rust
640 /// use wasmtime::component::ComponentType;
641 ///
642 /// #[derive(ComponentType)]
643 /// #[component(enum)]
644 /// enum Setting {
645 ///     #[component(name = "yes")]
646 ///     Yes,
647 ///     #[component(name = "no")]
648 ///     No,
649 ///     #[component(name = "auto")]
650 ///     Auto,
651 /// }
652 /// ```
653 ///
654 /// which corresponds to the WIT type:
655 ///
656 /// ```wit
657 /// enum setting {
658 ///     yes,
659 ///     no,
660 ///     auto,
661 /// }
662 /// ```
663 ///
664 /// Note that the order of variants in Rust must match the order of variants in
665 /// WIT. Additionally it's likely that `#[component(name = "...")]` is required
666 /// on all Rust `enum` variants because the name currently defaults to the Rust
667 /// name which is typically UpperCamelCase whereas WIT uses kebab-case.
668 pub use wasmtime_component_macro::ComponentType;
669 
670 /// A derive macro for generating implementations of the [`Lift`] trait.
671 ///
672 /// This macro will likely be applied in conjunction with the
673 /// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
674 /// of `#[derive(ComponentType, Lift)]`. This trait enables reading values from
675 /// WebAssembly.
676 ///
677 /// Note you might be looking for [`bindgen!`] rather than this macro as that
678 /// will generate the entire type for you rather than just a trait
679 /// implementation.
680 ///
681 /// At this time this derive macro has no configuration.
682 ///
683 /// ## Examples
684 ///
685 /// ```rust
686 /// use wasmtime::component::{ComponentType, Lift};
687 ///
688 /// #[derive(ComponentType, Lift)]
689 /// #[component(record)]
690 /// struct Color {
691 ///     r: u8,
692 ///     g: u8,
693 ///     b: u8,
694 /// }
695 /// ```
696 pub use wasmtime_component_macro::Lift;
697 
698 /// A derive macro for generating implementations of the [`Lower`] trait.
699 ///
700 /// This macro will likely be applied in conjunction with the
701 /// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines
702 /// of `#[derive(ComponentType, Lower)]`. This trait enables passing values to
703 /// WebAssembly.
704 ///
705 /// Note you might be looking for [`bindgen!`] rather than this macro as that
706 /// will generate the entire type for you rather than just a trait
707 /// implementation.
708 ///
709 /// At this time this derive macro has no configuration.
710 ///
711 /// ## Examples
712 ///
713 /// ```rust
714 /// use wasmtime::component::{ComponentType, Lower};
715 ///
716 /// #[derive(ComponentType, Lower)]
717 /// #[component(record)]
718 /// struct Color {
719 ///     r: u8,
720 ///     g: u8,
721 ///     b: u8,
722 /// }
723 /// ```
724 pub use wasmtime_component_macro::Lower;
725 
726 /// A macro to generate a Rust type corresponding to WIT `flags`
727 ///
728 /// This macro generates a type that implements the [`ComponentType`], [`Lift`],
729 /// and [`Lower`] traits. The generated Rust type corresponds to the `flags`
730 /// type in WIT.
731 ///
732 /// Example usage of this looks like:
733 ///
734 /// ```rust
735 /// use wasmtime::component::flags;
736 ///
737 /// flags! {
738 ///     Permissions {
739 ///         #[component(name = "read")]
740 ///         const READ;
741 ///         #[component(name = "write")]
742 ///         const WRITE;
743 ///         #[component(name = "execute")]
744 ///         const EXECUTE;
745 ///     }
746 /// }
747 ///
748 /// fn validate_permissions(permissions: &mut Permissions) {
749 ///     if permissions.contains(Permissions::EXECUTE | Permissions::WRITE) {
750 ///         panic!("cannot enable both writable and executable at the same time");
751 ///     }
752 ///
753 ///     if permissions.contains(Permissions::READ) {
754 ///         panic!("permissions must at least contain read");
755 ///     }
756 /// }
757 /// ```
758 ///
759 /// which corresponds to the WIT type:
760 ///
761 /// ```wit
762 /// flags permissions {
763 ///     read,
764 ///     write,
765 ///     execute,
766 /// }
767 /// ```
768 ///
769 /// This generates a structure which is similar to/inspired by the [`bitflags`
770 /// crate](https://crates.io/crates/bitflags). The `Permissions` structure
771 /// generated implements the [`PartialEq`], [`Eq`], [`Debug`], [`BitOr`],
772 /// [`BitOrAssign`], [`BitAnd`], [`BitAndAssign`], [`BitXor`], [`BitXorAssign`],
773 /// and [`Not`] traits - in addition to the Wasmtime-specific component ones
774 /// [`ComponentType`], [`Lift`], and [`Lower`].
775 ///
776 /// [`BitOr`]: std::ops::BitOr
777 /// [`BitOrAssign`]: std::ops::BitOrAssign
778 /// [`BitAnd`]: std::ops::BitAnd
779 /// [`BitAndAssign`]: std::ops::BitAndAssign
780 /// [`BitXor`]: std::ops::BitXor
781 /// [`BitXorAssign`]: std::ops::BitXorAssign
782 /// [`Not`]: std::ops::Not
783 pub use wasmtime_component_macro::flags;
784