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