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