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