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; 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. This requires 291 /// // `Config::async_support` to be `true` as well. 292 /// "wasi:io/poll.poll": async, 293 /// 294 /// // The `store` flag means that the host function will have access 295 /// // to the store during its execution. By default host functions take 296 /// // `&mut self` which only has access to the data in question 297 /// // implementing the generated traits from `bindgen!`. This 298 /// // configuration means that in addition to `Self` the entire store 299 /// // will be accessible if necessary. 300 /// // 301 /// // Functions that have access to a `store` are generated in a 302 /// // `HostWithStore` trait. Functions without a `store` are generated 303 /// // in a `Host` trait. 304 /// // 305 /// // > Note: this is not yet implemented for non-async functions. This 306 /// // > will result in bindgen errors right now and is intended to be 307 /// // > implemented in the near future. 308 /// "wasi:clocks/monotonic-clock.now": store, 309 /// 310 /// // This is an example of combining flags where the `async` and 311 /// // `store` flags are combined. This means that the generated 312 /// // host function is both `async` and additionally has access to 313 /// // the `store`. Note though that this configuration is not necessary 314 /// // as the WIT function is itself already marked as `async`. That 315 /// // means that this is the default already applied meaning that 316 /// // specifying it here would be redundant. 317 /// // 318 /// // "wasi:clocks/monotonic-clock.wait-until": async | store, 319 /// 320 /// // The `tracing` flag indicates that `tracing!` will be used to log 321 /// // entries and exits into this host API. This can assist with 322 /// // debugging or just generally be used to provide logs for the host. 323 /// // 324 /// // By default values are traced unless they contain lists, but 325 /// // tracing of lists can be enabled with `verbose_tracing` below. 326 /// "my:local/api.foo": tracing, 327 /// 328 /// // The `verbose_tracing` flag indicates that when combined with 329 /// // `tracing` the values of parameters/results are added to logs. 330 /// // This may include lists which may be very large. 331 /// "my:local/api.other-function": tracing | verbose_tracing, 332 /// 333 /// // The `trappable` flag indicates that this import is allowed to 334 /// // generate a trap. 335 /// // 336 /// // Imports that may trap have their return types wrapped in 337 /// // `wasmtime::Result<T>` where the `Err` variant indicates that a 338 /// // trap will be raised in the guest. 339 /// // 340 /// // By default imports cannot trap and the return value is the return 341 /// // value from the WIT bindings itself. 342 /// // 343 /// // Note that the `trappable` configuration can be combined with the 344 /// // `trappable_error_type` configuration below to avoid having a 345 /// // host function return `wasmtime::Result<Result<WitOk, WitErr>>` 346 /// // for example and instead return `Result<WitOk, RustErrorType>`. 347 /// "my:local/api.fallible": trappable, 348 /// 349 /// // The `ignore_wit` flag discards the WIT-level defaults of a 350 /// // function. For example this `async` WIT function will be ignored 351 /// // and a synchronous function will be generated on the host. 352 /// "my:local/api.wait": ignore_wit, 353 /// 354 /// // The `exact` flag ensures that the filter, here "f", only matches 355 /// // functions exactly. For example "f" here would only refer to 356 /// // `import f: func()` in a world. Without this flag then "f" 357 /// // would also configure any package `f:*/*/*` for example. 358 /// "f": exact, 359 /// 360 /// // This is used to configure the defaults of all functions if no 361 /// // other key above matches a function. Note that if specific 362 /// // functions mentioned above want these flags too then the flags 363 /// // must be added there too because only one matching rule in this 364 /// // map is used per-function. 365 /// default: async | trappable, 366 /// }, 367 /// 368 /// // Mostly the same as `imports` above, but applies to exported functions. 369 /// // 370 /// // The one difference here is that, whereas the `task_exit` flag has no 371 /// // effect for `imports`, it changes how bindings are generated for 372 /// // exported functions as described below. 373 /// exports: { 374 /// /* ... */ 375 /// 376 /// // The `task_exit` flag indicates that the generated binding for 377 /// // this function should return a tuple of the result produced by the 378 /// // callee and a `TaskExit` future which will resolve when the task 379 /// // (and any transitively created subtasks) have exited. 380 /// "my:local/api.does-stuff-after-returning": task_exit, 381 /// }, 382 /// 383 /// // This can be used to translate WIT return values of the form 384 /// // `result<T, error-type>` into `Result<T, RustErrorType>` in Rust. 385 /// // Users must define `RustErrorType` and the `Host` trait for the 386 /// // interface which defines `error-type` will have a method 387 /// // called `convert_error_type` which converts `RustErrorType` 388 /// // into `wasmtime::Result<ErrorType>`. This conversion can either 389 /// // return the raw WIT error (`ErrorType` here) or a trap. 390 /// // 391 /// // By default this option is not specified. This option only takes 392 /// // effect when `trappable` is set for some imports. 393 /// trappable_error_type: { 394 /// "wasi:io/streams.stream-error" => RustErrorType, 395 /// }, 396 /// 397 /// // All generated bindgen types are "owned" meaning types like `String` 398 /// // are used instead of `&str`, for example. This is the default and 399 /// // ensures that the same type used in both imports and exports uses the 400 /// // same generated type. 401 /// ownership: Owning, 402 /// 403 /// // Alternative to `Owning` above where borrowed types attempt to be used 404 /// // instead. The `duplicate_if_necessary` configures whether duplicate 405 /// // Rust types will be generated for the same WIT type if necessary, for 406 /// // example when a type is used both as an import and an export. 407 /// ownership: Borrowing { 408 /// duplicate_if_necessary: true 409 /// }, 410 /// 411 /// // Restrict the code generated to what's needed for the interface 412 /// // imports in the inlined WIT document fragment. 413 /// interfaces: " 414 /// import wasi:cli/command; 415 /// ", 416 /// 417 /// // Remap imported interfaces or resources to types defined in Rust 418 /// // elsewhere. Using this option will prevent any code from being 419 /// // generated for interfaces mentioned here. Resources named here will 420 /// // not have a type generated to represent the resource. 421 /// // 422 /// // Interfaces mapped with this option should be previously generated 423 /// // with an invocation of this macro. Resources need to be mapped to a 424 /// // Rust type name. 425 /// with: { 426 /// // This can be used to indicate that entire interfaces have 427 /// // bindings generated elsewhere with a path pointing to the 428 /// // bindinges-generated module. 429 /// "wasi:random/random": wasmtime_wasi::p2::bindings::random::random, 430 /// 431 /// // Similarly entire packages can also be specified. 432 /// "wasi:cli": wasmtime_wasi::p2::bindings::cli, 433 /// 434 /// // Or, if applicable, entire namespaces can additionally be mapped. 435 /// "wasi": wasmtime_wasi::p2::bindings, 436 /// 437 /// // Versions are supported if multiple versions are in play: 438 /// "wasi:http/types@0.2.0": wasmtime_wasi_http::bindings::http::types, 439 /// "wasi:[email protected]": wasmtime_wasi_http::bindings::http, 440 /// 441 /// // The `with` key can also be used to specify the `T` used in 442 /// // import bindings of `Resource<T>`. This can be done to configure 443 /// // which typed resource shows up in generated bindings and can be 444 /// // useful when working with the typed methods of `ResourceTable`. 445 /// "wasi:filesystem/types.descriptor": MyDescriptorType, 446 /// }, 447 /// 448 /// // Additional derive attributes to include on generated types (structs or enums). 449 /// // 450 /// // These are deduplicated and attached in a deterministic order. 451 /// additional_derives: [ 452 /// Hash, 453 /// serde::Deserialize, 454 /// serde::Serialize, 455 /// ], 456 /// 457 /// // An niche configuration option to require that the `T` in `Store<T>` 458 /// // is always `Send` in the generated bindings. Typically not needed 459 /// // but if synchronous bindings depend on asynchronous bindings using 460 /// // the `with` key then this may be required. 461 /// require_store_data_send: false, 462 /// 463 /// // If the `wasmtime` crate is depended on at a nonstandard location 464 /// // or is renamed then this is the path to the root of the `wasmtime` 465 /// // crate. Much of the generated code needs to refer to `wasmtime` so 466 /// // this should be used if the `wasmtime` name is not wasmtime itself. 467 /// // 468 /// // By default this is `wasmtime`. 469 /// wasmtime_crate: path::to::wasmtime, 470 /// 471 /// // This is an in-source alternative to using `WASMTIME_DEBUG_BINDGEN`. 472 /// // 473 /// // Note that if this option is specified then the compiler will always 474 /// // recompile your bindings. Cargo records the start time of when rustc 475 /// // is spawned by this will write a file during compilation. To Cargo 476 /// // that looks like a file was modified after `rustc` was spawned, 477 /// // so Cargo will always think your project is "dirty" and thus always 478 /// // recompile it. Recompiling will then overwrite the file again, 479 /// // starting the cycle anew. This is only recommended for debugging. 480 /// // 481 /// // This option defaults to false. 482 /// include_generated_code_from_file: false, 483 /// }); 484 /// ``` 485 pub use wasmtime_component_macro::bindgen; 486 487 /// Derive macro to generate implementations of the [`ComponentType`] trait. 488 /// 489 /// This derive macro can be applied to `struct` and `enum` definitions and is 490 /// used to bind either a `record`, `enum`, or `variant` in the component model. 491 /// 492 /// Note you might be looking for [`bindgen!`] rather than this macro as that 493 /// will generate the entire type for you rather than just a trait 494 /// implementation. 495 /// 496 /// This macro supports a `#[component]` attribute which is used to customize 497 /// how the type is bound to the component model. A top-level `#[component]` 498 /// attribute is required to specify either `record`, `enum`, or `variant`. 499 /// 500 /// ## Records 501 /// 502 /// `record`s in the component model correspond to `struct`s in Rust. An example 503 /// is: 504 /// 505 /// ```rust 506 /// use wasmtime::component::ComponentType; 507 /// 508 /// #[derive(ComponentType)] 509 /// #[component(record)] 510 /// struct Color { 511 /// r: u8, 512 /// g: u8, 513 /// b: u8, 514 /// } 515 /// ``` 516 /// 517 /// which corresponds to the WIT type: 518 /// 519 /// ```wit 520 /// record color { 521 /// r: u8, 522 /// g: u8, 523 /// b: u8, 524 /// } 525 /// ``` 526 /// 527 /// Note that the name `Color` here does not need to match the name in WIT. 528 /// That's purely used as a name in Rust of what to refer to. The field names 529 /// must match that in WIT, however. Field names can be customized with the 530 /// `#[component]` attribute though. 531 /// 532 /// ```rust 533 /// use wasmtime::component::ComponentType; 534 /// 535 /// #[derive(ComponentType)] 536 /// #[component(record)] 537 /// struct VerboseColor { 538 /// #[component(name = "r")] 539 /// red: u8, 540 /// #[component(name = "g")] 541 /// green: u8, 542 /// #[component(name = "b")] 543 /// blue: u8, 544 /// } 545 /// ``` 546 /// 547 /// Also note that field ordering is significant at this time and must match 548 /// WIT. 549 /// 550 /// ## Variants 551 /// 552 /// `variant`s in the component model correspond to a subset of shapes of a Rust 553 /// `enum`. Variants in the component model have a single optional payload type 554 /// which means that not all Rust `enum`s correspond to component model 555 /// `variant`s. An example variant is: 556 /// 557 /// ```rust 558 /// use wasmtime::component::ComponentType; 559 /// 560 /// #[derive(ComponentType)] 561 /// #[component(variant)] 562 /// enum Filter { 563 /// #[component(name = "none")] 564 /// None, 565 /// #[component(name = "all")] 566 /// All, 567 /// #[component(name = "some")] 568 /// Some(Vec<String>), 569 /// } 570 /// ``` 571 /// 572 /// which corresponds to the WIT type: 573 /// 574 /// ```wit 575 /// variant filter { 576 /// none, 577 /// all, 578 /// some(list<string>), 579 /// } 580 /// ``` 581 /// 582 /// The `variant` style of derive allows an optional payload on Rust `enum` 583 /// variants but it must be a single unnamed field. Variants of the form `Foo(T, 584 /// U)` or `Foo { name: T }` are not supported at this time. 585 /// 586 /// Note that the order of variants in Rust must match the order of variants in 587 /// WIT. Additionally it's likely that `#[component(name = "...")]` is required 588 /// on all Rust `enum` variants because the name currently defaults to the Rust 589 /// name which is typically UpperCamelCase whereas WIT uses kebab-case. 590 /// 591 /// ## Enums 592 /// 593 /// `enum`s in the component model correspond to C-like `enum`s in Rust. Note 594 /// that a component model `enum` does not allow any payloads so the Rust `enum` 595 /// must additionally have no payloads. 596 /// 597 /// ```rust 598 /// use wasmtime::component::ComponentType; 599 /// 600 /// #[derive(ComponentType)] 601 /// #[component(enum)] 602 /// #[repr(u8)] 603 /// enum Setting { 604 /// #[component(name = "yes")] 605 /// Yes, 606 /// #[component(name = "no")] 607 /// No, 608 /// #[component(name = "auto")] 609 /// Auto, 610 /// } 611 /// ``` 612 /// 613 /// which corresponds to the WIT type: 614 /// 615 /// ```wit 616 /// enum setting { 617 /// yes, 618 /// no, 619 /// auto, 620 /// } 621 /// ``` 622 /// 623 /// Note that the order of variants in Rust must match the order of variants in 624 /// WIT. Additionally it's likely that `#[component(name = "...")]` is required 625 /// on all Rust `enum` variants because the name currently defaults to the Rust 626 /// name which is typically UpperCamelCase whereas WIT uses kebab-case. 627 pub use wasmtime_component_macro::ComponentType; 628 629 /// A derive macro for generating implementations of the [`Lift`] trait. 630 /// 631 /// This macro will likely be applied in conjunction with the 632 /// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines 633 /// of `#[derive(ComponentType, Lift)]`. This trait enables reading values from 634 /// WebAssembly. 635 /// 636 /// Note you might be looking for [`bindgen!`] rather than this macro as that 637 /// will generate the entire type for you rather than just a trait 638 /// implementation. 639 /// 640 /// At this time this derive macro has no configuration. 641 /// 642 /// ## Examples 643 /// 644 /// ```rust 645 /// use wasmtime::component::{ComponentType, Lift}; 646 /// 647 /// #[derive(ComponentType, Lift)] 648 /// #[component(record)] 649 /// struct Color { 650 /// r: u8, 651 /// g: u8, 652 /// b: u8, 653 /// } 654 /// ``` 655 pub use wasmtime_component_macro::Lift; 656 657 /// A derive macro for generating implementations of the [`Lower`] trait. 658 /// 659 /// This macro will likely be applied in conjunction with the 660 /// [`#[derive(ComponentType)]`](macro@ComponentType) macro along the lines 661 /// of `#[derive(ComponentType, Lower)]`. This trait enables passing values to 662 /// WebAssembly. 663 /// 664 /// Note you might be looking for [`bindgen!`] rather than this macro as that 665 /// will generate the entire type for you rather than just a trait 666 /// implementation. 667 /// 668 /// At this time this derive macro has no configuration. 669 /// 670 /// ## Examples 671 /// 672 /// ```rust 673 /// use wasmtime::component::{ComponentType, Lower}; 674 /// 675 /// #[derive(ComponentType, Lower)] 676 /// #[component(record)] 677 /// struct Color { 678 /// r: u8, 679 /// g: u8, 680 /// b: u8, 681 /// } 682 /// ``` 683 pub use wasmtime_component_macro::Lower; 684 685 /// A macro to generate a Rust type corresponding to WIT `flags` 686 /// 687 /// This macro generates a type that implements the [`ComponentType`], [`Lift`], 688 /// and [`Lower`] traits. The generated Rust type corresponds to the `flags` 689 /// type in WIT. 690 /// 691 /// Example usage of this looks like: 692 /// 693 /// ```rust 694 /// use wasmtime::component::flags; 695 /// 696 /// flags! { 697 /// Permissions { 698 /// #[component(name = "read")] 699 /// const READ; 700 /// #[component(name = "write")] 701 /// const WRITE; 702 /// #[component(name = "execute")] 703 /// const EXECUTE; 704 /// } 705 /// } 706 /// 707 /// fn validate_permissions(permissions: &mut Permissions) { 708 /// if permissions.contains(Permissions::EXECUTE | Permissions::WRITE) { 709 /// panic!("cannot enable both writable and executable at the same time"); 710 /// } 711 /// 712 /// if permissions.contains(Permissions::READ) { 713 /// panic!("permissions must at least contain read"); 714 /// } 715 /// } 716 /// ``` 717 /// 718 /// which corresponds to the WIT type: 719 /// 720 /// ```wit 721 /// flags permissions { 722 /// read, 723 /// write, 724 /// execute, 725 /// } 726 /// ``` 727 /// 728 /// This generates a structure which is similar to/inspired by the [`bitflags` 729 /// crate](https://crates.io/crates/bitflags). The `Permissions` structure 730 /// generated implements the [`PartialEq`], [`Eq`], [`Debug`], [`BitOr`], 731 /// [`BitOrAssign`], [`BitAnd`], [`BitAndAssign`], [`BitXor`], [`BitXorAssign`], 732 /// and [`Not`] traits - in addition to the Wasmtime-specific component ones 733 /// [`ComponentType`], [`Lift`], and [`Lower`]. 734 /// 735 /// [`BitOr`]: std::ops::BitOr 736 /// [`BitOrAssign`]: std::ops::BitOrAssign 737 /// [`BitAnd`]: std::ops::BitAnd 738 /// [`BitAndAssign`]: std::ops::BitAndAssign 739 /// [`BitXor`]: std::ops::BitXor 740 /// [`BitXorAssign`]: std::ops::BitXorAssign 741 /// [`Not`]: std::ops::Not 742 pub use wasmtime_component_macro::flags; 743 744 #[cfg(any(docsrs, test, doctest))] 745 pub mod bindgen_examples; 746 747 // NB: needed for the links in the docs above to work in all `cargo doc` 748 // configurations and avoid errors. 749 #[cfg(not(any(docsrs, test, doctest)))] 750 #[doc(hidden)] 751 pub mod bindgen_examples {} 752 753 #[cfg(not(feature = "component-model-async"))] 754 pub(crate) mod concurrent_disabled; 755 756 #[cfg(not(feature = "component-model-async"))] 757 pub(crate) use concurrent_disabled as concurrent; 758