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