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