1 //! > **⚠️ Warning ⚠️**: this crate is an internal-only crate for the Wasmtime 2 //! > project and is not intended for general use. APIs are not strictly 3 //! > reviewed for safety and usage outside of Wasmtime may have bugs. If 4 //! > you're interested in using this feel free to file an issue on the 5 //! > Wasmtime repository to start a discussion about doing so, but otherwise 6 //! > be aware that your usage of this crate is not supported. 7 8 use crate::rust::{RustGenerator, TypeMode, to_rust_ident, to_rust_upper_camel_case}; 9 use crate::types::{TypeInfo, Types}; 10 use anyhow::bail; 11 use heck::*; 12 use indexmap::{IndexMap, IndexSet}; 13 use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; 14 use std::fmt::Write as _; 15 use std::io::{Read, Write}; 16 use std::mem; 17 use std::process::{Command, Stdio}; 18 use wit_parser::*; 19 20 macro_rules! uwrite { 21 ($dst:expr, $($arg:tt)*) => { 22 write!($dst, $($arg)*).unwrap() 23 }; 24 } 25 26 macro_rules! uwriteln { 27 ($dst:expr, $($arg:tt)*) => { 28 writeln!($dst, $($arg)*).unwrap() 29 }; 30 } 31 32 mod config; 33 mod rust; 34 mod source; 35 mod types; 36 37 pub use config::{FunctionConfig, FunctionFilter, FunctionFlags}; 38 use source::Source; 39 40 #[derive(Clone)] 41 enum InterfaceName { 42 /// This interface was remapped using `with` to some other Rust code. 43 Remapped { 44 /// This is the `::`-separated string which is the path to the mapped 45 /// item relative to the root of the `bindgen!` macro invocation. 46 /// 47 /// This path currently starts with `__with_name$N` and will then 48 /// optionally have `::` projections through to the actual item 49 /// depending on how `with` was configured. 50 name_at_root: String, 51 52 /// This is currently only used for exports and is the relative path to 53 /// where this mapped name would be located if `with` were not 54 /// specified. Basically it's the same as the `Path` variant of this 55 /// enum if the mapping weren't present. 56 local_path: Vec<String>, 57 }, 58 59 /// This interface is generated in the module hierarchy specified. 60 /// 61 /// The path listed here is the path, from the root of the `bindgen!` macro, 62 /// to where this interface is generated. 63 Path(Vec<String>), 64 } 65 66 #[derive(Default)] 67 struct Wasmtime { 68 src: Source, 69 opts: Opts, 70 /// A list of all interfaces which were imported by this world. 71 import_interfaces: Vec<ImportInterface>, 72 import_functions: Vec<Function>, 73 exports: Exports, 74 types: Types, 75 sizes: SizeAlign, 76 interface_names: HashMap<InterfaceId, InterfaceName>, 77 interface_last_seen_as_import: HashMap<InterfaceId, bool>, 78 trappable_errors: IndexMap<TypeId, String>, 79 // Track the with options that were used. Remapped interfaces provided via `with` 80 // are required to be used. 81 used_with_opts: HashSet<String>, 82 world_link_options: LinkOptionsBuilder, 83 interface_link_options: HashMap<InterfaceId, LinkOptionsBuilder>, 84 } 85 86 struct ImportInterface { 87 id: InterfaceId, 88 contents: String, 89 name: InterfaceName, 90 all_func_flags: FunctionFlags, 91 } 92 93 #[derive(Default)] 94 struct Exports { 95 fields: BTreeMap<String, ExportField>, 96 modules: Vec<(InterfaceId, String, InterfaceName)>, 97 funcs: Vec<String>, 98 } 99 100 struct ExportField { 101 ty: String, 102 ty_index: String, 103 load: String, 104 get_index: String, 105 } 106 107 #[derive(Default, Debug, Clone, Copy)] 108 pub enum Ownership { 109 /// Generated types will be composed entirely of owning fields, regardless 110 /// of whether they are used as parameters to guest exports or not. 111 #[default] 112 Owning, 113 114 /// Generated types used as parameters to guest exports will be "deeply 115 /// borrowing", i.e. contain references rather than owned values when 116 /// applicable. 117 Borrowing { 118 /// Whether or not to generate "duplicate" type definitions for a single 119 /// WIT type if necessary, for example if it's used as both an import 120 /// and an export, or if it's used both as a parameter to an export and 121 /// a return value from an export. 122 duplicate_if_necessary: bool, 123 }, 124 } 125 126 #[derive(Default, Debug, Clone)] 127 pub struct Opts { 128 /// Whether or not `rustfmt` is executed to format generated code. 129 pub rustfmt: bool, 130 131 /// A list of "trappable errors" which are used to replace the `E` in 132 /// `result<T, E>` found in WIT. 133 pub trappable_error_type: Vec<TrappableError>, 134 135 /// Whether to generate owning or borrowing type definitions. 136 pub ownership: Ownership, 137 138 /// Whether or not to generate code for only the interfaces of this wit file or not. 139 pub only_interfaces: bool, 140 141 /// Remapping of interface names to rust module names. 142 /// TODO: is there a better type to use for the value of this map? 143 pub with: HashMap<String, String>, 144 145 /// Additional derive attributes to add to generated types. If using in a CLI, this flag can be 146 /// specified multiple times to add multiple attributes. 147 /// 148 /// These derive attributes will be added to any generated structs or enums 149 pub additional_derive_attributes: Vec<String>, 150 151 /// Evaluate to a string literal containing the generated code rather than the generated tokens 152 /// themselves. Mostly useful for Wasmtime internal debugging and development. 153 pub stringify: bool, 154 155 /// Temporary option to skip `impl<T: Trait> Trait for &mut T` for the 156 /// `wasmtime-wasi` crate while that's given a chance to update its b 157 /// indings. 158 pub skip_mut_forwarding_impls: bool, 159 160 /// Indicates that the `T` in `Store<T>` should be send even if async is not 161 /// enabled. 162 /// 163 /// This is helpful when sync bindings depend on generated functions from 164 /// async bindings as is the case with WASI in-tree. 165 pub require_store_data_send: bool, 166 167 /// Path to the `wasmtime` crate if it's not the default path. 168 pub wasmtime_crate: Option<String>, 169 170 /// If true, write the generated bindings to a file for better error 171 /// messages from `rustc`. 172 /// 173 /// This can also be toggled via the `WASMTIME_DEBUG_BINDGEN` environment 174 /// variable, but that will affect _all_ `bindgen!` macro invocations (and 175 /// can sometimes lead to one invocation overwriting another in unpredictable 176 /// ways), whereas this option lets you specify it on a case-by-case basis. 177 pub debug: bool, 178 179 /// TODO 180 pub imports: FunctionConfig, 181 /// TODO 182 pub exports: FunctionConfig, 183 } 184 185 #[derive(Debug, Clone)] 186 pub struct TrappableError { 187 /// Full path to the error, such as `wasi:io/streams.error`. 188 pub wit_path: String, 189 190 /// The name, in Rust, of the error type to generate. 191 pub rust_type_name: String, 192 } 193 194 impl Opts { 195 pub fn generate(&self, resolve: &Resolve, world: WorldId) -> anyhow::Result<String> { 196 // TODO: Should we refine this test to inspect only types reachable from 197 // the specified world? 198 if !cfg!(feature = "component-model-async") 199 && resolve 200 .types 201 .iter() 202 .any(|(_, ty)| matches!(ty.kind, TypeDefKind::Future(_) | TypeDefKind::Stream(_))) 203 { 204 anyhow::bail!( 205 "must enable `component-model-async` feature when using WIT files \ 206 containing future, stream, or error-context types" 207 ); 208 } 209 210 let mut r = Wasmtime::default(); 211 r.sizes.fill(resolve); 212 r.opts = self.clone(); 213 r.populate_world_and_interface_options(resolve, world); 214 r.generate(resolve, world) 215 } 216 } 217 218 impl Wasmtime { 219 fn populate_world_and_interface_options(&mut self, resolve: &Resolve, world: WorldId) { 220 self.world_link_options.add_world(resolve, &world); 221 222 for (_, import) in resolve.worlds[world].imports.iter() { 223 match import { 224 WorldItem::Interface { id, .. } => { 225 let mut o = LinkOptionsBuilder::default(); 226 o.add_interface(resolve, id); 227 self.interface_link_options.insert(*id, o); 228 } 229 WorldItem::Function(_) | WorldItem::Type(_) => {} 230 } 231 } 232 } 233 fn name_interface( 234 &mut self, 235 resolve: &Resolve, 236 id: InterfaceId, 237 name: &WorldKey, 238 is_export: bool, 239 ) -> bool { 240 let mut path = Vec::new(); 241 if is_export { 242 path.push("exports".to_string()); 243 } 244 match name { 245 WorldKey::Name(name) => { 246 path.push(name.to_snake_case()); 247 } 248 WorldKey::Interface(_) => { 249 let iface = &resolve.interfaces[id]; 250 let pkgname = &resolve.packages[iface.package.unwrap()].name; 251 path.push(pkgname.namespace.to_snake_case()); 252 path.push(self.name_package_module(resolve, iface.package.unwrap())); 253 path.push(to_rust_ident(iface.name.as_ref().unwrap())); 254 } 255 } 256 let entry = if let Some(name_at_root) = self.lookup_replacement(resolve, name, None) { 257 InterfaceName::Remapped { 258 name_at_root, 259 local_path: path, 260 } 261 } else { 262 InterfaceName::Path(path) 263 }; 264 265 let remapped = matches!(entry, InterfaceName::Remapped { .. }); 266 self.interface_names.insert(id, entry); 267 remapped 268 } 269 270 /// If the package `id` is the only package with its namespace/name combo 271 /// then pass through the name unmodified. If, however, there are multiple 272 /// versions of this package then the package module is going to get version 273 /// information. 274 fn name_package_module(&self, resolve: &Resolve, id: PackageId) -> String { 275 let pkg = &resolve.packages[id]; 276 let versions_with_same_name = resolve 277 .packages 278 .iter() 279 .filter_map(|(_, p)| { 280 if p.name.namespace == pkg.name.namespace && p.name.name == pkg.name.name { 281 Some(&p.name.version) 282 } else { 283 None 284 } 285 }) 286 .collect::<Vec<_>>(); 287 let base = pkg.name.name.to_snake_case(); 288 if versions_with_same_name.len() == 1 { 289 return base; 290 } 291 292 let version = match &pkg.name.version { 293 Some(version) => version, 294 // If this package didn't have a version then don't mangle its name 295 // and other packages with the same name but with versions present 296 // will have their names mangled. 297 None => return base, 298 }; 299 300 // Here there's multiple packages with the same name that differ only in 301 // version, so the version needs to be mangled into the Rust module name 302 // that we're generating. This in theory could look at all of 303 // `versions_with_same_name` and produce a minimal diff, e.g. for 0.1.0 304 // and 0.2.0 this could generate "foo1" and "foo2", but for now 305 // a simpler path is chosen to generate "foo0_1_0" and "foo0_2_0". 306 let version = version 307 .to_string() 308 .replace('.', "_") 309 .replace('-', "_") 310 .replace('+', "_") 311 .to_snake_case(); 312 format!("{base}{version}") 313 } 314 315 fn generate(&mut self, resolve: &Resolve, id: WorldId) -> anyhow::Result<String> { 316 self.types.analyze(resolve, id); 317 318 self.world_link_options.write_struct(&mut self.src); 319 320 // Resolve the `trappable_error_type` configuration values to `TypeId` 321 // values. This is done by iterating over each `trappable_error_type` 322 // and then locating the interface that it corresponds to as well as the 323 // type within that interface. 324 // 325 // Note that `LookupItem::InterfaceNoPop` is used here as the full 326 // hierarchical behavior of `lookup_keys` isn't used as the interface 327 // must be named here. 328 'outer: for (i, te) in self.opts.trappable_error_type.iter().enumerate() { 329 let error_name = format!("_TrappableError{i}"); 330 for (id, iface) in resolve.interfaces.iter() { 331 for (key, projection) in lookup_keys( 332 resolve, 333 &WorldKey::Interface(id), 334 LookupItem::InterfaceNoPop, 335 ) { 336 assert!(projection.is_empty()); 337 338 // If `wit_path` looks like `{key}.{type_name}` where 339 // `type_name` is a type within `iface` then we've found a 340 // match. Otherwise continue to the next lookup key if there 341 // is one, and failing that continue to the next interface. 342 let suffix = match te.wit_path.strip_prefix(&key) { 343 Some(s) => s, 344 None => continue, 345 }; 346 let suffix = match suffix.strip_prefix('.') { 347 Some(s) => s, 348 None => continue, 349 }; 350 if let Some(id) = iface.types.get(suffix) { 351 uwriteln!(self.src, "type {error_name} = {};", te.rust_type_name); 352 let prev = self.trappable_errors.insert(*id, error_name); 353 assert!(prev.is_none()); 354 continue 'outer; 355 } 356 } 357 } 358 359 bail!( 360 "failed to locate a WIT error type corresponding to the \ 361 `trappable_error_type` name `{}` provided", 362 te.wit_path 363 ) 364 } 365 366 // Convert all entries in `with` as relative to the root of where the 367 // macro itself is invoked. This emits a `pub use` to bring the name 368 // into scope under an "anonymous name" which then replaces the `with` 369 // map entry. 370 let mut with = self.opts.with.iter_mut().collect::<Vec<_>>(); 371 with.sort(); 372 for (i, (_k, v)) in with.into_iter().enumerate() { 373 let name = format!("__with_name{i}"); 374 uwriteln!(self.src, "#[doc(hidden)]\npub use {v} as {name};"); 375 *v = name; 376 } 377 378 let world = &resolve.worlds[id]; 379 for (name, import) in world.imports.iter() { 380 if !self.opts.only_interfaces || matches!(import, WorldItem::Interface { .. }) { 381 self.import(resolve, name, import); 382 } 383 } 384 385 for (name, export) in world.exports.iter() { 386 if !self.opts.only_interfaces || matches!(export, WorldItem::Interface { .. }) { 387 self.export(resolve, name, export); 388 } 389 } 390 self.finish(resolve, id) 391 } 392 393 fn import(&mut self, resolve: &Resolve, name: &WorldKey, item: &WorldItem) { 394 let mut generator = InterfaceGenerator::new(self, resolve); 395 match item { 396 WorldItem::Function(func) => { 397 self.import_functions.push(func.clone()); 398 } 399 WorldItem::Interface { id, .. } => { 400 generator 401 .generator 402 .interface_last_seen_as_import 403 .insert(*id, true); 404 generator.current_interface = Some((*id, name, false)); 405 let snake = to_rust_ident(&match name { 406 WorldKey::Name(s) => s.to_snake_case(), 407 WorldKey::Interface(id) => resolve.interfaces[*id] 408 .name 409 .as_ref() 410 .unwrap() 411 .to_snake_case(), 412 }); 413 let module = if generator 414 .generator 415 .name_interface(resolve, *id, name, false) 416 { 417 // If this interface is remapped then that means that it was 418 // provided via the `with` key in the bindgen configuration. 419 // That means that bindings generation is skipped here. To 420 // accommodate future bindgens depending on this bindgen 421 // though we still generate a module which reexports the 422 // original module. This helps maintain the same output 423 // structure regardless of whether `with` is used. 424 let name_at_root = match &generator.generator.interface_names[id] { 425 InterfaceName::Remapped { name_at_root, .. } => name_at_root, 426 InterfaceName::Path(_) => unreachable!(), 427 }; 428 let path_to_root = generator.path_to_root(); 429 format!( 430 " 431 pub mod {snake} {{ 432 #[allow(unused_imports)] 433 pub use {path_to_root}{name_at_root}::*; 434 }} 435 " 436 ) 437 } else { 438 // If this interface is not remapped then it's time to 439 // actually generate bindings here. 440 generator.generator.interface_link_options[id].write_struct(&mut generator.src); 441 generator.types(*id); 442 let key_name = resolve.name_world_key(name); 443 generator.generate_add_to_linker(*id, &key_name); 444 445 let module = &generator.src[..]; 446 let wt = generator.generator.wasmtime_path(); 447 448 format!( 449 " 450 #[allow(clippy::all)] 451 pub mod {snake} {{ 452 #[allow(unused_imports)] 453 use {wt}::component::__internal::{{Box}}; 454 455 {module} 456 }} 457 " 458 ) 459 }; 460 let all_func_flags = generator.all_func_flags; 461 self.import_interfaces.push(ImportInterface { 462 id: *id, 463 contents: module, 464 name: self.interface_names[id].clone(), 465 all_func_flags, 466 }); 467 468 let interface_path = self.import_interface_path(id); 469 self.interface_link_options[id] 470 .write_impl_from_world(&mut self.src, &interface_path); 471 } 472 WorldItem::Type(ty) => { 473 let name = match name { 474 WorldKey::Name(name) => name, 475 WorldKey::Interface(_) => unreachable!(), 476 }; 477 generator.define_type(name, *ty); 478 let body = mem::take(&mut generator.src); 479 self.src.push_str(&body); 480 } 481 }; 482 } 483 484 fn export(&mut self, resolve: &Resolve, name: &WorldKey, item: &WorldItem) { 485 let wt = self.wasmtime_path(); 486 let mut generator = InterfaceGenerator::new(self, resolve); 487 let field; 488 let ty; 489 let ty_index; 490 let load; 491 let get_index; 492 match item { 493 WorldItem::Function(func) => { 494 generator.define_rust_guest_export(resolve, None, func); 495 let body = mem::take(&mut generator.src).into(); 496 load = generator.extract_typed_function(func).1; 497 assert!(generator.src.is_empty()); 498 generator.generator.exports.funcs.push(body); 499 ty_index = format!("{wt}::component::ComponentExportIndex"); 500 field = func_field_name(resolve, func); 501 ty = format!("{wt}::component::Func"); 502 let sig = generator.typedfunc_sig(func, TypeMode::AllBorrowed("'_")); 503 let typecheck = format!( 504 "match item {{ 505 {wt}::component::types::ComponentItem::ComponentFunc(func) => {{ 506 {wt}::error::Context::context( 507 func.typecheck::<{sig}>(&_instance_type), 508 \"type-checking export func `{0}`\" 509 )?; 510 index 511 }} 512 _ => Err({wt}::format_err!(\"export `{0}` is not a function\"))?, 513 }}", 514 func.name 515 ); 516 get_index = format!( 517 "{{ let (item, index) = _component.get_export(None, \"{}\") 518 .ok_or_else(|| {wt}::format_err!(\"no export `{0}` found\"))?; 519 {typecheck} 520 }}", 521 func.name 522 ); 523 } 524 WorldItem::Type(_) => unreachable!(), 525 WorldItem::Interface { id, .. } => { 526 generator 527 .generator 528 .interface_last_seen_as_import 529 .insert(*id, false); 530 generator.generator.name_interface(resolve, *id, name, true); 531 generator.current_interface = Some((*id, name, true)); 532 generator.types(*id); 533 let struct_name = "Guest"; 534 let iface = &resolve.interfaces[*id]; 535 let iface_name = match name { 536 WorldKey::Name(name) => name, 537 WorldKey::Interface(_) => iface.name.as_ref().unwrap(), 538 }; 539 uwriteln!(generator.src, "#[derive(Clone)]"); 540 uwriteln!(generator.src, "pub struct {struct_name} {{"); 541 for (_, func) in iface.functions.iter() { 542 uwriteln!( 543 generator.src, 544 "{}: {wt}::component::Func,", 545 func_field_name(resolve, func) 546 ); 547 } 548 uwriteln!(generator.src, "}}"); 549 550 uwriteln!(generator.src, "#[derive(Clone)]"); 551 uwriteln!(generator.src, "pub struct {struct_name}Indices {{"); 552 for (_, func) in iface.functions.iter() { 553 uwriteln!( 554 generator.src, 555 "{}: {wt}::component::ComponentExportIndex,", 556 func_field_name(resolve, func) 557 ); 558 } 559 uwriteln!(generator.src, "}}"); 560 561 uwriteln!(generator.src, "impl {struct_name}Indices {{"); 562 let instance_name = resolve.name_world_key(name); 563 uwrite!( 564 generator.src, 565 " 566 /// Constructor for [`{struct_name}Indices`] which takes a 567 /// [`Component`]({wt}::component::Component) as input and can be executed 568 /// before instantiation. 569 /// 570 /// This constructor can be used to front-load string lookups to find exports 571 /// within a component. 572 pub fn new<_T>( 573 _instance_pre: &{wt}::component::InstancePre<_T>, 574 ) -> {wt}::Result<{struct_name}Indices> {{ 575 let instance = _instance_pre.component().get_export_index(None, \"{instance_name}\") 576 .ok_or_else(|| {wt}::format_err!(\"no exported instance named `{instance_name}`\"))?; 577 let mut lookup = move |name| {{ 578 _instance_pre.component().get_export_index(Some(&instance), name).ok_or_else(|| {{ 579 {wt}::format_err!( 580 \"instance export `{instance_name}` does \\ 581 not have export `{{name}}`\" 582 ) 583 }}) 584 }}; 585 let _ = &mut lookup; 586 " 587 ); 588 let mut fields = Vec::new(); 589 for (_, func) in iface.functions.iter() { 590 let name = func_field_name(resolve, func); 591 uwriteln!(generator.src, "let {name} = lookup(\"{}\")?;", func.name); 592 fields.push(name); 593 } 594 uwriteln!(generator.src, "Ok({struct_name}Indices {{"); 595 for name in fields { 596 uwriteln!(generator.src, "{name},"); 597 } 598 uwriteln!(generator.src, "}})"); 599 uwriteln!(generator.src, "}}"); // end `fn _new` 600 601 uwrite!( 602 generator.src, 603 " 604 pub fn load( 605 &self, 606 mut store: impl {wt}::AsContextMut, 607 instance: &{wt}::component::Instance, 608 ) -> {wt}::Result<{struct_name}> {{ 609 let _instance = instance; 610 let _instance_pre = _instance.instance_pre(&store); 611 let _instance_type = _instance_pre.instance_type(); 612 let mut store = store.as_context_mut(); 613 let _ = &mut store; 614 " 615 ); 616 let mut fields = Vec::new(); 617 for (_, func) in iface.functions.iter() { 618 let (name, getter) = generator.extract_typed_function(func); 619 uwriteln!(generator.src, "let {name} = {getter};"); 620 fields.push(name); 621 } 622 uwriteln!(generator.src, "Ok({struct_name} {{"); 623 for name in fields { 624 uwriteln!(generator.src, "{name},"); 625 } 626 uwriteln!(generator.src, "}})"); 627 uwriteln!(generator.src, "}}"); // end `fn new` 628 uwriteln!(generator.src, "}}"); // end `impl {struct_name}Indices` 629 630 uwriteln!(generator.src, "impl {struct_name} {{"); 631 let mut resource_methods = IndexMap::new(); 632 633 for (_, func) in iface.functions.iter() { 634 match func.kind.resource() { 635 None => { 636 generator.define_rust_guest_export(resolve, Some(name), func); 637 } 638 Some(id) => { 639 resource_methods.entry(id).or_insert(Vec::new()).push(func); 640 } 641 } 642 } 643 644 for (id, _) in resource_methods.iter() { 645 let name = resolve.types[*id].name.as_ref().unwrap(); 646 let snake = name.to_snake_case(); 647 let camel = name.to_upper_camel_case(); 648 uwriteln!( 649 generator.src, 650 "pub fn {snake}(&self) -> Guest{camel}<'_> {{ 651 Guest{camel} {{ funcs: self }} 652 }}" 653 ); 654 } 655 656 uwriteln!(generator.src, "}}"); 657 658 for (id, methods) in resource_methods { 659 let resource_name = resolve.types[id].name.as_ref().unwrap(); 660 let camel = resource_name.to_upper_camel_case(); 661 uwriteln!(generator.src, "impl Guest{camel}<'_> {{"); 662 for method in methods { 663 generator.define_rust_guest_export(resolve, Some(name), method); 664 } 665 uwriteln!(generator.src, "}}"); 666 } 667 668 let module = &generator.src[..]; 669 let snake = to_rust_ident(iface_name); 670 671 let module = format!( 672 " 673 #[allow(clippy::all)] 674 pub mod {snake} {{ 675 #[allow(unused_imports)] 676 use {wt}::component::__internal::Box; 677 678 {module} 679 }} 680 " 681 ); 682 let pkgname = match name { 683 WorldKey::Name(_) => None, 684 WorldKey::Interface(_) => { 685 Some(resolve.packages[iface.package.unwrap()].name.clone()) 686 } 687 }; 688 self.exports 689 .modules 690 .push((*id, module, self.interface_names[id].clone())); 691 692 let (path, method_name) = match pkgname { 693 Some(pkgname) => ( 694 format!( 695 "exports::{}::{}::{snake}::{struct_name}", 696 pkgname.namespace.to_snake_case(), 697 self.name_package_module(resolve, iface.package.unwrap()), 698 ), 699 format!( 700 "{}_{}_{snake}", 701 pkgname.namespace.to_snake_case(), 702 self.name_package_module(resolve, iface.package.unwrap()) 703 ), 704 ), 705 None => (format!("exports::{snake}::{struct_name}"), snake.clone()), 706 }; 707 field = format!("interface{}", self.exports.fields.len()); 708 load = format!("self.{field}.load(&mut store, &_instance)?"); 709 self.exports.funcs.push(format!( 710 " 711 pub fn {method_name}(&self) -> &{path} {{ 712 &self.{field} 713 }} 714 ", 715 )); 716 ty_index = format!("{path}Indices"); 717 ty = path; 718 get_index = format!("{ty_index}::new(_instance_pre)?"); 719 } 720 } 721 let prev = self.exports.fields.insert( 722 field, 723 ExportField { 724 ty, 725 ty_index, 726 load, 727 get_index, 728 }, 729 ); 730 assert!(prev.is_none()); 731 } 732 733 fn build_world_struct(&mut self, resolve: &Resolve, world: WorldId) { 734 let wt = self.wasmtime_path(); 735 let world_name = &resolve.worlds[world].name; 736 let camel = to_rust_upper_camel_case(&world_name); 737 uwriteln!( 738 self.src, 739 " 740 /// Auto-generated bindings for a pre-instantiated version of a 741 /// component which implements the world `{world_name}`. 742 /// 743 /// This structure is created through [`{camel}Pre::new`] which 744 /// takes a [`InstancePre`]({wt}::component::InstancePre) that 745 /// has been created through a [`Linker`]({wt}::component::Linker). 746 /// 747 /// For more information see [`{camel}`] as well. 748 pub struct {camel}Pre<T: 'static> {{ 749 instance_pre: {wt}::component::InstancePre<T>, 750 indices: {camel}Indices, 751 }} 752 753 impl<T: 'static> Clone for {camel}Pre<T> {{ 754 fn clone(&self) -> Self {{ 755 Self {{ 756 instance_pre: self.instance_pre.clone(), 757 indices: self.indices.clone(), 758 }} 759 }} 760 }} 761 762 impl<_T: 'static> {camel}Pre<_T> {{ 763 /// Creates a new copy of `{camel}Pre` bindings which can then 764 /// be used to instantiate into a particular store. 765 /// 766 /// This method may fail if the component behind `instance_pre` 767 /// does not have the required exports. 768 pub fn new(instance_pre: {wt}::component::InstancePre<_T>) -> {wt}::Result<Self> {{ 769 let indices = {camel}Indices::new(&instance_pre)?; 770 Ok(Self {{ instance_pre, indices }}) 771 }} 772 773 pub fn engine(&self) -> &{wt}::Engine {{ 774 self.instance_pre.engine() 775 }} 776 777 pub fn instance_pre(&self) -> &{wt}::component::InstancePre<_T> {{ 778 &self.instance_pre 779 }} 780 781 /// Instantiates a new instance of [`{camel}`] within the 782 /// `store` provided. 783 /// 784 /// This function will use `self` as the pre-instantiated 785 /// instance to perform instantiation. Afterwards the preloaded 786 /// indices in `self` are used to lookup all exports on the 787 /// resulting instance. 788 pub fn instantiate( 789 &self, 790 mut store: impl {wt}::AsContextMut<Data = _T>, 791 ) -> {wt}::Result<{camel}> {{ 792 let mut store = store.as_context_mut(); 793 let instance = self.instance_pre.instantiate(&mut store)?; 794 self.indices.load(&mut store, &instance) 795 }} 796 }} 797 " 798 ); 799 800 if cfg!(feature = "async") { 801 uwriteln!( 802 self.src, 803 " 804 impl<_T: Send + 'static> {camel}Pre<_T> {{ 805 /// Same as [`Self::instantiate`], except with `async`. 806 pub async fn instantiate_async( 807 &self, 808 mut store: impl {wt}::AsContextMut<Data = _T>, 809 ) -> {wt}::Result<{camel}> {{ 810 let mut store = store.as_context_mut(); 811 let instance = self.instance_pre.instantiate_async(&mut store).await?; 812 self.indices.load(&mut store, &instance) 813 }} 814 }} 815 " 816 ); 817 } 818 819 uwriteln!( 820 self.src, 821 " 822 /// Auto-generated bindings for index of the exports of 823 /// `{world_name}`. 824 /// 825 /// This is an implementation detail of [`{camel}Pre`] and can 826 /// be constructed if needed as well. 827 /// 828 /// For more information see [`{camel}`] as well. 829 #[derive(Clone)] 830 pub struct {camel}Indices {{" 831 ); 832 for (name, field) in self.exports.fields.iter() { 833 uwriteln!(self.src, "{name}: {},", field.ty_index); 834 } 835 self.src.push_str("}\n"); 836 837 uwriteln!( 838 self.src, 839 " 840 /// Auto-generated bindings for an instance a component which 841 /// implements the world `{world_name}`. 842 /// 843 /// This structure can be created through a number of means 844 /// depending on your requirements and what you have on hand: 845 /// 846 /// * The most convenient way is to use 847 /// [`{camel}::instantiate`] which only needs a 848 /// [`Store`], [`Component`], and [`Linker`]. 849 /// 850 /// * Alternatively you can create a [`{camel}Pre`] ahead of 851 /// time with a [`Component`] to front-load string lookups 852 /// of exports once instead of per-instantiation. This 853 /// method then uses [`{camel}Pre::instantiate`] to 854 /// create a [`{camel}`]. 855 /// 856 /// * If you've instantiated the instance yourself already 857 /// then you can use [`{camel}::new`]. 858 /// 859 /// These methods are all equivalent to one another and move 860 /// around the tradeoff of what work is performed when. 861 /// 862 /// [`Store`]: {wt}::Store 863 /// [`Component`]: {wt}::component::Component 864 /// [`Linker`]: {wt}::component::Linker 865 pub struct {camel} {{" 866 ); 867 for (name, field) in self.exports.fields.iter() { 868 uwriteln!(self.src, "{name}: {},", field.ty); 869 } 870 self.src.push_str("}\n"); 871 872 let world_trait = self.world_imports_trait(resolve, world); 873 874 uwriteln!(self.src, "const _: () = {{"); 875 876 uwriteln!( 877 self.src, 878 "impl {camel}Indices {{ 879 /// Creates a new copy of `{camel}Indices` bindings which can then 880 /// be used to instantiate into a particular store. 881 /// 882 /// This method may fail if the component does not have the 883 /// required exports. 884 pub fn new<_T>(_instance_pre: &{wt}::component::InstancePre<_T>) -> {wt}::Result<Self> {{ 885 let _component = _instance_pre.component(); 886 let _instance_type = _instance_pre.instance_type(); 887 ", 888 ); 889 for (name, field) in self.exports.fields.iter() { 890 uwriteln!(self.src, "let {name} = {};", field.get_index); 891 } 892 uwriteln!(self.src, "Ok({camel}Indices {{"); 893 for (name, _) in self.exports.fields.iter() { 894 uwriteln!(self.src, "{name},"); 895 } 896 uwriteln!(self.src, "}})"); 897 uwriteln!(self.src, "}}"); // close `fn new` 898 899 uwriteln!( 900 self.src, 901 " 902 /// Uses the indices stored in `self` to load an instance 903 /// of [`{camel}`] from the instance provided. 904 /// 905 /// Note that at this time this method will additionally 906 /// perform type-checks of all exports. 907 pub fn load( 908 &self, 909 mut store: impl {wt}::AsContextMut, 910 instance: &{wt}::component::Instance, 911 ) -> {wt}::Result<{camel}> {{ 912 let _ = &mut store; 913 let _instance = instance; 914 ", 915 ); 916 for (name, field) in self.exports.fields.iter() { 917 uwriteln!(self.src, "let {name} = {};", field.load); 918 } 919 uwriteln!(self.src, "Ok({camel} {{"); 920 for (name, _) in self.exports.fields.iter() { 921 uwriteln!(self.src, "{name},"); 922 } 923 uwriteln!(self.src, "}})"); 924 uwriteln!(self.src, "}}"); // close `fn load` 925 uwriteln!(self.src, "}}"); // close `impl {camel}Indices` 926 927 uwriteln!( 928 self.src, 929 "impl {camel} {{ 930 /// Convenience wrapper around [`{camel}Pre::new`] and 931 /// [`{camel}Pre::instantiate`]. 932 pub fn instantiate<_T>( 933 store: impl {wt}::AsContextMut<Data = _T>, 934 component: &{wt}::component::Component, 935 linker: &{wt}::component::Linker<_T>, 936 ) -> {wt}::Result<{camel}> {{ 937 let pre = linker.instantiate_pre(component)?; 938 {camel}Pre::new(pre)?.instantiate(store) 939 }} 940 941 /// Convenience wrapper around [`{camel}Indices::new`] and 942 /// [`{camel}Indices::load`]. 943 pub fn new( 944 mut store: impl {wt}::AsContextMut, 945 instance: &{wt}::component::Instance, 946 ) -> {wt}::Result<{camel}> {{ 947 let indices = {camel}Indices::new(&instance.instance_pre(&store))?; 948 indices.load(&mut store, instance) 949 }} 950 ", 951 ); 952 953 if cfg!(feature = "async") { 954 uwriteln!( 955 self.src, 956 " 957 /// Convenience wrapper around [`{camel}Pre::new`] and 958 /// [`{camel}Pre::instantiate_async`]. 959 pub async fn instantiate_async<_T>( 960 store: impl {wt}::AsContextMut<Data = _T>, 961 component: &{wt}::component::Component, 962 linker: &{wt}::component::Linker<_T>, 963 ) -> {wt}::Result<{camel}> 964 where _T: Send, 965 {{ 966 let pre = linker.instantiate_pre(component)?; 967 {camel}Pre::new(pre)?.instantiate_async(store).await 968 }} 969 ", 970 ); 971 } 972 self.world_add_to_linker(resolve, world, world_trait.as_ref()); 973 974 for func in self.exports.funcs.iter() { 975 self.src.push_str(func); 976 } 977 978 uwriteln!(self.src, "}}"); // close `impl {camel}` 979 980 uwriteln!(self.src, "}};"); // close `const _: () = ... 981 } 982 983 fn finish(&mut self, resolve: &Resolve, world: WorldId) -> anyhow::Result<String> { 984 let remapping_keys = self.opts.with.keys().cloned().collect::<HashSet<String>>(); 985 986 let mut unused_keys = remapping_keys 987 .difference(&self.used_with_opts) 988 .map(|s| s.as_str()) 989 .collect::<Vec<&str>>(); 990 991 unused_keys.sort(); 992 993 if !unused_keys.is_empty() { 994 anyhow::bail!( 995 "interfaces were specified in the `with` config option but are not referenced in the target world: {unused_keys:?}" 996 ); 997 } 998 999 if !self.opts.only_interfaces { 1000 self.build_world_struct(resolve, world) 1001 } 1002 1003 self.opts.imports.assert_all_rules_used("imports")?; 1004 self.opts.exports.assert_all_rules_used("exports")?; 1005 1006 let imports = mem::take(&mut self.import_interfaces); 1007 self.emit_modules( 1008 imports 1009 .into_iter() 1010 .map(|i| (i.id, i.contents, i.name)) 1011 .collect(), 1012 ); 1013 1014 let exports = mem::take(&mut self.exports.modules); 1015 self.emit_modules(exports); 1016 1017 let mut src = mem::take(&mut self.src); 1018 if self.opts.rustfmt { 1019 let mut child = Command::new("rustfmt") 1020 .arg("--edition=2018") 1021 .stdin(Stdio::piped()) 1022 .stdout(Stdio::piped()) 1023 .spawn() 1024 .expect("failed to spawn `rustfmt`"); 1025 child 1026 .stdin 1027 .take() 1028 .unwrap() 1029 .write_all(src.as_bytes()) 1030 .unwrap(); 1031 src.as_mut_string().truncate(0); 1032 child 1033 .stdout 1034 .take() 1035 .unwrap() 1036 .read_to_string(src.as_mut_string()) 1037 .unwrap(); 1038 let status = child.wait().unwrap(); 1039 assert!(status.success()); 1040 } 1041 1042 Ok(src.into()) 1043 } 1044 1045 fn emit_modules(&mut self, modules: Vec<(InterfaceId, String, InterfaceName)>) { 1046 #[derive(Default)] 1047 struct Module { 1048 submodules: BTreeMap<String, Module>, 1049 contents: Vec<String>, 1050 } 1051 let mut map = Module::default(); 1052 for (_, module, name) in modules { 1053 let path = match name { 1054 InterfaceName::Remapped { local_path, .. } => local_path, 1055 InterfaceName::Path(path) => path, 1056 }; 1057 let mut cur = &mut map; 1058 for name in path[..path.len() - 1].iter() { 1059 cur = cur 1060 .submodules 1061 .entry(name.clone()) 1062 .or_insert(Module::default()); 1063 } 1064 cur.contents.push(module); 1065 } 1066 1067 emit(&mut self.src, map); 1068 1069 fn emit(me: &mut Source, module: Module) { 1070 for (name, submodule) in module.submodules { 1071 uwriteln!(me, "pub mod {name} {{"); 1072 emit(me, submodule); 1073 uwriteln!(me, "}}"); 1074 } 1075 for submodule in module.contents { 1076 uwriteln!(me, "{submodule}"); 1077 } 1078 } 1079 } 1080 1081 /// Attempts to find the `key`, possibly with the resource projection 1082 /// `item`, within the `with` map provided to bindings configuration. 1083 fn lookup_replacement( 1084 &mut self, 1085 resolve: &Resolve, 1086 key: &WorldKey, 1087 item: Option<&str>, 1088 ) -> Option<String> { 1089 let item = match item { 1090 Some(item) => LookupItem::Name(item), 1091 None => LookupItem::None, 1092 }; 1093 1094 for (lookup, mut projection) in lookup_keys(resolve, key, item) { 1095 if let Some(renamed) = self.opts.with.get(&lookup) { 1096 projection.push(renamed.clone()); 1097 projection.reverse(); 1098 self.used_with_opts.insert(lookup); 1099 return Some(projection.join("::")); 1100 } 1101 } 1102 1103 None 1104 } 1105 1106 fn wasmtime_path(&self) -> String { 1107 self.opts 1108 .wasmtime_crate 1109 .clone() 1110 .unwrap_or("wasmtime".to_string()) 1111 } 1112 } 1113 1114 enum LookupItem<'a> { 1115 None, 1116 Name(&'a str), 1117 InterfaceNoPop, 1118 } 1119 1120 fn lookup_keys( 1121 resolve: &Resolve, 1122 key: &WorldKey, 1123 item: LookupItem<'_>, 1124 ) -> Vec<(String, Vec<String>)> { 1125 struct Name<'a> { 1126 prefix: Prefix, 1127 item: Option<&'a str>, 1128 } 1129 1130 #[derive(Copy, Clone)] 1131 enum Prefix { 1132 Namespace(PackageId), 1133 UnversionedPackage(PackageId), 1134 VersionedPackage(PackageId), 1135 UnversionedInterface(InterfaceId), 1136 VersionedInterface(InterfaceId), 1137 } 1138 1139 let prefix = match key { 1140 WorldKey::Interface(id) => Prefix::VersionedInterface(*id), 1141 1142 // Non-interface-keyed names don't get the lookup logic below, 1143 // they're relatively uncommon so only lookup the precise key here. 1144 WorldKey::Name(key) => { 1145 let to_lookup = match item { 1146 LookupItem::Name(item) => format!("{key}.{item}"), 1147 LookupItem::None | LookupItem::InterfaceNoPop => key.to_string(), 1148 }; 1149 return vec![(to_lookup, Vec::new())]; 1150 } 1151 }; 1152 1153 // Here names are iteratively attempted as `key` + `item` is "walked to 1154 // its root" and each attempt is consulted in `self.opts.with`. This 1155 // loop will start at the leaf, the most specific path, and then walk to 1156 // the root, popping items, trying to find a result. 1157 // 1158 // Each time a name is "popped" the projection from the next path is 1159 // pushed onto `projection`. This means that if we actually find a match 1160 // then `projection` is a collection of namespaces that results in the 1161 // final replacement name. 1162 let (interface_required, item) = match item { 1163 LookupItem::None => (false, None), 1164 LookupItem::Name(s) => (false, Some(s)), 1165 LookupItem::InterfaceNoPop => (true, None), 1166 }; 1167 let mut name = Name { prefix, item }; 1168 let mut projection = Vec::new(); 1169 let mut ret = Vec::new(); 1170 loop { 1171 let lookup = name.lookup_key(resolve); 1172 ret.push((lookup, projection.clone())); 1173 if !name.pop(resolve, &mut projection) { 1174 break; 1175 } 1176 if interface_required { 1177 match name.prefix { 1178 Prefix::VersionedInterface(_) | Prefix::UnversionedInterface(_) => {} 1179 _ => break, 1180 } 1181 } 1182 } 1183 1184 return ret; 1185 1186 impl<'a> Name<'a> { 1187 fn lookup_key(&self, resolve: &Resolve) -> String { 1188 let mut s = self.prefix.lookup_key(resolve); 1189 if let Some(item) = self.item { 1190 s.push_str("."); 1191 s.push_str(item); 1192 } 1193 s 1194 } 1195 1196 fn pop(&mut self, resolve: &'a Resolve, projection: &mut Vec<String>) -> bool { 1197 match (self.item, self.prefix) { 1198 // If this is a versioned resource name, try the unversioned 1199 // resource name next. 1200 (Some(_), Prefix::VersionedInterface(id)) => { 1201 self.prefix = Prefix::UnversionedInterface(id); 1202 true 1203 } 1204 // If this is an unversioned resource name then time to 1205 // ignore the resource itself and move on to the next most 1206 // specific item, versioned interface names. 1207 (Some(item), Prefix::UnversionedInterface(id)) => { 1208 self.prefix = Prefix::VersionedInterface(id); 1209 self.item = None; 1210 projection.push(item.to_upper_camel_case()); 1211 true 1212 } 1213 (Some(_), _) => unreachable!(), 1214 (None, _) => self.prefix.pop(resolve, projection), 1215 } 1216 } 1217 } 1218 1219 impl Prefix { 1220 fn lookup_key(&self, resolve: &Resolve) -> String { 1221 match *self { 1222 Prefix::Namespace(id) => resolve.packages[id].name.namespace.clone(), 1223 Prefix::UnversionedPackage(id) => { 1224 let mut name = resolve.packages[id].name.clone(); 1225 name.version = None; 1226 name.to_string() 1227 } 1228 Prefix::VersionedPackage(id) => resolve.packages[id].name.to_string(), 1229 Prefix::UnversionedInterface(id) => { 1230 let id = resolve.id_of(id).unwrap(); 1231 match id.find('@') { 1232 Some(i) => id[..i].to_string(), 1233 None => id, 1234 } 1235 } 1236 Prefix::VersionedInterface(id) => resolve.id_of(id).unwrap(), 1237 } 1238 } 1239 1240 fn pop(&mut self, resolve: &Resolve, projection: &mut Vec<String>) -> bool { 1241 *self = match *self { 1242 // try the unversioned interface next 1243 Prefix::VersionedInterface(id) => Prefix::UnversionedInterface(id), 1244 // try this interface's versioned package next 1245 Prefix::UnversionedInterface(id) => { 1246 let iface = &resolve.interfaces[id]; 1247 let name = iface.name.as_ref().unwrap(); 1248 projection.push(to_rust_ident(name)); 1249 Prefix::VersionedPackage(iface.package.unwrap()) 1250 } 1251 // try the unversioned package next 1252 Prefix::VersionedPackage(id) => Prefix::UnversionedPackage(id), 1253 // try this package's namespace next 1254 Prefix::UnversionedPackage(id) => { 1255 let name = &resolve.packages[id].name; 1256 projection.push(to_rust_ident(&name.name)); 1257 Prefix::Namespace(id) 1258 } 1259 // nothing left to try any more 1260 Prefix::Namespace(_) => return false, 1261 }; 1262 true 1263 } 1264 } 1265 } 1266 1267 impl Wasmtime { 1268 fn has_world_imports_trait(&self, resolve: &Resolve, world: WorldId) -> bool { 1269 !self.import_functions.is_empty() || get_world_resources(resolve, world).count() > 0 1270 } 1271 1272 fn world_imports_trait(&mut self, resolve: &Resolve, world: WorldId) -> Option<GeneratedTrait> { 1273 if !self.has_world_imports_trait(resolve, world) { 1274 return None; 1275 } 1276 1277 let world_camel = to_rust_upper_camel_case(&resolve.worlds[world].name); 1278 1279 let functions = self.import_functions.clone(); 1280 let mut generator = InterfaceGenerator::new(self, resolve); 1281 let generated_trait = generator.generate_trait( 1282 &format!("{world_camel}Imports"), 1283 &functions 1284 .iter() 1285 .filter(|f| f.kind.resource().is_none()) 1286 .collect::<Vec<_>>(), 1287 &[], 1288 &get_world_resources(resolve, world).collect::<Vec<_>>(), 1289 ); 1290 let src = String::from(mem::take(&mut generator.src)); 1291 self.src.push_str(&src); 1292 Some(generated_trait) 1293 } 1294 1295 fn import_interface_paths(&self) -> Vec<(InterfaceId, String)> { 1296 self.import_interfaces 1297 .iter() 1298 .map(|i| { 1299 let path = match &i.name { 1300 InterfaceName::Path(path) => path.join("::"), 1301 InterfaceName::Remapped { name_at_root, .. } => name_at_root.clone(), 1302 }; 1303 (i.id, path) 1304 }) 1305 .collect() 1306 } 1307 1308 fn import_interface_path(&self, id: &InterfaceId) -> String { 1309 match &self.interface_names[id] { 1310 InterfaceName::Path(path) => path.join("::"), 1311 InterfaceName::Remapped { name_at_root, .. } => name_at_root.clone(), 1312 } 1313 } 1314 1315 fn import_interface_all_func_flags(&self, id: InterfaceId) -> FunctionFlags { 1316 for i in self.import_interfaces.iter() { 1317 if id != i.id { 1318 continue; 1319 } 1320 1321 return i.all_func_flags; 1322 } 1323 unreachable!() 1324 } 1325 1326 fn world_host_traits( 1327 &self, 1328 world_trait: Option<&GeneratedTrait>, 1329 ) -> (Vec<String>, Vec<String>) { 1330 let mut without_store = Vec::new(); 1331 let mut without_store_async = false; 1332 let mut with_store = Vec::new(); 1333 let mut with_store_async = false; 1334 for (id, path) in self.import_interface_paths() { 1335 without_store.push(format!("{path}::Host")); 1336 let flags = self.import_interface_all_func_flags(id); 1337 without_store_async = without_store_async || flags.contains(FunctionFlags::ASYNC); 1338 1339 // Note that the requirement of `HostWithStore` is technically 1340 // dependent on `FunctionFlags::STORE`, but when `with` is in use we 1341 // don't necessarily know whether the other bindings generation 1342 // specified this flag or not. To handle that always assume that a 1343 // `HostWithStore` bound is needed. 1344 with_store.push(format!("{path}::HostWithStore")); 1345 with_store_async = with_store_async || flags.contains(FunctionFlags::ASYNC); 1346 } 1347 if let Some(world_trait) = world_trait { 1348 without_store.push(world_trait.name.clone()); 1349 without_store_async = 1350 without_store_async || world_trait.all_func_flags.contains(FunctionFlags::ASYNC); 1351 1352 if world_trait.with_store_name.is_some() { 1353 with_store.extend(world_trait.with_store_name.clone()); 1354 with_store_async = 1355 with_store_async || world_trait.all_func_flags.contains(FunctionFlags::ASYNC); 1356 } 1357 } 1358 if without_store_async { 1359 without_store.push("Send".to_string()); 1360 } 1361 if with_store_async { 1362 with_store.push("Send".to_string()); 1363 } 1364 (without_store, with_store) 1365 } 1366 1367 fn world_add_to_linker( 1368 &mut self, 1369 resolve: &Resolve, 1370 world: WorldId, 1371 world_trait: Option<&GeneratedTrait>, 1372 ) { 1373 let has_world_imports_trait = self.has_world_imports_trait(resolve, world); 1374 if self.import_interfaces.is_empty() && !has_world_imports_trait { 1375 return; 1376 } 1377 1378 let (options_param, options_arg) = if self.world_link_options.has_any() { 1379 ("options: &LinkOptions,", ", options") 1380 } else { 1381 ("", "") 1382 }; 1383 1384 let mut all_func_flags = FunctionFlags::empty(); 1385 if let Some(world_trait) = world_trait { 1386 all_func_flags |= world_trait.all_func_flags; 1387 } 1388 for i in self.import_interfaces.iter() { 1389 all_func_flags |= i.all_func_flags; 1390 } 1391 1392 all_func_flags |= self.opts.imports.default; 1393 all_func_flags |= self.opts.exports.default; 1394 1395 let opt_t_send_bound = 1396 if all_func_flags.contains(FunctionFlags::ASYNC) || self.opts.require_store_data_send { 1397 "+ Send" 1398 } else { 1399 "" 1400 }; 1401 1402 let wt = self.wasmtime_path(); 1403 if let Some(world_trait) = world_trait { 1404 let d_bound = match &world_trait.with_store_name { 1405 Some(name) => name.clone(), 1406 None => format!("{wt}::component::HasData"), 1407 }; 1408 uwrite!( 1409 self.src, 1410 " 1411 pub fn add_to_linker_imports<T, D>( 1412 linker: &mut {wt}::component::Linker<T>, 1413 {options_param} 1414 host_getter: fn(&mut T) -> D::Data<'_>, 1415 ) -> {wt}::Result<()> 1416 where 1417 D: {d_bound}, 1418 for<'a> D::Data<'a>: {name}, 1419 T: 'static {opt_t_send_bound} 1420 {{ 1421 let mut linker = linker.root(); 1422 ", 1423 name = world_trait.name, 1424 ); 1425 let gate = FeatureGate::open(&mut self.src, &resolve.worlds[world].stability); 1426 for (ty, _name) in get_world_resources(resolve, world) { 1427 self.generate_add_resource_to_linker(None, None, "linker", resolve, ty); 1428 } 1429 for f in self.import_functions.clone() { 1430 let mut generator = InterfaceGenerator::new(self, resolve); 1431 generator.generate_add_function_to_linker(TypeOwner::World(world), &f, "linker"); 1432 let src = String::from(generator.src); 1433 self.src.push_str(&src); 1434 self.src.push_str("\n"); 1435 } 1436 gate.close(&mut self.src); 1437 uwriteln!(self.src, "Ok(())\n}}"); 1438 } 1439 1440 let (sync_bounds, concurrent_bounds) = self.world_host_traits(world_trait); 1441 let sync_bounds = sync_bounds.join(" + "); 1442 let concurrent_bounds = concurrent_bounds.join(" + "); 1443 let d_bounds = if !concurrent_bounds.is_empty() { 1444 concurrent_bounds 1445 } else { 1446 format!("{wt}::component::HasData") 1447 }; 1448 1449 uwriteln!( 1450 self.src, 1451 " 1452 pub fn add_to_linker<T, D>( 1453 linker: &mut {wt}::component::Linker<T>, 1454 {options_param} 1455 host_getter: fn(&mut T) -> D::Data<'_>, 1456 ) -> {wt}::Result<()> 1457 where 1458 D: {d_bounds}, 1459 for<'a> D::Data<'a>: {sync_bounds}, 1460 T: 'static {opt_t_send_bound} 1461 {{ 1462 " 1463 ); 1464 let gate = FeatureGate::open(&mut self.src, &resolve.worlds[world].stability); 1465 if has_world_imports_trait { 1466 uwriteln!( 1467 self.src, 1468 "Self::add_to_linker_imports::<T, D>(linker {options_arg}, host_getter)?;" 1469 ); 1470 } 1471 for (interface_id, path) in self.import_interface_paths() { 1472 let options_arg = if self.interface_link_options[&interface_id].has_any() { 1473 ", &options.into()" 1474 } else { 1475 "" 1476 }; 1477 1478 let import_stability = resolve.worlds[world] 1479 .imports 1480 .iter() 1481 .filter_map(|(_, i)| match i { 1482 WorldItem::Interface { id, stability } if *id == interface_id => { 1483 Some(stability.clone()) 1484 } 1485 _ => None, 1486 }) 1487 .next() 1488 .unwrap_or(Stability::Unknown); 1489 1490 let gate = FeatureGate::open(&mut self.src, &import_stability); 1491 uwriteln!( 1492 self.src, 1493 "{path}::add_to_linker::<T, D>(linker {options_arg}, host_getter)?;" 1494 ); 1495 gate.close(&mut self.src); 1496 } 1497 gate.close(&mut self.src); 1498 uwriteln!(self.src, "Ok(())\n}}"); 1499 } 1500 1501 fn generate_add_resource_to_linker( 1502 &mut self, 1503 key: Option<&WorldKey>, 1504 src: Option<&mut Source>, 1505 inst: &str, 1506 resolve: &Resolve, 1507 ty: TypeId, 1508 ) { 1509 let ty = &resolve.types[ty]; 1510 let name = ty.name.as_ref().unwrap(); 1511 let stability = &ty.stability; 1512 let wt = self.wasmtime_path(); 1513 let src = src.unwrap_or(&mut self.src); 1514 let gate = FeatureGate::open(src, stability); 1515 let camel = name.to_upper_camel_case(); 1516 1517 let flags = self.opts.imports.resource_drop_flags(resolve, key, name); 1518 if flags.contains(FunctionFlags::ASYNC) { 1519 if flags.contains(FunctionFlags::STORE) { 1520 uwriteln!( 1521 src, 1522 "{inst}.resource_concurrent( 1523 \"{name}\", 1524 {wt}::component::ResourceType::host::<{camel}>(), 1525 move |caller: &{wt}::component::Accessor::<T>, rep| {{ 1526 {wt}::component::__internal::Box::pin(async move {{ 1527 let accessor = &caller.with_getter(host_getter); 1528 Host{camel}WithStore::drop(accessor, {wt}::component::Resource::new_own(rep)).await 1529 }}) 1530 }}, 1531 )?;" 1532 ) 1533 } else { 1534 uwriteln!( 1535 src, 1536 "{inst}.resource_async( 1537 \"{name}\", 1538 {wt}::component::ResourceType::host::<{camel}>(), 1539 move |mut store, rep| {{ 1540 {wt}::component::__internal::Box::new(async move {{ 1541 Host{camel}::drop(&mut host_getter(store.data_mut()), {wt}::component::Resource::new_own(rep)).await 1542 }}) 1543 }}, 1544 )?;" 1545 ) 1546 } 1547 } else { 1548 let (first_arg, trait_suffix) = if flags.contains(FunctionFlags::STORE) { 1549 ( 1550 format!("{wt}::component::Access::new(store, host_getter)"), 1551 "WithStore", 1552 ) 1553 } else { 1554 ("&mut host_getter(store.data_mut())".to_string(), "") 1555 }; 1556 uwriteln!( 1557 src, 1558 "{inst}.resource( 1559 \"{name}\", 1560 {wt}::component::ResourceType::host::<{camel}>(), 1561 move |mut store, rep| -> {wt}::Result<()> {{ 1562 1563 let resource = {wt}::component::Resource::new_own(rep); 1564 Host{camel}{trait_suffix}::drop({first_arg}, resource) 1565 }}, 1566 )?;", 1567 ) 1568 } 1569 gate.close(src); 1570 } 1571 } 1572 1573 struct InterfaceGenerator<'a> { 1574 src: Source, 1575 generator: &'a mut Wasmtime, 1576 resolve: &'a Resolve, 1577 current_interface: Option<(InterfaceId, &'a WorldKey, bool)>, 1578 all_func_flags: FunctionFlags, 1579 } 1580 1581 impl<'a> InterfaceGenerator<'a> { 1582 fn new(generator: &'a mut Wasmtime, resolve: &'a Resolve) -> InterfaceGenerator<'a> { 1583 InterfaceGenerator { 1584 src: Source::default(), 1585 generator, 1586 resolve, 1587 current_interface: None, 1588 all_func_flags: FunctionFlags::empty(), 1589 } 1590 } 1591 1592 fn types_imported(&self) -> bool { 1593 match self.current_interface { 1594 Some((_, _, is_export)) => !is_export, 1595 None => true, 1596 } 1597 } 1598 1599 fn types(&mut self, id: InterfaceId) { 1600 for (name, id) in self.resolve.interfaces[id].types.iter() { 1601 self.define_type(name, *id); 1602 } 1603 } 1604 1605 fn define_type(&mut self, name: &str, id: TypeId) { 1606 let ty = &self.resolve.types[id]; 1607 match &ty.kind { 1608 TypeDefKind::Record(record) => self.type_record(id, name, record, &ty.docs), 1609 TypeDefKind::Flags(flags) => self.type_flags(id, name, flags, &ty.docs), 1610 TypeDefKind::Tuple(tuple) => self.type_tuple(id, name, tuple, &ty.docs), 1611 TypeDefKind::Enum(enum_) => self.type_enum(id, name, enum_, &ty.docs), 1612 TypeDefKind::Variant(variant) => self.type_variant(id, name, variant, &ty.docs), 1613 TypeDefKind::Option(t) => self.type_option(id, name, t, &ty.docs), 1614 TypeDefKind::Result(r) => self.type_result(id, name, r, &ty.docs), 1615 TypeDefKind::List(t) => self.type_list(id, name, t, &ty.docs), 1616 TypeDefKind::Type(t) => self.type_alias(id, name, t, &ty.docs), 1617 TypeDefKind::Future(t) => self.type_future(id, name, t.as_ref(), &ty.docs), 1618 TypeDefKind::Stream(t) => self.type_stream(id, name, t.as_ref(), &ty.docs), 1619 TypeDefKind::Handle(handle) => self.type_handle(id, name, handle, &ty.docs), 1620 TypeDefKind::Resource => self.type_resource(id, name, ty, &ty.docs), 1621 TypeDefKind::Unknown => unreachable!(), 1622 TypeDefKind::FixedSizeList(..) => todo!(), 1623 TypeDefKind::Map(..) => todo!(), 1624 } 1625 } 1626 1627 fn type_handle(&mut self, id: TypeId, name: &str, handle: &Handle, docs: &Docs) { 1628 self.rustdoc(docs); 1629 let name = name.to_upper_camel_case(); 1630 uwriteln!(self.src, "pub type {name} = "); 1631 self.print_handle(handle); 1632 self.push_str(";\n"); 1633 self.assert_type(id, &name); 1634 } 1635 1636 fn type_resource(&mut self, id: TypeId, name: &str, _resource: &TypeDef, docs: &Docs) { 1637 let camel = name.to_upper_camel_case(); 1638 let wt = self.generator.wasmtime_path(); 1639 1640 if self.types_imported() { 1641 self.rustdoc(docs); 1642 1643 let replacement = match self.current_interface { 1644 Some((_, key, _)) => { 1645 self.generator 1646 .lookup_replacement(self.resolve, key, Some(name)) 1647 } 1648 None => { 1649 self.generator.used_with_opts.insert(name.into()); 1650 self.generator.opts.with.get(name).cloned() 1651 } 1652 }; 1653 match replacement { 1654 Some(path) => { 1655 uwriteln!( 1656 self.src, 1657 "pub use {}{path} as {camel};", 1658 self.path_to_root() 1659 ); 1660 } 1661 None => { 1662 uwriteln!(self.src, "pub enum {camel} {{}}"); 1663 } 1664 } 1665 1666 // Generate resource trait 1667 1668 let functions = get_resource_functions(self.resolve, id); 1669 let trait_ = self.generate_trait( 1670 &format!("Host{camel}"), 1671 &functions, 1672 &[ExtraTraitMethod::ResourceDrop { name }], 1673 &[], 1674 ); 1675 self.all_func_flags |= trait_.all_func_flags; 1676 } else { 1677 self.rustdoc(docs); 1678 uwriteln!( 1679 self.src, 1680 " 1681 pub type {camel} = {wt}::component::ResourceAny; 1682 1683 pub struct Guest{camel}<'a> {{ 1684 funcs: &'a Guest, 1685 }} 1686 " 1687 ); 1688 } 1689 } 1690 1691 fn type_record(&mut self, id: TypeId, _name: &str, record: &Record, docs: &Docs) { 1692 let info = self.info(id); 1693 let wt = self.generator.wasmtime_path(); 1694 1695 // We use a BTree set to make sure we don't have any duplicates and we have a stable order 1696 let additional_derives: BTreeSet<String> = self 1697 .generator 1698 .opts 1699 .additional_derive_attributes 1700 .iter() 1701 .cloned() 1702 .collect(); 1703 1704 for (name, mode) in self.modes_of(id) { 1705 let lt = self.lifetime_for(&info, mode); 1706 self.rustdoc(docs); 1707 1708 let mut derives = additional_derives.clone(); 1709 1710 uwriteln!(self.src, "#[derive({wt}::component::ComponentType)]"); 1711 if lt.is_none() { 1712 uwriteln!(self.src, "#[derive({wt}::component::Lift)]"); 1713 } 1714 uwriteln!(self.src, "#[derive({wt}::component::Lower)]"); 1715 self.push_str("#[component(record)]\n"); 1716 if let Some(path) = &self.generator.opts.wasmtime_crate { 1717 uwriteln!(self.src, "#[component(wasmtime_crate = {path})]\n"); 1718 } 1719 1720 if info.is_copy() { 1721 derives.extend(["Copy", "Clone"].into_iter().map(|s| s.to_string())); 1722 } else if info.is_clone() { 1723 derives.insert("Clone".to_string()); 1724 } 1725 1726 if !derives.is_empty() { 1727 self.push_str("#[derive("); 1728 self.push_str(&derives.into_iter().collect::<Vec<_>>().join(", ")); 1729 self.push_str(")]\n") 1730 } 1731 1732 self.push_str(&format!("pub struct {name}")); 1733 self.print_generics(lt); 1734 self.push_str(" {\n"); 1735 for field in record.fields.iter() { 1736 self.rustdoc(&field.docs); 1737 self.push_str(&format!("#[component(name = \"{}\")]\n", field.name)); 1738 self.push_str("pub "); 1739 self.push_str(&to_rust_ident(&field.name)); 1740 self.push_str(": "); 1741 self.print_ty(&field.ty, mode); 1742 self.push_str(",\n"); 1743 } 1744 self.push_str("}\n"); 1745 1746 self.push_str("impl"); 1747 self.print_generics(lt); 1748 self.push_str(" core::fmt::Debug for "); 1749 self.push_str(&name); 1750 self.print_generics(lt); 1751 self.push_str(" {\n"); 1752 self.push_str( 1753 "fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n", 1754 ); 1755 self.push_str(&format!("f.debug_struct(\"{name}\")")); 1756 for field in record.fields.iter() { 1757 self.push_str(&format!( 1758 ".field(\"{}\", &self.{})", 1759 field.name, 1760 to_rust_ident(&field.name) 1761 )); 1762 } 1763 self.push_str(".finish()\n"); 1764 self.push_str("}\n"); 1765 self.push_str("}\n"); 1766 1767 if info.error { 1768 self.push_str("impl"); 1769 self.print_generics(lt); 1770 self.push_str(" core::fmt::Display for "); 1771 self.push_str(&name); 1772 self.print_generics(lt); 1773 self.push_str(" {\n"); 1774 self.push_str( 1775 "fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n", 1776 ); 1777 self.push_str("write!(f, \"{:?}\", self)\n"); 1778 self.push_str("}\n"); 1779 self.push_str("}\n"); 1780 1781 self.push_str("impl core::error::Error for "); 1782 self.push_str(&name); 1783 self.push_str("{}\n"); 1784 } 1785 self.assert_type(id, &name); 1786 } 1787 } 1788 1789 fn type_tuple(&mut self, id: TypeId, _name: &str, tuple: &Tuple, docs: &Docs) { 1790 let info = self.info(id); 1791 for (name, mode) in self.modes_of(id) { 1792 let lt = self.lifetime_for(&info, mode); 1793 self.rustdoc(docs); 1794 self.push_str(&format!("pub type {name}")); 1795 self.print_generics(lt); 1796 self.push_str(" = ("); 1797 for ty in tuple.types.iter() { 1798 self.print_ty(ty, mode); 1799 self.push_str(","); 1800 } 1801 self.push_str(");\n"); 1802 self.assert_type(id, &name); 1803 } 1804 } 1805 1806 fn type_flags(&mut self, id: TypeId, name: &str, flags: &Flags, docs: &Docs) { 1807 self.rustdoc(docs); 1808 let wt = self.generator.wasmtime_path(); 1809 let rust_name = to_rust_upper_camel_case(name); 1810 uwriteln!(self.src, "{wt}::component::flags!(\n"); 1811 self.src.push_str(&format!("{rust_name} {{\n")); 1812 for flag in flags.flags.iter() { 1813 // TODO wasmtime-component-macro doesn't support docs for flags rn 1814 uwrite!( 1815 self.src, 1816 "#[component(name=\"{}\")] const {};\n", 1817 flag.name, 1818 flag.name.to_shouty_snake_case() 1819 ); 1820 } 1821 self.src.push_str("}\n"); 1822 self.src.push_str(");\n\n"); 1823 self.assert_type(id, &rust_name); 1824 } 1825 1826 fn type_variant(&mut self, id: TypeId, _name: &str, variant: &Variant, docs: &Docs) { 1827 self.print_rust_enum( 1828 id, 1829 variant.cases.iter().map(|c| { 1830 ( 1831 c.name.to_upper_camel_case(), 1832 Some(c.name.clone()), 1833 &c.docs, 1834 c.ty.as_ref(), 1835 ) 1836 }), 1837 docs, 1838 "variant", 1839 ); 1840 } 1841 1842 fn type_option(&mut self, id: TypeId, _name: &str, payload: &Type, docs: &Docs) { 1843 let info = self.info(id); 1844 1845 for (name, mode) in self.modes_of(id) { 1846 self.rustdoc(docs); 1847 let lt = self.lifetime_for(&info, mode); 1848 self.push_str(&format!("pub type {name}")); 1849 self.print_generics(lt); 1850 self.push_str("= Option<"); 1851 self.print_ty(payload, mode); 1852 self.push_str(">;\n"); 1853 self.assert_type(id, &name); 1854 } 1855 } 1856 1857 // Emit a double-check that the wit-parser-understood size of a type agrees 1858 // with the Wasmtime-understood size of a type. 1859 fn assert_type(&mut self, id: TypeId, name: &str) { 1860 self.push_str("const _: () = {\n"); 1861 let wt = self.generator.wasmtime_path(); 1862 uwriteln!( 1863 self.src, 1864 "assert!({} == <{name} as {wt}::component::ComponentType>::SIZE32);", 1865 self.generator.sizes.size(&Type::Id(id)).size_wasm32(), 1866 ); 1867 uwriteln!( 1868 self.src, 1869 "assert!({} == <{name} as {wt}::component::ComponentType>::ALIGN32);", 1870 self.generator.sizes.align(&Type::Id(id)).align_wasm32(), 1871 ); 1872 self.push_str("};\n"); 1873 } 1874 1875 fn print_rust_enum<'b>( 1876 &mut self, 1877 id: TypeId, 1878 cases: impl IntoIterator<Item = (String, Option<String>, &'b Docs, Option<&'b Type>)> + Clone, 1879 docs: &Docs, 1880 derive_component: &str, 1881 ) where 1882 Self: Sized, 1883 { 1884 let info = self.info(id); 1885 let wt = self.generator.wasmtime_path(); 1886 1887 // We use a BTree set to make sure we don't have any duplicates and we have a stable order 1888 let additional_derives: BTreeSet<String> = self 1889 .generator 1890 .opts 1891 .additional_derive_attributes 1892 .iter() 1893 .cloned() 1894 .collect(); 1895 1896 for (name, mode) in self.modes_of(id) { 1897 let name = to_rust_upper_camel_case(&name); 1898 1899 let mut derives = additional_derives.clone(); 1900 1901 self.rustdoc(docs); 1902 let lt = self.lifetime_for(&info, mode); 1903 uwriteln!(self.src, "#[derive({wt}::component::ComponentType)]"); 1904 if lt.is_none() { 1905 uwriteln!(self.src, "#[derive({wt}::component::Lift)]"); 1906 } 1907 uwriteln!(self.src, "#[derive({wt}::component::Lower)]"); 1908 self.push_str(&format!("#[component({derive_component})]\n")); 1909 if let Some(path) = &self.generator.opts.wasmtime_crate { 1910 uwriteln!(self.src, "#[component(wasmtime_crate = {path})]\n"); 1911 } 1912 if info.is_copy() { 1913 derives.extend(["Copy", "Clone"].into_iter().map(|s| s.to_string())); 1914 } else if info.is_clone() { 1915 derives.insert("Clone".to_string()); 1916 } 1917 1918 if !derives.is_empty() { 1919 self.push_str("#[derive("); 1920 self.push_str(&derives.into_iter().collect::<Vec<_>>().join(", ")); 1921 self.push_str(")]\n") 1922 } 1923 1924 self.push_str(&format!("pub enum {name}")); 1925 self.print_generics(lt); 1926 self.push_str("{\n"); 1927 for (case_name, component_name, docs, payload) in cases.clone() { 1928 self.rustdoc(docs); 1929 if let Some(n) = component_name { 1930 self.push_str(&format!("#[component(name = \"{n}\")] ")); 1931 } 1932 self.push_str(&case_name); 1933 if let Some(ty) = payload { 1934 self.push_str("("); 1935 self.print_ty(ty, mode); 1936 self.push_str(")") 1937 } 1938 self.push_str(",\n"); 1939 } 1940 self.push_str("}\n"); 1941 1942 self.print_rust_enum_debug( 1943 id, 1944 mode, 1945 &name, 1946 cases 1947 .clone() 1948 .into_iter() 1949 .map(|(name, _attr, _docs, ty)| (name, ty)), 1950 ); 1951 1952 if info.error { 1953 self.push_str("impl"); 1954 self.print_generics(lt); 1955 self.push_str(" core::fmt::Display for "); 1956 self.push_str(&name); 1957 self.print_generics(lt); 1958 self.push_str(" {\n"); 1959 self.push_str( 1960 "fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n", 1961 ); 1962 self.push_str("write!(f, \"{:?}\", self)\n"); 1963 self.push_str("}\n"); 1964 self.push_str("}\n"); 1965 1966 self.push_str("impl"); 1967 self.print_generics(lt); 1968 self.push_str(" core::error::Error for "); 1969 self.push_str(&name); 1970 self.print_generics(lt); 1971 self.push_str(" {}\n"); 1972 } 1973 1974 self.assert_type(id, &name); 1975 } 1976 } 1977 1978 fn print_rust_enum_debug<'b>( 1979 &mut self, 1980 id: TypeId, 1981 mode: TypeMode, 1982 name: &str, 1983 cases: impl IntoIterator<Item = (String, Option<&'b Type>)>, 1984 ) where 1985 Self: Sized, 1986 { 1987 let info = self.info(id); 1988 let lt = self.lifetime_for(&info, mode); 1989 self.push_str("impl"); 1990 self.print_generics(lt); 1991 self.push_str(" core::fmt::Debug for "); 1992 self.push_str(name); 1993 self.print_generics(lt); 1994 self.push_str(" {\n"); 1995 self.push_str("fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n"); 1996 self.push_str("match self {\n"); 1997 for (case_name, payload) in cases { 1998 self.push_str(name); 1999 self.push_str("::"); 2000 self.push_str(&case_name); 2001 if payload.is_some() { 2002 self.push_str("(e)"); 2003 } 2004 self.push_str(" => {\n"); 2005 self.push_str(&format!("f.debug_tuple(\"{name}::{case_name}\")")); 2006 if payload.is_some() { 2007 self.push_str(".field(e)"); 2008 } 2009 self.push_str(".finish()\n"); 2010 self.push_str("}\n"); 2011 } 2012 self.push_str("}\n"); 2013 self.push_str("}\n"); 2014 self.push_str("}\n"); 2015 } 2016 2017 fn type_result(&mut self, id: TypeId, _name: &str, result: &Result_, docs: &Docs) { 2018 let info = self.info(id); 2019 2020 for (name, mode) in self.modes_of(id) { 2021 self.rustdoc(docs); 2022 let lt = self.lifetime_for(&info, mode); 2023 self.push_str(&format!("pub type {name}")); 2024 self.print_generics(lt); 2025 self.push_str("= Result<"); 2026 self.print_optional_ty(result.ok.as_ref(), mode); 2027 self.push_str(","); 2028 self.print_optional_ty(result.err.as_ref(), mode); 2029 self.push_str(">;\n"); 2030 self.assert_type(id, &name); 2031 } 2032 } 2033 2034 fn type_enum(&mut self, id: TypeId, name: &str, enum_: &Enum, docs: &Docs) { 2035 let info = self.info(id); 2036 let wt = self.generator.wasmtime_path(); 2037 2038 // We use a BTree set to make sure we don't have any duplicates and have a stable order 2039 let mut derives: BTreeSet<String> = self 2040 .generator 2041 .opts 2042 .additional_derive_attributes 2043 .iter() 2044 .cloned() 2045 .collect(); 2046 2047 derives.extend( 2048 ["Clone", "Copy", "PartialEq", "Eq"] 2049 .into_iter() 2050 .map(|s| s.to_string()), 2051 ); 2052 2053 let name = to_rust_upper_camel_case(name); 2054 self.rustdoc(docs); 2055 uwriteln!(self.src, "#[derive({wt}::component::ComponentType)]"); 2056 uwriteln!(self.src, "#[derive({wt}::component::Lift)]"); 2057 uwriteln!(self.src, "#[derive({wt}::component::Lower)]"); 2058 self.push_str("#[component(enum)]\n"); 2059 if let Some(path) = &self.generator.opts.wasmtime_crate { 2060 uwriteln!(self.src, "#[component(wasmtime_crate = {path})]\n"); 2061 } 2062 2063 self.push_str("#[derive("); 2064 self.push_str(&derives.into_iter().collect::<Vec<_>>().join(", ")); 2065 self.push_str(")]\n"); 2066 2067 let repr = match enum_.cases.len().ilog2() { 2068 0..=7 => "u8", 2069 8..=15 => "u16", 2070 _ => "u32", 2071 }; 2072 uwriteln!(self.src, "#[repr({repr})]"); 2073 2074 self.push_str(&format!("pub enum {name} {{\n")); 2075 for case in enum_.cases.iter() { 2076 self.rustdoc(&case.docs); 2077 self.push_str(&format!("#[component(name = \"{}\")]", case.name)); 2078 self.push_str(&case.name.to_upper_camel_case()); 2079 self.push_str(",\n"); 2080 } 2081 self.push_str("}\n"); 2082 2083 // Auto-synthesize an implementation of the standard `Error` trait for 2084 // error-looking types based on their name. 2085 if info.error { 2086 self.push_str("impl "); 2087 self.push_str(&name); 2088 self.push_str("{\n"); 2089 2090 self.push_str("pub fn name(&self) -> &'static str {\n"); 2091 self.push_str("match self {\n"); 2092 for case in enum_.cases.iter() { 2093 self.push_str(&name); 2094 self.push_str("::"); 2095 self.push_str(&case.name.to_upper_camel_case()); 2096 self.push_str(" => \""); 2097 self.push_str(case.name.as_str()); 2098 self.push_str("\",\n"); 2099 } 2100 self.push_str("}\n"); 2101 self.push_str("}\n"); 2102 2103 self.push_str("pub fn message(&self) -> &'static str {\n"); 2104 self.push_str("match self {\n"); 2105 for case in enum_.cases.iter() { 2106 self.push_str(&name); 2107 self.push_str("::"); 2108 self.push_str(&case.name.to_upper_camel_case()); 2109 self.push_str(" => \""); 2110 if let Some(contents) = &case.docs.contents { 2111 self.push_str(contents.trim()); 2112 } 2113 self.push_str("\",\n"); 2114 } 2115 self.push_str("}\n"); 2116 self.push_str("}\n"); 2117 2118 self.push_str("}\n"); 2119 2120 self.push_str("impl core::fmt::Debug for "); 2121 self.push_str(&name); 2122 self.push_str( 2123 "{\nfn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n", 2124 ); 2125 self.push_str("f.debug_struct(\""); 2126 self.push_str(&name); 2127 self.push_str("\")\n"); 2128 self.push_str(".field(\"code\", &(*self as i32))\n"); 2129 self.push_str(".field(\"name\", &self.name())\n"); 2130 self.push_str(".field(\"message\", &self.message())\n"); 2131 self.push_str(".finish()\n"); 2132 self.push_str("}\n"); 2133 self.push_str("}\n"); 2134 2135 self.push_str("impl core::fmt::Display for "); 2136 self.push_str(&name); 2137 self.push_str( 2138 "{\nfn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n", 2139 ); 2140 self.push_str("write!(f, \"{} (error {})\", self.name(), *self as i32)"); 2141 self.push_str("}\n"); 2142 self.push_str("}\n"); 2143 self.push_str("\n"); 2144 self.push_str("impl core::error::Error for "); 2145 self.push_str(&name); 2146 self.push_str("{}\n"); 2147 } else { 2148 self.print_rust_enum_debug( 2149 id, 2150 TypeMode::Owned, 2151 &name, 2152 enum_ 2153 .cases 2154 .iter() 2155 .map(|c| (c.name.to_upper_camel_case(), None)), 2156 ) 2157 } 2158 self.assert_type(id, &name); 2159 } 2160 2161 fn type_alias(&mut self, id: TypeId, _name: &str, ty: &Type, docs: &Docs) { 2162 let info = self.info(id); 2163 for (name, mode) in self.modes_of(id) { 2164 self.rustdoc(docs); 2165 self.push_str(&format!("pub type {name}")); 2166 let lt = self.lifetime_for(&info, mode); 2167 self.print_generics(lt); 2168 self.push_str(" = "); 2169 self.print_ty(ty, mode); 2170 self.push_str(";\n"); 2171 let def_id = resolve_type_definition_id(self.resolve, id); 2172 if !matches!(self.resolve().types[def_id].kind, TypeDefKind::Resource) { 2173 self.assert_type(id, &name); 2174 } 2175 } 2176 } 2177 2178 fn type_list(&mut self, id: TypeId, _name: &str, ty: &Type, docs: &Docs) { 2179 let info = self.info(id); 2180 for (name, mode) in self.modes_of(id) { 2181 let lt = self.lifetime_for(&info, mode); 2182 self.rustdoc(docs); 2183 self.push_str(&format!("pub type {name}")); 2184 self.print_generics(lt); 2185 self.push_str(" = "); 2186 self.print_list(ty, mode); 2187 self.push_str(";\n"); 2188 self.assert_type(id, &name); 2189 } 2190 } 2191 2192 fn type_stream(&mut self, id: TypeId, name: &str, ty: Option<&Type>, docs: &Docs) { 2193 self.rustdoc(docs); 2194 self.push_str(&format!("pub type {name}")); 2195 self.print_generics(None); 2196 self.push_str(" = "); 2197 self.print_stream(ty); 2198 self.push_str(";\n"); 2199 self.assert_type(id, &name); 2200 } 2201 2202 fn type_future(&mut self, id: TypeId, name: &str, ty: Option<&Type>, docs: &Docs) { 2203 self.rustdoc(docs); 2204 self.push_str(&format!("pub type {name}")); 2205 self.print_generics(None); 2206 self.push_str(" = "); 2207 self.print_future(ty); 2208 self.push_str(";\n"); 2209 self.assert_type(id, &name); 2210 } 2211 2212 fn print_result_ty(&mut self, result: Option<Type>, mode: TypeMode) { 2213 match result { 2214 Some(ty) => self.print_ty(&ty, mode), 2215 None => self.push_str("()"), 2216 } 2217 } 2218 2219 fn special_case_trappable_error( 2220 &mut self, 2221 func: &Function, 2222 ) -> Option<(&'a Result_, TypeId, String)> { 2223 let result = func.result?; 2224 2225 // We fill in a special trappable error type in the case when a function has just one 2226 // result, which is itself a `result<a, e>`, and the `e` is *not* a primitive 2227 // (i.e. defined in std) type, and matches the typename given by the user. 2228 let id = match result { 2229 Type::Id(id) => id, 2230 _ => return None, 2231 }; 2232 let result = match &self.resolve.types[id].kind { 2233 TypeDefKind::Result(r) => r, 2234 _ => return None, 2235 }; 2236 let error_typeid = match result.err? { 2237 Type::Id(id) => resolve_type_definition_id(&self.resolve, id), 2238 _ => return None, 2239 }; 2240 2241 let name = self.generator.trappable_errors.get(&error_typeid)?; 2242 2243 let mut path = self.path_to_root(); 2244 uwrite!(path, "{name}"); 2245 Some((result, error_typeid, path)) 2246 } 2247 2248 fn generate_add_to_linker(&mut self, id: InterfaceId, name: &str) { 2249 let iface = &self.resolve.interfaces[id]; 2250 let owner = TypeOwner::Interface(id); 2251 let wt = self.generator.wasmtime_path(); 2252 2253 let mut required_conversion_traits = IndexSet::new(); 2254 let extra_functions = { 2255 let mut functions = Vec::new(); 2256 let mut errors_converted = IndexMap::new(); 2257 let mut my_error_types = iface 2258 .types 2259 .iter() 2260 .filter(|(_, id)| self.generator.trappable_errors.contains_key(*id)) 2261 .map(|(_, id)| *id) 2262 .collect::<Vec<_>>(); 2263 my_error_types.extend( 2264 iface 2265 .functions 2266 .iter() 2267 .filter_map(|(_, func)| self.special_case_trappable_error(func)) 2268 .map(|(_, id, _)| id), 2269 ); 2270 for err_id in my_error_types { 2271 let err = &self.resolve.types[resolve_type_definition_id(self.resolve, err_id)]; 2272 let err_name = err.name.as_ref().unwrap(); 2273 let owner = match err.owner { 2274 TypeOwner::Interface(i) => i, 2275 _ => unimplemented!(), 2276 }; 2277 match self.path_to_interface(owner) { 2278 Some(path) => { 2279 required_conversion_traits.insert(format!("{path}::Host")); 2280 } 2281 None => { 2282 if errors_converted.insert(err_name, err_id).is_none() { 2283 functions.push(ExtraTraitMethod::ErrorConvert { 2284 name: err_name, 2285 id: err_id, 2286 }) 2287 } 2288 } 2289 } 2290 } 2291 functions 2292 }; 2293 2294 // Generate the `pub trait` which represents the host functionality for 2295 // this import which additionally inherits from all resource traits 2296 // for this interface defined by `type_resource`. 2297 let generated_trait = self.generate_trait( 2298 "Host", 2299 &iface 2300 .functions 2301 .iter() 2302 .filter_map(|(_, f)| { 2303 if f.kind.resource().is_none() { 2304 Some(f) 2305 } else { 2306 None 2307 } 2308 }) 2309 .collect::<Vec<_>>(), 2310 &extra_functions, 2311 &get_resources(self.resolve, id).collect::<Vec<_>>(), 2312 ); 2313 2314 let opt_t_send_bound = if generated_trait 2315 .all_func_flags 2316 .contains(FunctionFlags::ASYNC) 2317 { 2318 "+ Send" 2319 } else { 2320 "" 2321 }; 2322 2323 let mut sync_bounds = "Host".to_string(); 2324 2325 for ty in required_conversion_traits { 2326 uwrite!(sync_bounds, " + {ty}"); 2327 } 2328 2329 let options_param = if self.generator.interface_link_options[&id].has_any() { 2330 "options: &LinkOptions," 2331 } else { 2332 "" 2333 }; 2334 2335 uwriteln!( 2336 self.src, 2337 " 2338 pub fn add_to_linker<T, D>( 2339 linker: &mut {wt}::component::Linker<T>, 2340 {options_param} 2341 host_getter: fn(&mut T) -> D::Data<'_>, 2342 ) -> {wt}::Result<()> 2343 where 2344 D: HostWithStore, 2345 for<'a> D::Data<'a>: {sync_bounds}, 2346 T: 'static {opt_t_send_bound}, 2347 {{ 2348 " 2349 ); 2350 2351 let gate = FeatureGate::open(&mut self.src, &iface.stability); 2352 uwriteln!(self.src, "let mut inst = linker.instance(\"{name}\")?;"); 2353 2354 for (ty, _name) in get_resources(self.resolve, id) { 2355 self.generator.generate_add_resource_to_linker( 2356 self.current_interface.map(|p| p.1), 2357 Some(&mut self.src), 2358 "inst", 2359 self.resolve, 2360 ty, 2361 ); 2362 } 2363 2364 for (_, func) in iface.functions.iter() { 2365 self.generate_add_function_to_linker(owner, func, "inst"); 2366 } 2367 gate.close(&mut self.src); 2368 uwriteln!(self.src, "Ok(())"); 2369 uwriteln!(self.src, "}}"); 2370 } 2371 2372 fn import_resource_drop_flags(&mut self, name: &str) -> FunctionFlags { 2373 self.generator.opts.imports.resource_drop_flags( 2374 self.resolve, 2375 self.current_interface.map(|p| p.1), 2376 name, 2377 ) 2378 } 2379 2380 fn generate_add_function_to_linker(&mut self, owner: TypeOwner, func: &Function, linker: &str) { 2381 let flags = self.generator.opts.imports.flags( 2382 self.resolve, 2383 self.current_interface.map(|p| p.1), 2384 func, 2385 ); 2386 self.all_func_flags |= flags; 2387 let gate = FeatureGate::open(&mut self.src, &func.stability); 2388 uwrite!( 2389 self.src, 2390 "{linker}.{}(\"{}\", ", 2391 if flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE) { 2392 "func_wrap_concurrent" 2393 } else if flags.contains(FunctionFlags::ASYNC) { 2394 "func_wrap_async" 2395 } else { 2396 "func_wrap" 2397 }, 2398 func.name 2399 ); 2400 self.generate_guest_import_closure(owner, func, flags); 2401 uwriteln!(self.src, ")?;"); 2402 gate.close(&mut self.src); 2403 } 2404 2405 fn generate_guest_import_closure( 2406 &mut self, 2407 owner: TypeOwner, 2408 func: &Function, 2409 flags: FunctionFlags, 2410 ) { 2411 // Generate the closure that's passed to a `Linker`, the final piece of 2412 // codegen here. 2413 2414 let wt = self.generator.wasmtime_path(); 2415 if flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE) { 2416 uwrite!(self.src, "move |caller: &{wt}::component::Accessor::<T>, ("); 2417 } else { 2418 uwrite!( 2419 self.src, 2420 "move |mut caller: {wt}::StoreContextMut<'_, T>, (" 2421 ); 2422 } 2423 for (i, _param) in func.params.iter().enumerate() { 2424 uwrite!(self.src, "arg{},", i); 2425 } 2426 self.src.push_str(") : ("); 2427 2428 for (_, ty) in func.params.iter() { 2429 // Lift is required to be implied for this type, so we can't use 2430 // a borrowed type: 2431 self.print_ty(ty, TypeMode::Owned); 2432 self.src.push_str(", "); 2433 } 2434 self.src.push_str(")| {\n"); 2435 2436 if flags.contains(FunctionFlags::TRACING) { 2437 if flags.contains(FunctionFlags::ASYNC) { 2438 self.src.push_str("use tracing::Instrument;\n"); 2439 } 2440 2441 uwrite!( 2442 self.src, 2443 " 2444 let span = tracing::span!( 2445 tracing::Level::TRACE, 2446 \"wit-bindgen import\", 2447 module = \"{}\", 2448 function = \"{}\", 2449 ); 2450 ", 2451 match owner { 2452 TypeOwner::Interface(id) => self.resolve.interfaces[id] 2453 .name 2454 .as_deref() 2455 .unwrap_or("<no module>"), 2456 TypeOwner::World(id) => &self.resolve.worlds[id].name, 2457 TypeOwner::None => "<no owner>", 2458 }, 2459 func.name, 2460 ); 2461 } 2462 2463 if flags.contains(FunctionFlags::ASYNC) { 2464 let ctor = if flags.contains(FunctionFlags::STORE) { 2465 "pin" 2466 } else { 2467 "new" 2468 }; 2469 uwriteln!( 2470 self.src, 2471 "{wt}::component::__internal::Box::{ctor}(async move {{" 2472 ); 2473 } else { 2474 // Only directly enter the span if the function is sync. Otherwise 2475 // we use tracing::Instrument to ensure that the span is not entered 2476 // across an await point. 2477 if flags.contains(FunctionFlags::TRACING) { 2478 self.push_str("let _enter = span.enter();\n"); 2479 } 2480 } 2481 2482 if flags.contains(FunctionFlags::TRACING) { 2483 let mut event_fields = func 2484 .params 2485 .iter() 2486 .enumerate() 2487 .map(|(i, (name, ty))| { 2488 let name = to_rust_ident(&name); 2489 formatting_for_arg(&name, i, *ty, &self.resolve, flags) 2490 }) 2491 .collect::<Vec<String>>(); 2492 event_fields.push(format!("\"call\"")); 2493 uwrite!( 2494 self.src, 2495 "tracing::event!(tracing::Level::TRACE, {});\n", 2496 event_fields.join(", ") 2497 ); 2498 } 2499 2500 if flags.contains(FunctionFlags::STORE) { 2501 if flags.contains(FunctionFlags::ASYNC) { 2502 uwriteln!(self.src, "let host = &caller.with_getter(host_getter);"); 2503 } else { 2504 uwriteln!( 2505 self.src, 2506 "let access_cx = {wt}::AsContextMut::as_context_mut(&mut caller);" 2507 ); 2508 uwriteln!( 2509 self.src, 2510 "let host = {wt}::component::Access::new(access_cx, host_getter);" 2511 ); 2512 } 2513 } else { 2514 self.src 2515 .push_str("let host = &mut host_getter(caller.data_mut());\n"); 2516 } 2517 let func_name = rust_function_name(func); 2518 let host_trait = match func.kind.resource() { 2519 None => match owner { 2520 TypeOwner::World(id) => format!( 2521 "{}Imports", 2522 rust::to_rust_upper_camel_case(&self.resolve.worlds[id].name) 2523 ), 2524 _ => "Host".to_string(), 2525 }, 2526 Some(id) => { 2527 let resource = self.resolve.types[id] 2528 .name 2529 .as_ref() 2530 .unwrap() 2531 .to_upper_camel_case(); 2532 format!("Host{resource}") 2533 } 2534 }; 2535 2536 if flags.contains(FunctionFlags::STORE) { 2537 uwrite!( 2538 self.src, 2539 "let r = <D as {host_trait}WithStore>::{func_name}(host, " 2540 ); 2541 } else { 2542 uwrite!(self.src, "let r = {host_trait}::{func_name}(host, "); 2543 } 2544 2545 for (i, _) in func.params.iter().enumerate() { 2546 uwrite!(self.src, "arg{},", i); 2547 } 2548 2549 self.src.push_str(if flags.contains(FunctionFlags::ASYNC) { 2550 ").await;\n" 2551 } else { 2552 ");\n" 2553 }); 2554 2555 if flags.contains(FunctionFlags::TRACING) { 2556 uwrite!( 2557 self.src, 2558 "tracing::event!(tracing::Level::TRACE, {}, \"return\");", 2559 formatting_for_results(func.result, &self.resolve, flags) 2560 ); 2561 } 2562 2563 if !flags.contains(FunctionFlags::TRAPPABLE) { 2564 if func.result.is_some() { 2565 uwrite!(self.src, "Ok((r,))\n"); 2566 } else { 2567 uwrite!(self.src, "Ok(r)\n"); 2568 } 2569 } else if let Some((_, err, _)) = self.special_case_trappable_error(func) { 2570 let err = &self.resolve.types[resolve_type_definition_id(self.resolve, err)]; 2571 let err_name = err.name.as_ref().unwrap(); 2572 let owner = match err.owner { 2573 TypeOwner::Interface(i) => i, 2574 _ => unimplemented!(), 2575 }; 2576 let convert_trait = match self.path_to_interface(owner) { 2577 Some(path) => format!("{path}::Host"), 2578 None => format!("Host"), 2579 }; 2580 let convert = format!("{}::convert_{}", convert_trait, err_name.to_snake_case()); 2581 let convert = if flags.contains(FunctionFlags::STORE) { 2582 if flags.contains(FunctionFlags::ASYNC) { 2583 format!("caller.with(|mut host| {convert}(&mut host_getter(host.get()), e))?") 2584 } else { 2585 format!("{convert}(&mut host_getter(caller.data_mut()), e)?") 2586 } 2587 } else { 2588 format!("{convert}(host, e)?") 2589 }; 2590 uwrite!( 2591 self.src, 2592 "Ok((match r {{ 2593 Ok(a) => Ok(a), 2594 Err(e) => Err({convert}), 2595 }},))" 2596 ); 2597 } else if func.result.is_some() { 2598 uwrite!(self.src, "Ok((r?,))\n"); 2599 } else { 2600 uwrite!(self.src, "r\n"); 2601 } 2602 2603 if flags.contains(FunctionFlags::ASYNC) { 2604 if flags.contains(FunctionFlags::TRACING) { 2605 self.src.push_str("}.instrument(span))\n"); 2606 } else { 2607 self.src.push_str("})\n"); 2608 } 2609 } 2610 2611 self.src.push_str("}\n"); 2612 } 2613 2614 fn generate_function_trait_sig(&mut self, func: &Function, flags: FunctionFlags) { 2615 let wt = self.generator.wasmtime_path(); 2616 self.rustdoc(&func.docs); 2617 2618 self.push_str("fn "); 2619 self.push_str(&rust_function_name(func)); 2620 if flags.contains(FunctionFlags::STORE | FunctionFlags::ASYNC) { 2621 uwrite!( 2622 self.src, 2623 "<T>(accessor: &{wt}::component::Accessor<T, Self>, " 2624 ); 2625 } else if flags.contains(FunctionFlags::STORE) { 2626 uwrite!(self.src, "<T>(host: {wt}::component::Access<T, Self>, "); 2627 } else { 2628 self.push_str("(&mut self, "); 2629 } 2630 self.generate_function_params(func); 2631 self.push_str(")"); 2632 self.push_str(" -> "); 2633 2634 if flags.contains(FunctionFlags::ASYNC) { 2635 uwrite!(self.src, "impl ::core::future::Future<Output = "); 2636 } 2637 2638 self.all_func_flags |= flags; 2639 self.generate_function_result(func, flags); 2640 2641 if flags.contains(FunctionFlags::ASYNC) { 2642 self.push_str("> + Send"); 2643 } 2644 } 2645 2646 fn generate_function_params(&mut self, func: &Function) { 2647 for (name, param) in func.params.iter() { 2648 let name = to_rust_ident(name); 2649 self.push_str(&name); 2650 self.push_str(": "); 2651 self.print_ty(param, TypeMode::Owned); 2652 self.push_str(","); 2653 } 2654 } 2655 2656 fn generate_function_result(&mut self, func: &Function, flags: FunctionFlags) { 2657 if !flags.contains(FunctionFlags::TRAPPABLE) { 2658 self.print_result_ty(func.result, TypeMode::Owned); 2659 } else if let Some((r, _id, error_typename)) = self.special_case_trappable_error(func) { 2660 // Functions which have a single result `result<ok,err>` get special 2661 // cased to use the host_wasmtime_rust::Error<err>, making it possible 2662 // for them to trap or use `?` to propagate their errors 2663 self.push_str("Result<"); 2664 if let Some(ok) = r.ok { 2665 self.print_ty(&ok, TypeMode::Owned); 2666 } else { 2667 self.push_str("()"); 2668 } 2669 self.push_str(","); 2670 self.push_str(&error_typename); 2671 self.push_str(">"); 2672 } else { 2673 // All other functions get their return values wrapped in an wasmtime::Result. 2674 // Returning the anyhow::Error case can be used to trap. 2675 let wt = self.generator.wasmtime_path(); 2676 uwrite!(self.src, "{wt}::Result<"); 2677 self.print_result_ty(func.result, TypeMode::Owned); 2678 self.push_str(">"); 2679 } 2680 } 2681 2682 fn extract_typed_function(&mut self, func: &Function) -> (String, String) { 2683 let snake = func_field_name(self.resolve, func); 2684 let sig = self.typedfunc_sig(func, TypeMode::AllBorrowed("'_")); 2685 let extract = 2686 format!("*_instance.get_typed_func::<{sig}>(&mut store, &self.{snake})?.func()"); 2687 (snake, extract) 2688 } 2689 2690 fn define_rust_guest_export( 2691 &mut self, 2692 resolve: &Resolve, 2693 ns: Option<&WorldKey>, 2694 func: &Function, 2695 ) { 2696 let flags = self.generator.opts.exports.flags(resolve, ns, func); 2697 let (async_, async__, await_) = if flags.contains(FunctionFlags::ASYNC) { 2698 ("async", "_async", ".await") 2699 } else { 2700 ("", "", "") 2701 }; 2702 2703 self.rustdoc(&func.docs); 2704 let wt = self.generator.wasmtime_path(); 2705 2706 uwrite!( 2707 self.src, 2708 "pub {async_} fn call_{}", 2709 func.item_name().to_snake_case(), 2710 ); 2711 if flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE) { 2712 uwrite!( 2713 self.src, 2714 "<_T, _D>(&self, accessor: &{wt}::component::Accessor<_T, _D>, ", 2715 ); 2716 } else { 2717 uwrite!(self.src, "<S: {wt}::AsContextMut>(&self, mut store: S, ",); 2718 } 2719 2720 let task_exit = 2721 flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE | FunctionFlags::TASK_EXIT); 2722 2723 let param_mode = if flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE) { 2724 TypeMode::Owned 2725 } else { 2726 TypeMode::AllBorrowed("'_") 2727 }; 2728 2729 for (i, param) in func.params.iter().enumerate() { 2730 uwrite!(self.src, "arg{}: ", i); 2731 self.print_ty(¶m.1, param_mode); 2732 self.push_str(","); 2733 } 2734 2735 uwrite!(self.src, ") -> {wt}::Result<"); 2736 if task_exit { 2737 self.src.push_str("("); 2738 } 2739 self.print_result_ty(func.result, TypeMode::Owned); 2740 if task_exit { 2741 uwrite!(self.src, ", {wt}::component::TaskExit)"); 2742 } 2743 uwrite!(self.src, ">"); 2744 2745 if flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE) { 2746 uwrite!(self.src, " where _T: Send, _D: {wt}::component::HasData"); 2747 } else if flags.contains(FunctionFlags::ASYNC) { 2748 uwrite!(self.src, " where <S as {wt}::AsContext>::Data: Send"); 2749 } 2750 uwrite!(self.src, "{{\n"); 2751 2752 if flags.contains(FunctionFlags::TRACING) { 2753 if flags.contains(FunctionFlags::ASYNC) { 2754 self.src.push_str("use tracing::Instrument;\n"); 2755 } 2756 2757 let ns = match ns { 2758 Some(key) => resolve.name_world_key(key), 2759 None => "default".to_string(), 2760 }; 2761 self.src.push_str(&format!( 2762 " 2763 let span = tracing::span!( 2764 tracing::Level::TRACE, 2765 \"wit-bindgen export\", 2766 module = \"{ns}\", 2767 function = \"{}\", 2768 ); 2769 ", 2770 func.name, 2771 )); 2772 2773 if !flags.contains(FunctionFlags::ASYNC) { 2774 self.src.push_str( 2775 " 2776 let _enter = span.enter(); 2777 ", 2778 ); 2779 } 2780 } 2781 2782 self.src.push_str("let callee = unsafe {\n"); 2783 uwrite!( 2784 self.src, 2785 "{wt}::component::TypedFunc::<{}>", 2786 self.typedfunc_sig(func, param_mode) 2787 ); 2788 let projection_to_func = if func.kind.resource().is_some() { 2789 ".funcs" 2790 } else { 2791 "" 2792 }; 2793 uwriteln!( 2794 self.src, 2795 "::new_unchecked(self{projection_to_func}.{})", 2796 func_field_name(self.resolve, func), 2797 ); 2798 self.src.push_str("};\n"); 2799 2800 self.src.push_str("let ("); 2801 if flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE) { 2802 self.src.push_str("("); 2803 } 2804 if func.result.is_some() { 2805 uwrite!(self.src, "ret0,"); 2806 } 2807 2808 if flags.contains(FunctionFlags::ASYNC | FunctionFlags::STORE) { 2809 let task_exit = if task_exit { "task_exit" } else { "_" }; 2810 uwrite!( 2811 self.src, 2812 "), {task_exit}) = callee.call_concurrent(accessor, (" 2813 ); 2814 } else { 2815 uwrite!( 2816 self.src, 2817 ") = callee.call{async__}(store.as_context_mut(), (" 2818 ); 2819 }; 2820 2821 for (i, _) in func.params.iter().enumerate() { 2822 uwrite!(self.src, "arg{}, ", i); 2823 } 2824 2825 let instrument = if flags.contains(FunctionFlags::ASYNC | FunctionFlags::TRACING) { 2826 ".instrument(span.clone())" 2827 } else { 2828 "" 2829 }; 2830 uwriteln!(self.src, ")){instrument}{await_}?;"); 2831 2832 let instrument = if flags.contains(FunctionFlags::ASYNC | FunctionFlags::TRACING) { 2833 ".instrument(span)" 2834 } else { 2835 "" 2836 }; 2837 2838 if !flags.contains(FunctionFlags::STORE) { 2839 uwriteln!( 2840 self.src, 2841 "callee.post_return{async__}(store.as_context_mut()){instrument}{await_}?;" 2842 ); 2843 } 2844 2845 self.src.push_str("Ok("); 2846 if task_exit { 2847 self.src.push_str("("); 2848 } 2849 if func.result.is_some() { 2850 self.src.push_str("ret0"); 2851 } else { 2852 self.src.push_str("()"); 2853 } 2854 if task_exit { 2855 self.src.push_str(", task_exit)"); 2856 } 2857 self.src.push_str(")\n"); 2858 2859 // End function body 2860 self.src.push_str("}\n"); 2861 } 2862 2863 fn rustdoc(&mut self, docs: &Docs) { 2864 let docs = match &docs.contents { 2865 Some(docs) => docs, 2866 None => return, 2867 }; 2868 for line in docs.trim().lines() { 2869 self.push_str("/// "); 2870 self.push_str(line); 2871 self.push_str("\n"); 2872 } 2873 } 2874 2875 fn path_to_root(&self) -> String { 2876 let mut path_to_root = String::new(); 2877 if let Some((_, key, is_export)) = self.current_interface { 2878 match key { 2879 WorldKey::Name(_) => { 2880 path_to_root.push_str("super::"); 2881 } 2882 WorldKey::Interface(_) => { 2883 path_to_root.push_str("super::super::super::"); 2884 } 2885 } 2886 if is_export { 2887 path_to_root.push_str("super::"); 2888 } 2889 } 2890 path_to_root 2891 } 2892 2893 fn partition_concurrent_funcs<'b>( 2894 &mut self, 2895 funcs: impl IntoIterator<Item = &'b Function>, 2896 ) -> FunctionPartitioning<'b> { 2897 let key = self.current_interface.map(|p| p.1); 2898 let (with_store, without_store) = funcs 2899 .into_iter() 2900 .map(|func| { 2901 let flags = self.generator.opts.imports.flags(self.resolve, key, func); 2902 (func, flags) 2903 }) 2904 .partition(|(_, flags)| flags.contains(FunctionFlags::STORE)); 2905 FunctionPartitioning { 2906 with_store, 2907 without_store, 2908 } 2909 } 2910 2911 fn generate_trait( 2912 &mut self, 2913 trait_name: &str, 2914 functions: &[&Function], 2915 extra_functions: &[ExtraTraitMethod<'_>], 2916 resources: &[(TypeId, &str)], 2917 ) -> GeneratedTrait { 2918 let mut ret = GeneratedTrait::default(); 2919 let wt = self.generator.wasmtime_path(); 2920 let partition = self.partition_concurrent_funcs(functions.iter().copied()); 2921 2922 for (_, flags) in partition.with_store.iter().chain(&partition.without_store) { 2923 ret.all_func_flags |= *flags; 2924 } 2925 2926 let mut with_store_supertraits = vec![format!("{wt}::component::HasData")]; 2927 let mut without_store_supertraits = vec![]; 2928 for (id, name) in resources { 2929 let camel = name.to_upper_camel_case(); 2930 without_store_supertraits.push(format!("Host{camel}")); 2931 let funcs = self.partition_concurrent_funcs(get_resource_functions(self.resolve, *id)); 2932 for (_, flags) in funcs.with_store.iter().chain(&funcs.without_store) { 2933 ret.all_func_flags |= *flags; 2934 } 2935 ret.all_func_flags |= self.import_resource_drop_flags(name); 2936 with_store_supertraits.push(format!("Host{camel}WithStore")); 2937 } 2938 if ret.all_func_flags.contains(FunctionFlags::ASYNC) { 2939 with_store_supertraits.push("Send".to_string()); 2940 without_store_supertraits.push("Send".to_string()); 2941 } 2942 2943 uwriteln!( 2944 self.src, 2945 "pub trait {trait_name}WithStore: {} {{", 2946 with_store_supertraits.join(" + "), 2947 ); 2948 ret.with_store_name = Some(format!("{trait_name}WithStore")); 2949 2950 let mut extra_with_store_function = false; 2951 for extra in extra_functions { 2952 match extra { 2953 ExtraTraitMethod::ResourceDrop { name } => { 2954 let flags = self.import_resource_drop_flags(name); 2955 if !flags.contains(FunctionFlags::STORE) { 2956 continue; 2957 } 2958 let camel = name.to_upper_camel_case(); 2959 2960 if flags.contains(FunctionFlags::ASYNC) { 2961 uwrite!( 2962 self.src, 2963 " 2964 fn drop<T>(accessor: &{wt}::component::Accessor<T, Self>, rep: {wt}::component::Resource<{camel}>) 2965 -> impl ::core::future::Future<Output = {wt}::Result<()>> + Send where Self: Sized; 2966 " 2967 ); 2968 } else { 2969 uwrite!( 2970 self.src, 2971 " 2972 fn drop<T>(accessor: {wt}::component::Access<T, Self>, rep: {wt}::component::Resource<{camel}>) 2973 -> {wt}::Result<()>; 2974 " 2975 ); 2976 } 2977 2978 extra_with_store_function = true; 2979 } 2980 ExtraTraitMethod::ErrorConvert { .. } => {} 2981 } 2982 } 2983 2984 for (func, flags) in partition.with_store.iter() { 2985 self.generate_function_trait_sig(func, *flags); 2986 self.push_str(";\n"); 2987 } 2988 uwriteln!(self.src, "}}"); 2989 2990 // If `*WithStore` is empty, generate a blanket impl for the trait since 2991 // it's otherwise not necessary to implement it manually. 2992 if partition.with_store.is_empty() && !extra_with_store_function { 2993 uwriteln!(self.src, "impl<_T: ?Sized> {trait_name}WithStore for _T"); 2994 uwriteln!( 2995 self.src, 2996 " where _T: {}", 2997 with_store_supertraits.join(" + ") 2998 ); 2999 3000 uwriteln!(self.src, "{{}}"); 3001 } 3002 3003 uwriteln!( 3004 self.src, 3005 "pub trait {trait_name}: {} {{", 3006 without_store_supertraits.join(" + ") 3007 ); 3008 ret.name = trait_name.to_string(); 3009 for (func, flags) in partition.without_store.iter() { 3010 self.generate_function_trait_sig(func, *flags); 3011 self.push_str(";\n"); 3012 } 3013 3014 for extra in extra_functions { 3015 match extra { 3016 ExtraTraitMethod::ResourceDrop { name } => { 3017 let flags = self.import_resource_drop_flags(name); 3018 ret.all_func_flags |= flags; 3019 if flags.contains(FunctionFlags::STORE) { 3020 continue; 3021 } 3022 let camel = name.to_upper_camel_case(); 3023 uwrite!( 3024 self.src, 3025 "fn drop(&mut self, rep: {wt}::component::Resource<{camel}>) -> " 3026 ); 3027 if flags.contains(FunctionFlags::ASYNC) { 3028 uwrite!(self.src, "impl ::core::future::Future<Output ="); 3029 } 3030 uwrite!(self.src, "{wt}::Result<()>"); 3031 if flags.contains(FunctionFlags::ASYNC) { 3032 uwrite!(self.src, "> + Send"); 3033 } 3034 uwrite!(self.src, ";"); 3035 } 3036 ExtraTraitMethod::ErrorConvert { name, id } => { 3037 let root = self.path_to_root(); 3038 let custom_name = &self.generator.trappable_errors[id]; 3039 let snake = name.to_snake_case(); 3040 let camel = name.to_upper_camel_case(); 3041 uwriteln!( 3042 self.src, 3043 " 3044 fn convert_{snake}(&mut self, err: {root}{custom_name}) -> {wt}::Result<{camel}>; 3045 " 3046 ); 3047 } 3048 } 3049 } 3050 3051 uwriteln!(self.src, "}}"); 3052 3053 if self.generator.opts.skip_mut_forwarding_impls { 3054 return ret; 3055 } 3056 3057 // Generate impl HostResource for &mut HostResource 3058 let maybe_send = if ret.all_func_flags.contains(FunctionFlags::ASYNC) { 3059 "+ Send" 3060 } else { 3061 "" 3062 }; 3063 uwriteln!( 3064 self.src, 3065 "impl <_T: {trait_name} + ?Sized {maybe_send}> {trait_name} for &mut _T {{" 3066 ); 3067 for (func, flags) in partition.without_store.iter() { 3068 self.generate_function_trait_sig(func, *flags); 3069 uwriteln!(self.src, "{{"); 3070 if flags.contains(FunctionFlags::ASYNC) { 3071 uwriteln!(self.src, "async move {{"); 3072 } 3073 uwrite!( 3074 self.src, 3075 "{trait_name}::{}(*self,", 3076 rust_function_name(func) 3077 ); 3078 for (name, _) in func.params.iter() { 3079 uwrite!(self.src, "{},", to_rust_ident(name)); 3080 } 3081 uwrite!(self.src, ")"); 3082 if flags.contains(FunctionFlags::ASYNC) { 3083 uwrite!(self.src, ".await\n}}"); 3084 } 3085 uwriteln!(self.src, "}}"); 3086 } 3087 for extra in extra_functions { 3088 match extra { 3089 ExtraTraitMethod::ResourceDrop { name } => { 3090 let flags = self.import_resource_drop_flags(name); 3091 if flags.contains(FunctionFlags::STORE) { 3092 continue; 3093 } 3094 let camel = name.to_upper_camel_case(); 3095 let mut await_ = ""; 3096 if flags.contains(FunctionFlags::ASYNC) { 3097 self.src.push_str("async "); 3098 await_ = ".await"; 3099 } 3100 uwriteln!( 3101 self.src, 3102 " 3103 fn drop(&mut self, rep: {wt}::component::Resource<{camel}>) -> {wt}::Result<()> {{ 3104 {trait_name}::drop(*self, rep){await_} 3105 }} 3106 ", 3107 ); 3108 } 3109 ExtraTraitMethod::ErrorConvert { name, id } => { 3110 let root = self.path_to_root(); 3111 let custom_name = &self.generator.trappable_errors[id]; 3112 let snake = name.to_snake_case(); 3113 let camel = name.to_upper_camel_case(); 3114 uwriteln!( 3115 self.src, 3116 " 3117 fn convert_{snake}(&mut self, err: {root}{custom_name}) -> {wt}::Result<{camel}> {{ 3118 {trait_name}::convert_{snake}(*self, err) 3119 }} 3120 ", 3121 ); 3122 } 3123 } 3124 } 3125 uwriteln!(self.src, "}}"); 3126 3127 ret 3128 } 3129 } 3130 3131 enum ExtraTraitMethod<'a> { 3132 ResourceDrop { name: &'a str }, 3133 ErrorConvert { name: &'a str, id: TypeId }, 3134 } 3135 3136 struct FunctionPartitioning<'a> { 3137 without_store: Vec<(&'a Function, FunctionFlags)>, 3138 with_store: Vec<(&'a Function, FunctionFlags)>, 3139 } 3140 3141 #[derive(Default)] 3142 struct GeneratedTrait { 3143 name: String, 3144 with_store_name: Option<String>, 3145 all_func_flags: FunctionFlags, 3146 } 3147 3148 impl<'a> RustGenerator<'a> for InterfaceGenerator<'a> { 3149 fn resolve(&self) -> &'a Resolve { 3150 self.resolve 3151 } 3152 3153 fn ownership(&self) -> Ownership { 3154 self.generator.opts.ownership 3155 } 3156 3157 fn path_to_interface(&self, interface: InterfaceId) -> Option<String> { 3158 if let Some((cur, _, _)) = self.current_interface { 3159 if cur == interface { 3160 return None; 3161 } 3162 } 3163 let mut path_to_root = self.path_to_root(); 3164 match &self.generator.interface_names[&interface] { 3165 InterfaceName::Remapped { name_at_root, .. } => path_to_root.push_str(name_at_root), 3166 InterfaceName::Path(path) => { 3167 for (i, name) in path.iter().enumerate() { 3168 if i > 0 { 3169 path_to_root.push_str("::"); 3170 } 3171 path_to_root.push_str(name); 3172 } 3173 } 3174 } 3175 Some(path_to_root) 3176 } 3177 3178 fn push_str(&mut self, s: &str) { 3179 self.src.push_str(s); 3180 } 3181 3182 fn info(&self, ty: TypeId) -> TypeInfo { 3183 self.generator.types.get(ty) 3184 } 3185 3186 fn is_imported_interface(&self, interface: InterfaceId) -> bool { 3187 self.generator.interface_last_seen_as_import[&interface] 3188 } 3189 3190 fn wasmtime_path(&self) -> String { 3191 self.generator.wasmtime_path() 3192 } 3193 } 3194 3195 #[derive(Default)] 3196 struct LinkOptionsBuilder { 3197 unstable_features: BTreeSet<String>, 3198 } 3199 impl LinkOptionsBuilder { 3200 fn has_any(&self) -> bool { 3201 !self.unstable_features.is_empty() 3202 } 3203 fn add_world(&mut self, resolve: &Resolve, id: &WorldId) { 3204 let world = &resolve.worlds[*id]; 3205 3206 self.add_stability(&world.stability); 3207 3208 for (_, import) in world.imports.iter() { 3209 match import { 3210 WorldItem::Interface { id, stability } => { 3211 self.add_stability(stability); 3212 self.add_interface(resolve, id); 3213 } 3214 WorldItem::Function(f) => { 3215 self.add_stability(&f.stability); 3216 } 3217 WorldItem::Type(t) => { 3218 self.add_type(resolve, t); 3219 } 3220 } 3221 } 3222 } 3223 fn add_interface(&mut self, resolve: &Resolve, id: &InterfaceId) { 3224 let interface = &resolve.interfaces[*id]; 3225 3226 self.add_stability(&interface.stability); 3227 3228 for (_, t) in interface.types.iter() { 3229 self.add_type(resolve, t); 3230 } 3231 for (_, f) in interface.functions.iter() { 3232 self.add_stability(&f.stability); 3233 } 3234 } 3235 fn add_type(&mut self, resolve: &Resolve, id: &TypeId) { 3236 let t = &resolve.types[*id]; 3237 self.add_stability(&t.stability); 3238 } 3239 fn add_stability(&mut self, stability: &Stability) { 3240 match stability { 3241 Stability::Unstable { feature, .. } => { 3242 self.unstable_features.insert(feature.clone()); 3243 } 3244 Stability::Stable { .. } | Stability::Unknown => {} 3245 } 3246 } 3247 fn write_struct(&self, src: &mut Source) { 3248 if !self.has_any() { 3249 return; 3250 } 3251 3252 let mut unstable_features = self.unstable_features.iter().cloned().collect::<Vec<_>>(); 3253 unstable_features.sort(); 3254 3255 uwriteln!( 3256 src, 3257 " 3258 /// Link-time configurations. 3259 #[derive(Clone, Debug, Default)] 3260 pub struct LinkOptions {{ 3261 " 3262 ); 3263 3264 for feature in unstable_features.iter() { 3265 let feature_rust_name = feature.to_snake_case(); 3266 uwriteln!(src, "{feature_rust_name}: bool,"); 3267 } 3268 3269 uwriteln!(src, "}}"); 3270 uwriteln!(src, "impl LinkOptions {{"); 3271 3272 for feature in unstable_features.iter() { 3273 let feature_rust_name = feature.to_snake_case(); 3274 uwriteln!( 3275 src, 3276 " 3277 /// Enable members marked as `@unstable(feature = {feature})` 3278 pub fn {feature_rust_name}(&mut self, enabled: bool) -> &mut Self {{ 3279 self.{feature_rust_name} = enabled; 3280 self 3281 }} 3282 " 3283 ); 3284 } 3285 3286 uwriteln!(src, "}}"); 3287 } 3288 fn write_impl_from_world(&self, src: &mut Source, path: &str) { 3289 if !self.has_any() { 3290 return; 3291 } 3292 3293 let mut unstable_features = self.unstable_features.iter().cloned().collect::<Vec<_>>(); 3294 unstable_features.sort(); 3295 3296 uwriteln!( 3297 src, 3298 " 3299 impl core::convert::From<LinkOptions> for {path}::LinkOptions {{ 3300 fn from(src: LinkOptions) -> Self {{ 3301 (&src).into() 3302 }} 3303 }} 3304 3305 impl core::convert::From<&LinkOptions> for {path}::LinkOptions {{ 3306 fn from(src: &LinkOptions) -> Self {{ 3307 let mut dest = Self::default(); 3308 " 3309 ); 3310 3311 for feature in unstable_features.iter() { 3312 let feature_rust_name = feature.to_snake_case(); 3313 uwriteln!(src, "dest.{feature_rust_name}(src.{feature_rust_name});"); 3314 } 3315 3316 uwriteln!( 3317 src, 3318 " 3319 dest 3320 }} 3321 }} 3322 " 3323 ); 3324 } 3325 } 3326 3327 struct FeatureGate { 3328 close: bool, 3329 } 3330 impl FeatureGate { 3331 fn open(src: &mut Source, stability: &Stability) -> FeatureGate { 3332 let close = if let Stability::Unstable { feature, .. } = stability { 3333 let feature_rust_name = feature.to_snake_case(); 3334 uwrite!(src, "if options.{feature_rust_name} {{"); 3335 true 3336 } else { 3337 false 3338 }; 3339 Self { close } 3340 } 3341 3342 fn close(self, src: &mut Source) { 3343 if self.close { 3344 uwriteln!(src, "}}"); 3345 } 3346 } 3347 } 3348 3349 /// Produce a string for tracing a function argument. 3350 fn formatting_for_arg( 3351 name: &str, 3352 index: usize, 3353 ty: Type, 3354 resolve: &Resolve, 3355 flags: FunctionFlags, 3356 ) -> String { 3357 if !flags.contains(FunctionFlags::VERBOSE_TRACING) && type_contains_lists(ty, resolve) { 3358 return format!("{name} = tracing::field::debug(\"...\")"); 3359 } 3360 3361 // Normal tracing. 3362 format!("{name} = tracing::field::debug(&arg{index})") 3363 } 3364 3365 /// Produce a string for tracing function results. 3366 fn formatting_for_results(result: Option<Type>, resolve: &Resolve, flags: FunctionFlags) -> String { 3367 let contains_lists = match result { 3368 Some(ty) => type_contains_lists(ty, resolve), 3369 None => false, 3370 }; 3371 3372 if !flags.contains(FunctionFlags::VERBOSE_TRACING) && contains_lists { 3373 return format!("result = tracing::field::debug(\"...\")"); 3374 } 3375 3376 // Normal tracing. 3377 format!("result = tracing::field::debug(&r)") 3378 } 3379 3380 /// Test whether the given type contains lists. 3381 /// 3382 /// Here, a `string` is not considered a list. 3383 fn type_contains_lists(ty: Type, resolve: &Resolve) -> bool { 3384 match ty { 3385 Type::Id(id) => match &resolve.types[id].kind { 3386 TypeDefKind::Resource 3387 | TypeDefKind::Unknown 3388 | TypeDefKind::Flags(_) 3389 | TypeDefKind::Handle(_) 3390 | TypeDefKind::Enum(_) 3391 | TypeDefKind::Stream(_) 3392 | TypeDefKind::Future(_) => false, 3393 TypeDefKind::Option(ty) => type_contains_lists(*ty, resolve), 3394 TypeDefKind::Result(Result_ { ok, err }) => { 3395 option_type_contains_lists(*ok, resolve) 3396 || option_type_contains_lists(*err, resolve) 3397 } 3398 TypeDefKind::Record(record) => record 3399 .fields 3400 .iter() 3401 .any(|field| type_contains_lists(field.ty, resolve)), 3402 TypeDefKind::Tuple(tuple) => tuple 3403 .types 3404 .iter() 3405 .any(|ty| type_contains_lists(*ty, resolve)), 3406 TypeDefKind::Variant(variant) => variant 3407 .cases 3408 .iter() 3409 .any(|case| option_type_contains_lists(case.ty, resolve)), 3410 TypeDefKind::Type(ty) => type_contains_lists(*ty, resolve), 3411 TypeDefKind::List(_) => true, 3412 TypeDefKind::FixedSizeList(..) => todo!(), 3413 TypeDefKind::Map(..) => todo!(), 3414 }, 3415 3416 // Technically strings are lists too, but we ignore that here because 3417 // they're usually short. 3418 _ => false, 3419 } 3420 } 3421 3422 fn option_type_contains_lists(ty: Option<Type>, resolve: &Resolve) -> bool { 3423 match ty { 3424 Some(ty) => type_contains_lists(ty, resolve), 3425 None => false, 3426 } 3427 } 3428 3429 /// When an interface `use`s a type from another interface, it creates a new TypeId 3430 /// referring to the definition TypeId. Chase this chain of references down to 3431 /// a TypeId for type's definition. 3432 fn resolve_type_definition_id(resolve: &Resolve, mut id: TypeId) -> TypeId { 3433 loop { 3434 match resolve.types[id].kind { 3435 TypeDefKind::Type(Type::Id(def_id)) => id = def_id, 3436 _ => return id, 3437 } 3438 } 3439 } 3440 3441 fn rust_function_name(func: &Function) -> String { 3442 match func.kind { 3443 FunctionKind::Constructor(_) => "new".to_string(), 3444 FunctionKind::Method(_) 3445 | FunctionKind::Static(_) 3446 | FunctionKind::AsyncMethod(_) 3447 | FunctionKind::AsyncStatic(_) 3448 | FunctionKind::Freestanding 3449 | FunctionKind::AsyncFreestanding => to_rust_ident(func.item_name()), 3450 } 3451 } 3452 3453 fn func_field_name(resolve: &Resolve, func: &Function) -> String { 3454 let mut name = String::new(); 3455 match func.kind { 3456 FunctionKind::Method(id) | FunctionKind::AsyncMethod(id) => { 3457 name.push_str("method-"); 3458 name.push_str(resolve.types[id].name.as_ref().unwrap()); 3459 name.push_str("-"); 3460 } 3461 FunctionKind::Static(id) | FunctionKind::AsyncStatic(id) => { 3462 name.push_str("static-"); 3463 name.push_str(resolve.types[id].name.as_ref().unwrap()); 3464 name.push_str("-"); 3465 } 3466 FunctionKind::Constructor(id) => { 3467 name.push_str("constructor-"); 3468 name.push_str(resolve.types[id].name.as_ref().unwrap()); 3469 name.push_str("-"); 3470 } 3471 FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {} 3472 } 3473 name.push_str(func.item_name()); 3474 name.to_snake_case() 3475 } 3476 3477 fn get_resources<'a>( 3478 resolve: &'a Resolve, 3479 id: InterfaceId, 3480 ) -> impl Iterator<Item = (TypeId, &'a str)> + 'a { 3481 resolve.interfaces[id] 3482 .types 3483 .iter() 3484 .filter_map(move |(name, ty)| match &resolve.types[*ty].kind { 3485 TypeDefKind::Resource => Some((*ty, name.as_str())), 3486 _ => None, 3487 }) 3488 } 3489 3490 fn get_resource_functions<'a>(resolve: &'a Resolve, resource_id: TypeId) -> Vec<&'a Function> { 3491 let resource = &resolve.types[resource_id]; 3492 match resource.owner { 3493 TypeOwner::World(id) => resolve.worlds[id] 3494 .imports 3495 .values() 3496 .filter_map(|item| match item { 3497 WorldItem::Function(f) => Some(f), 3498 _ => None, 3499 }) 3500 .filter(|f| f.kind.resource() == Some(resource_id)) 3501 .collect(), 3502 TypeOwner::Interface(id) => resolve.interfaces[id] 3503 .functions 3504 .values() 3505 .filter(|f| f.kind.resource() == Some(resource_id)) 3506 .collect::<Vec<_>>(), 3507 TypeOwner::None => { 3508 panic!("A resource must be owned by a world or interface"); 3509 } 3510 } 3511 } 3512 3513 fn get_world_resources<'a>( 3514 resolve: &'a Resolve, 3515 id: WorldId, 3516 ) -> impl Iterator<Item = (TypeId, &'a str)> + 'a { 3517 resolve.worlds[id] 3518 .imports 3519 .iter() 3520 .filter_map(move |(name, item)| match item { 3521 WorldItem::Type(id) => match resolve.types[*id].kind { 3522 TypeDefKind::Resource => Some(match name { 3523 WorldKey::Name(s) => (*id, s.as_str()), 3524 WorldKey::Interface(_) => unreachable!(), 3525 }), 3526 _ => None, 3527 }, 3528 _ => None, 3529 }) 3530 } 3531