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