Skip to main content

js_component_bindgen/
transpile_bindgen.rs

1use std::cell::RefCell;
2use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
3use std::fmt::Write;
4use std::mem;
5use std::ops::Index;
6
7use base64::Engine as _;
8use base64::engine::general_purpose;
9use heck::{ToKebabCase, ToLowerCamelCase, ToUpperCamelCase};
10use semver::Version;
11use wasmtime_environ::component::{
12    CanonicalOptions, CanonicalOptionsDataModel, Component, ComponentExtern, ComponentTranslation,
13    ComponentTypes, CoreDef, CoreExport, Export, ExportItem, FixedEncoding, GlobalInitializer,
14    InstantiateModule, InterfaceType, LinearMemoryOptions, LoweredIndex, ResourceIndex,
15    RuntimeComponentInstanceIndex, RuntimeImportIndex, RuntimeInstanceIndex, StaticModuleIndex,
16    Trampoline, TrampolineIndex, TypeDef, TypeFuncIndex, TypeFutureTableIndex,
17    TypeResourceTableIndex, TypeStreamTableIndex,
18};
19use wasmtime_environ::component::{
20    ExtractCallback, ImportIndex, NameMapNoIntern, Transcode,
21    TypeComponentLocalErrorContextTableIndex,
22};
23use wasmtime_environ::{EntityIndex, PrimaryMap};
24use wit_bindgen_core::abi::{self, LiftLower};
25use wit_component::StringEncoding;
26use wit_parser::abi::AbiVariant;
27use wit_parser::{
28    Function, FunctionKind, Handle, Resolve, Result_, SizeAlign, Type, TypeDefKind, TypeId,
29    WorldId, WorldItem, WorldKey,
30};
31
32use crate::esm_bindgen::EsmBindgen;
33use crate::files::Files;
34use crate::function_bindgen::{
35    ErrHandling, FunctionBindgen, FunctionBindgenComponentState, PayloadTypeMetadata, ResourceData,
36    ResourceExtraData, ResourceMap, ResourceTable,
37};
38use crate::intrinsics::component::ComponentIntrinsic;
39use crate::intrinsics::js_helper::JsHelperIntrinsic;
40use crate::intrinsics::lift::LiftIntrinsic;
41use crate::intrinsics::lower::LowerIntrinsic;
42use crate::intrinsics::p3::async_future::AsyncFutureIntrinsic;
43use crate::intrinsics::p3::async_stream::AsyncStreamIntrinsic;
44use crate::intrinsics::p3::async_task::AsyncTaskIntrinsic;
45use crate::intrinsics::p3::error_context::ErrCtxIntrinsic;
46use crate::intrinsics::p3::host::HostIntrinsic;
47use crate::intrinsics::p3::waitable::WaitableIntrinsic;
48use crate::intrinsics::resource::ResourceIntrinsic;
49use crate::intrinsics::string::StringIntrinsic;
50use crate::intrinsics::webidl::WebIdlIntrinsic;
51use crate::intrinsics::{
52    AsyncDeterminismProfile, Intrinsic, RenderIntrinsicsArgs, render_intrinsics,
53};
54use crate::names::{LocalNames, is_js_reserved_word, maybe_quote_id, maybe_quote_member};
55use crate::{
56    FunctionIdentifier, ManagesIntrinsics, core, get_thrown_type, is_async_fn,
57    requires_async_porcelain, source, uwrite, uwriteln,
58};
59
60/// Size of flat parameters that can be sent, for example via the `task.return`
61/// intrinsic, when returning from an async func
62const MAX_FLAT_PARAMS: usize = 16;
63/// Maximum direct flat results for sync canonical lowering.
64const MAX_FLAT_RESULTS: usize = 1;
65
66#[derive(Debug, Default, Clone, bon::Builder)]
67pub struct TranspileOpts {
68    pub name: String,
69    /// Disables generation of `*.d.ts` files and instead only generates `*.js`
70    /// source files.
71    #[builder(default)]
72    pub no_typescript: bool,
73    /// Provide a custom JS instantiation API for the component instead
74    /// of the direct importable native ESM output.
75    pub instantiation_mode: Option<InstantiationMode>,
76    /// Configure how import bindings are provided, as high-level JS bindings,
77    /// or as hybrid optimized bindings.
78    pub import_bindings: Option<BindingsMode>,
79    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of
80    /// component import specifiers to JS import specifiers.
81    pub map: Option<HashMap<String, String>>,
82    /// Disables compatibility in Node.js without a fetch global.
83    #[builder(default)]
84    pub nodejs_compat_disabled: bool,
85    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode
86    /// (set to 0 to disable all base64 inlining)
87    #[builder(default)]
88    pub base64_cutoff: usize,
89    /// Enables compatibility for JS environments without top-level await support
90    /// via an async $init promise export to wait for instead.
91    #[builder(default)]
92    pub tla_compat: bool,
93    /// Disable verification of component Wasm data structures when
94    /// lifting as a production optimization
95    #[builder(default)]
96    pub valid_lifting_optimization: bool,
97    /// Whether or not to emit `tracing` calls on function entry/exit.
98    #[builder(default)]
99    pub tracing: bool,
100    /// Throw the lifted error payload directly for top-level `result` errors
101    /// instead of wrapping it in a generated `ComponentError`.
102    #[builder(default)]
103    pub no_component_error_wrapping: bool,
104    /// Whether to generate namespaced exports like `foo as "local:package/foo"`.
105    /// These exports can break typescript builds.
106    #[builder(default)]
107    pub no_namespaced_exports: bool,
108    /// Whether to output core Wasm utilizing multi-memory or to polyfill
109    /// this handling.
110    #[builder(default)]
111    pub multi_memory: bool,
112    /// Whether to generate types for a guest module using module declarations.
113    #[builder(default)]
114    pub guest: bool,
115    /// Configure whether to use `async` imports or exports with
116    /// JavaScript Promise Integration (JSPI).
117    pub async_mode: Option<AsyncMode>,
118    /// Configure whether to generate code that includes strict type checks
119    #[builder(default)]
120    pub strict: bool,
121    /// Represent WIT flags as bigint values instead of objects of booleans.
122    #[builder(default)]
123    pub flags_as_bigint: bool,
124    /// Inline WIT variant cases in their discriminated unions instead of
125    /// generating a named interface for each case.
126    #[builder(default)]
127    pub variants_inline_cases: bool,
128    /// Generate runtime namespace objects for WIT flags, enums, and variants.
129    /// Implies `flags_as_bigint` and conflicts with `variants_inline_cases`.
130    #[builder(default)]
131    pub use_namespace_objects: bool,
132    /// Represent WIT enum values as SCREAMING_SNAKE_CASE strings.
133    #[builder(default)]
134    pub enum_values_screaming_snake_case: bool,
135    /// Whether the core module(s) to be wrapped were actually transpiled from Wasm to JS (asm.js) and thus need shimming for i64
136    #[builder(default)]
137    pub asmjs: bool,
138    /// Whether the target JS engine supports the exception handling proposal
139    /// (`try_table`/exnref).
140    ///
141    /// When disabled (the default), the exceptions feature is masked off
142    /// during component validation so that wasmtime-environ's FACT-generated
143    /// adapters do not wrap calls in exception barriers, which would only run
144    /// behind a flag in today's JS engines.
145    #[builder(default)]
146    pub supports_wasm_exnref: bool,
147}
148
149#[derive(Default, Clone, Debug)]
150#[non_exhaustive]
151pub enum AsyncMode {
152    #[default]
153    Sync,
154    JavaScriptPromiseIntegration {
155        imports: Vec<String>,
156        exports: Vec<String>,
157    },
158}
159
160#[derive(Default, Clone, Debug)]
161#[non_exhaustive]
162pub enum InstantiationMode {
163    #[default]
164    Async,
165    Sync,
166}
167
168/// Internal Bindgen calling convention
169enum CallType {
170    /// Standard calls - inner function is called directly with parameters
171    Standard,
172    /// Standard calls that are async (p3)
173    AsyncStandard,
174    /// Exported resource method calls - this is passed as the first argument
175    FirstArgIsThis,
176    /// Exported resource method calls that are async (p3)
177    AsyncFirstArgIsThis,
178    /// Imported resource method calls - callee is a member of the parameter
179    CalleeResourceDispatch,
180    /// Imported resource method calls that are async (p3)
181    AsyncCalleeResourceDispatch,
182}
183
184#[derive(Default, Clone, Debug)]
185#[non_exhaustive]
186pub enum BindingsMode {
187    Hybrid,
188    #[default]
189    Js,
190    Optimized,
191    DirectOptimized,
192}
193
194struct JsBindgen<'a> {
195    local_names: LocalNames,
196
197    esm_bindgen: EsmBindgen,
198
199    /// The source code for the "main" file that's going to be created for the
200    /// component we're generating bindings for. This is incrementally added to
201    /// over time and primarily contains the main `instantiate` function as well
202    /// as a type-description of the input/output interfaces.
203    src: Source,
204
205    /// Core module count
206    core_module_cnt: usize,
207
208    /// Various options for code generation.
209    opts: &'a TranspileOpts,
210
211    /// List of all intrinsics emitted to `src` so far.
212    all_intrinsics: BTreeSet<Intrinsic>,
213
214    /// List of all core Wasm exported functions (and if is async) referenced in
215    /// `src` so far.
216    ///
217    /// The second boolean is true when async procelain is required *or* if the
218    /// export itself is async.
219    all_core_exported_funcs: Vec<(String, bool)>,
220}
221
222/// Arguments provided to `JSBindgen::bindgen`, normally called to perform bindgen on a given function
223struct JsFunctionBindgenArgs<'a> {
224    /// Number of params that the function expects
225    nparams: usize,
226    /// Internal convention for function calls (ex. whether the first argument is known to be 'this')
227    call_type: CallType,
228    /// Interface name (if inside an interface)
229    iface_name: Option<&'a str>,
230    /// Callee of the function
231    callee: &'a str,
232    /// Canon opts provided for the functions
233    opts: &'a CanonicalOptions,
234    /// Parsed function metadata
235    func: &'a Function,
236    resource_map: &'a ResourceMap,
237    /// ABI variant of the function
238    abi: AbiVariant,
239    /// Whether the function in question is a host async function (i.e. JSPI)
240    requires_async_porcelain: bool,
241    /// Whether the function in question is a guest async function (i.e. WASI P3)
242    is_async: bool,
243    /// Whether an async export must preserve its future result as an awaitable layer.
244    wrap_async_future_result: bool,
245    /// Whether the function in question is being generated for an import
246    /// (false implies generation is happening for an export)
247    for_import: bool,
248}
249
250impl<'a> ManagesIntrinsics for JsBindgen<'a> {
251    fn add_intrinsic(&mut self, intrinsic: Intrinsic) {
252        self.intrinsic(intrinsic);
253    }
254}
255
256#[derive(PartialEq, Eq, Clone)]
257#[non_exhaustive]
258pub enum ExportKind {
259    /// Maps to `wasmtime_environ::export::LiftedFunction`
260    LiftedFunction,
261    /// Maps to `wasmtime_environ::export::Instance`
262    Instance,
263}
264
265#[allow(clippy::too_many_arguments)]
266pub fn transpile_bindgen(
267    name: &str,
268    component: &ComponentTranslation,
269    modules: &PrimaryMap<StaticModuleIndex, core::Translation<'_>>,
270    types: &ComponentTypes,
271    resolve: &Resolve,
272    id: WorldId,
273    opts: TranspileOpts,
274    files: &mut Files,
275) -> (Vec<String>, Vec<(String, ExportKind)>) {
276    let (async_imports, async_exports) = match opts.async_mode.clone() {
277        None | Some(AsyncMode::Sync) => (Default::default(), Default::default()),
278        Some(AsyncMode::JavaScriptPromiseIntegration { imports, exports }) => {
279            (imports.into_iter().collect(), exports.into_iter().collect())
280        }
281    };
282
283    let mut bindgen = JsBindgen {
284        local_names: LocalNames::default(),
285        src: Source::default(),
286        esm_bindgen: EsmBindgen::default(),
287        core_module_cnt: 0,
288        opts: &opts,
289        all_intrinsics: BTreeSet::new(),
290        all_core_exported_funcs: Vec::new(),
291    };
292    bindgen.local_names.exclude_globals(
293        &Intrinsic::get_global_names()
294            .into_iter()
295            .collect::<Vec<_>>(),
296    );
297    bindgen.core_module_cnt = modules.len();
298
299    // Generate mapping of stream tables to components that are related
300    let mut stream_tables = BTreeMap::new();
301    for idx in 0..component.component.num_stream_tables {
302        let stream_table_idx = TypeStreamTableIndex::from_u32(idx as u32);
303        let stream_table_ty = &types[stream_table_idx];
304        stream_tables.insert(stream_table_idx, stream_table_ty.instance);
305    }
306
307    // Generate mapping of future tables to components that are related
308    let mut future_tables = BTreeMap::new();
309    for idx in 0..component.component.num_future_tables {
310        let future_table_idx = TypeFutureTableIndex::from_u32(idx as u32);
311        let future_table_ty = &types[future_table_idx];
312        future_tables.insert(future_table_idx, future_table_ty.instance);
313    }
314
315    // Generate mapping of err_ctx tables to components that are related
316    let mut err_ctx_tables = BTreeMap::new();
317    for idx in 0..component.component.num_error_context_tables {
318        let err_ctx_table_idx = TypeComponentLocalErrorContextTableIndex::from_u32(idx as u32);
319        let err_ctx_table_ty = &types[err_ctx_table_idx];
320        err_ctx_tables.insert(err_ctx_table_idx, err_ctx_table_ty.instance);
321    }
322
323    // Bindings are generated when the `instantiate` method is called on the
324    // Instantiator structure created below
325    let mut instantiator = Instantiator {
326        src: Source::default(),
327        sizes: SizeAlign::default(),
328        bindgen: &mut bindgen,
329        modules,
330        instances: Default::default(),
331        error_context_component_initialized: (0..component
332            .component
333            .num_runtime_component_instances)
334            .map(|_| false)
335            .collect(),
336        error_context_component_table_initialized: (0..component
337            .component
338            .num_error_context_tables)
339            .map(|_| false)
340            .collect(),
341        resolve,
342        world: id,
343        translation: component,
344        component: &component.component,
345        types,
346        async_imports,
347        async_exports,
348        imports: Default::default(),
349        exports: Default::default(),
350        lowering_options: Default::default(),
351        used_instance_flags: Default::default(),
352        defined_resource_classes: Default::default(),
353        imports_resource_types: Default::default(),
354        imports_resource_index_types: Default::default(),
355        exports_resource_types: Default::default(),
356        exports_resource_index_types: Default::default(),
357        resource_exports: Default::default(),
358        resource_imports: Default::default(),
359        resources_initialized: BTreeMap::new(),
360        resource_tables_initialized: BTreeMap::new(),
361        stream_tables,
362        future_tables,
363        err_ctx_tables,
364        init_current_module: None,
365        context_components: Default::default(),
366    };
367    instantiator.sizes.fill(resolve);
368    instantiator.initialize();
369    instantiator.instantiate();
370
371    instantiator.resource_definitions();
372    instantiator.instance_flags();
373
374    instantiator.bindgen.src.js(&instantiator.src.js);
375    instantiator.bindgen.src.js_init(&instantiator.src.js_init);
376
377    instantiator
378        .bindgen
379        .finish_component(name, files, &opts, source::Source::default());
380
381    let exports = instantiator
382        .bindgen
383        .esm_bindgen
384        .exports()
385        .iter()
386        .map(|(export_name, canon_export_name)| {
387            let expected_export_name =
388                if canon_export_name.contains(':') || canon_export_name.starts_with("[async]") {
389                    canon_export_name.to_string()
390                } else {
391                    canon_export_name.to_kebab_case()
392                };
393            let (export_idx, _extern_data) = instantiator
394                .component
395                .exports
396                .get(&expected_export_name, &NameMapNoIntern)
397                .unwrap_or_else(|| panic!("failed to find component export [{expected_export_name}] (original '{canon_export_name}')"));
398
399            let export_kind = match &instantiator.component.export_items[*export_idx] {
400                wasmtime_environ::component::Export::LiftedFunction { .. } => {
401                    ExportKind::LiftedFunction
402                }
403                wasmtime_environ::component::Export::Instance { .. } => {
404                    ExportKind::Instance
405                }
406                _ => panic!("unexpected export kind"),
407            };
408
409
410            (
411                export_name.to_string(),
412export_kind,
413            )
414        })
415        .collect();
416
417    (bindgen.esm_bindgen.import_specifiers(), exports)
418}
419
420impl JsBindgen<'_> {
421    fn finish_component(
422        &mut self,
423        name: &str,
424        files: &mut Files,
425        opts: &TranspileOpts,
426        intrinsic_definitions: source::Source,
427    ) {
428        let mut output = source::Source::default();
429        let mut compilation_promises = source::Source::default();
430        let mut core_exported_funcs = source::Source::default();
431
432        for (core_export_fn, is_async) in self.all_core_exported_funcs.iter() {
433            let local_name = self.local_names.get(core_export_fn);
434            if *is_async {
435                uwriteln!(
436                    core_exported_funcs,
437                    "{local_name} = WebAssembly.promising({core_export_fn});",
438                );
439            } else {
440                uwriteln!(core_exported_funcs, "{local_name} = {core_export_fn};",);
441            }
442        }
443
444        // adds a default implementation of `getCoreModule`
445        if matches!(self.opts.instantiation_mode, Some(InstantiationMode::Async)) {
446            uwriteln!(
447                compilation_promises,
448                "if (!getCoreModule) getCoreModule = (name) => {}(new URL(`./${{name}}`, import.meta.url));",
449                self.intrinsic(Intrinsic::FetchCompile)
450            );
451        }
452
453        // Setup the compilation data and compilation promises
454        let mut removed = BTreeSet::new();
455        for i in 0..self.core_module_cnt {
456            let local_name = format!("module{i}");
457            let mut name_idx = core_file_name(name, i as u32);
458            if self.opts.instantiation_mode.is_some() {
459                uwriteln!(
460                    compilation_promises,
461                    "const {local_name} = getCoreModule('{name_idx}');"
462                );
463            } else if files.get_size(&name_idx).unwrap() < self.opts.base64_cutoff {
464                assert!(removed.insert(i));
465                let data = files.remove(&name_idx).unwrap();
466                uwriteln!(
467                    compilation_promises,
468                    "const {local_name} = {}('{}');",
469                    self.intrinsic(Intrinsic::Base64Compile),
470                    general_purpose::STANDARD_NO_PAD.encode(&data),
471                );
472            } else {
473                // Maintain numerical file orderings when a previous file was
474                // inlined
475                if let Some(&replacement) = removed.iter().next() {
476                    assert!(removed.remove(&replacement) && removed.insert(i));
477                    let data = files.remove(&name_idx).unwrap();
478                    name_idx = core_file_name(name, replacement as u32);
479                    files.push(&name_idx, &data);
480                }
481                uwriteln!(
482                    compilation_promises,
483                    "const {local_name} = {}(new URL('./{name_idx}', import.meta.url));",
484                    self.intrinsic(Intrinsic::FetchCompile)
485                );
486            }
487        }
488
489        // Render the telemery directive
490        uwriteln!(output, r#""use components";"#);
491
492        let render_args = RenderIntrinsicsArgs::builder()
493            .intrinsics(&mut self.all_intrinsics)
494            .instantiation_occurred(self.opts.instantiation_mode.is_some())
495            .determinism_profile(AsyncDeterminismProfile::default())
496            .transpile_opts(opts)
497            .build();
498        let js_intrinsics = render_intrinsics(render_args);
499
500        // Write out instantiation
501        if let Some(instantiation) = &self.opts.instantiation_mode {
502            uwrite!(
503                output,
504                "\
505                    export function instantiate(getCoreModule, imports, instantiateCore = {}) {{
506                        {}
507                        {}
508                        {}
509                ",
510                match instantiation {
511                    InstantiationMode::Async => "WebAssembly.instantiate",
512                    InstantiationMode::Sync =>
513                        "(module, importObject) => new WebAssembly.Instance(module, importObject)",
514                },
515                &js_intrinsics as &str,
516                &intrinsic_definitions as &str,
517                &compilation_promises as &str,
518            );
519        }
520
521        // Render all imports
522        let imports_object = if self.opts.instantiation_mode.is_some() {
523            Some("imports")
524        } else {
525            None
526        };
527        self.esm_bindgen
528            .render_imports(&mut output, imports_object, &mut self.local_names);
529
530        // Create instantiation code
531        if self.opts.instantiation_mode.is_some() {
532            uwrite!(&mut self.src.js, "{}", &core_exported_funcs as &str);
533            self.esm_bindgen.render_exports(
534                &mut self.src.js,
535                self.opts.instantiation_mode.is_some(),
536                &mut self.local_names,
537                opts,
538            );
539            uwrite!(
540                output,
541                "\
542                        let gen = (function* _initGenerator () {{
543                            {}\
544                            {};
545                        }})();
546                        let promise, resolve, reject;
547                        function runNext (value) {{
548                            try {{
549                                let done;
550                                do {{
551                                    ({{ value, done }} = gen.next(value));
552                                }} while (!(value instanceof Promise) && !done);
553                                if (done) {{
554                                    if (resolve) return resolve(value);
555                                    else return value;
556                                }}
557                                if (!promise) promise = new Promise((_resolve, _reject) => (resolve = _resolve, reject = _reject));
558                                value.then(nextVal => done ? resolve() : runNext(nextVal), reject);
559                            }}
560                            catch (e) {{
561                                if (reject) reject(e);
562                                else throw e;
563                            }}
564                        }}
565                        const maybeSyncReturn = runNext(null);
566                        return promise || maybeSyncReturn;
567                    }};
568                ",
569                &self.src.js_init as &str,
570                &self.src.js as &str,
571            );
572        } else {
573            let (maybe_init_export, maybe_init) =
574                if self.opts.tla_compat && opts.instantiation_mode.is_none() {
575                    uwriteln!(self.src.js_init, "_initialized = true;");
576                    (
577                        "\
578                        let _initialized = false;
579                        export ",
580                        "",
581                    )
582                } else {
583                    (
584                        "",
585                        "
586                        await $init;
587                    ",
588                    )
589                };
590
591            uwrite!(
592                output,
593                "\
594                    {}
595                    {}
596                    {}
597                    {maybe_init_export}const $init = (() => {{
598                        let gen = (function* _initGenerator () {{
599                            {}\
600                            {}\
601                            {}\
602                        }})();
603                        let promise, resolve, reject;
604                        function runNext (value) {{
605                            try {{
606                                let done;
607                                do {{
608                                    ({{ value, done }} = gen.next(value));
609                                }} while (!(value instanceof Promise) && !done);
610                                if (done) {{
611                                    if (resolve) resolve(value);
612                                    else return value;
613                                }}
614                                if (!promise) promise = new Promise((_resolve, _reject) => (resolve = _resolve, reject = _reject));
615                                value.then(runNext, reject);
616                            }}
617                            catch (e) {{
618                                if (reject) reject(e);
619                                else throw e;
620                            }}
621                        }}
622                        const maybeSyncReturn = runNext(null);
623                        return promise || maybeSyncReturn;
624                    }})();
625                    {maybe_init}\
626                ",
627                &js_intrinsics as &str,
628                &intrinsic_definitions as &str,
629                &self.src.js as &str,
630                &compilation_promises as &str,
631                &self.src.js_init as &str,
632                &core_exported_funcs as &str,
633            );
634
635            self.esm_bindgen.render_exports(
636                &mut output,
637                self.opts.instantiation_mode.is_some(),
638                &mut self.local_names,
639                opts,
640            );
641        }
642
643        // The generated ES module will have a `util` member that can be used,
644        // (but may be empty), which hosts can use to perform special functionality
645        // like nesting futures where necessary.
646        self.write_util_export(&mut output);
647
648        let mut bytes = output.as_bytes();
649        // strip leading newline
650        if bytes[0] == b'\n' {
651            bytes = &bytes[1..];
652        }
653        files.push(&format!("{name}.js"), bytes);
654    }
655
656    fn intrinsic(&mut self, intrinsic: Intrinsic) -> String {
657        self.all_intrinsics.insert(intrinsic);
658        intrinsic.name().to_string()
659    }
660
661    /// Write out utility helpers/objects (available via esModule._util)
662    fn write_util_export(&mut self, output: &mut source::Source) {
663        // Future` class that can be used by external consumers (e.g. host code) to build nested future values
664        //
665        // This class is exposed via module._util, always
666        let maybe_ext_future_class = if self.all_intrinsics.contains(&Intrinsic::AsyncFuture(
667            AsyncFutureIntrinsic::HostFutureClass,
668        )) {
669            r#"
670                  Future: class Future {
671                      #value;
672                      #hidden = 0;
673                      constructor(value) {
674                          this.#value = value;
675                      }
676                      get then() {
677                          if (this.#hidden !== 0) {
678                              return undefined;
679                          }
680                          return (resolve) => {
681                              if (this.#value instanceof Future) {
682                                  this.#value.resolveAsValue(resolve);
683                              } else {
684                                  resolve(this.#value);
685                              }
686                          };
687                      }
688                      resolveAsValue(resolve) {
689                          this.#hidden++;
690                          try {
691                              resolve(this);
692                          } finally {
693                              this.#hidden--;
694                          }
695                      }
696                  },
697                "#
698            .to_string()
699        } else {
700            "".into()
701        };
702
703        uwriteln!(
704            output,
705            r#"
706              export const _util = {{
707                  {maybe_ext_future_class}
708              }}
709            "#,
710        );
711    }
712}
713
714/// Helper structure used to generate the `instantiate` method of a component.
715///
716/// This is the main structure for parsing the output of Wasmtime.
717pub(crate) struct Instantiator<'a, 'b> {
718    src: Source,
719    bindgen: &'a mut JsBindgen<'b>,
720    modules: &'a PrimaryMap<StaticModuleIndex, core::Translation<'a>>,
721    instances: PrimaryMap<RuntimeInstanceIndex, StaticModuleIndex>,
722    types: &'a ComponentTypes,
723    resolve: &'a Resolve,
724    world: WorldId,
725    sizes: SizeAlign,
726    component: &'a Component,
727
728    /// Map of error contexts tables for a given component & error context index pair
729    /// that have been initialized
730    error_context_component_initialized: PrimaryMap<RuntimeComponentInstanceIndex, bool>,
731    error_context_component_table_initialized:
732        PrimaryMap<TypeComponentLocalErrorContextTableIndex, bool>,
733
734    /// Component-level translation information, including trampolines
735    translation: &'a ComponentTranslation,
736
737    /// Lookup of exported types to resource indices
738    exports_resource_types: BTreeMap<TypeId, ResourceIndex>,
739    /// Lookup of resource indices to exported types
740    exports_resource_index_types: BTreeMap<ResourceIndex, TypeId>,
741
742    /// Lookup of imported types to resource indices
743    imports_resource_types: BTreeMap<TypeId, ResourceIndex>,
744    /// Lookup of resource indices to imported types
745    #[allow(unused)]
746    imports_resource_index_types: BTreeMap<ResourceIndex, TypeId>,
747
748    resources_initialized: BTreeMap<ResourceIndex, bool>,
749    resource_tables_initialized: BTreeMap<TypeResourceTableIndex, bool>,
750
751    exports: BTreeMap<String, WorldKey>,
752    imports: BTreeMap<String, WorldKey>,
753    /// Instance flags which references have been emitted externally at least once.
754    used_instance_flags: RefCell<BTreeSet<RuntimeComponentInstanceIndex>>,
755    defined_resource_classes: BTreeSet<String>,
756    async_imports: HashSet<String>,
757    async_exports: HashSet<String>,
758    lowering_options:
759        PrimaryMap<LoweredIndex, (&'a CanonicalOptions, TrampolineIndex, TypeFuncIndex)>,
760
761    /// Mapping of stream table indices to component indices
762    stream_tables: BTreeMap<TypeStreamTableIndex, RuntimeComponentInstanceIndex>,
763
764    /// Mapping of future table indices to component indices
765    future_tables: BTreeMap<TypeFutureTableIndex, RuntimeComponentInstanceIndex>,
766
767    /// Mapping of err ctx indices to component indices
768    err_ctx_tables:
769        BTreeMap<TypeComponentLocalErrorContextTableIndex, RuntimeComponentInstanceIndex>,
770
771    /// Map of exported resources built during export bindgen
772    resource_exports: ResourceMap,
773    /// Map of imported resources built during export bindgen
774    resource_imports: ResourceMap,
775
776    /// Component index of the module that is currentlty being initialized
777    ///
778    /// This is only populated after processing of `GlobalInitializer::InstantiateModule`
779    /// blocks has started, and is likely to be stale if read too late (i.e. it will be set
780    /// to the last module processed).
781    init_current_module: Option<RuntimeComponentInstanceIndex>,
782
783    /// Component instances whose core modules import `context.get`/`context.set`.
784    /// These need a task whenever generated host-side JS enters guest core
785    /// Wasm, including core start functions and resource destructors.
786    context_components: RefCell<BTreeSet<RuntimeComponentInstanceIndex>>,
787}
788
789impl<'a> ManagesIntrinsics for Instantiator<'a, '_> {
790    fn add_intrinsic(&mut self, intrinsic: Intrinsic) {
791        self.bindgen.intrinsic(intrinsic);
792    }
793}
794
795impl<'a> Instantiator<'a, '_> {
796    fn initialize(&mut self) {
797        // Populate reverse map from import and export names to world items
798        for (key, _) in &self.resolve.worlds[self.world].imports {
799            let name = &self.resolve.name_world_key(key);
800            self.imports.insert(name.to_string(), key.clone());
801        }
802        for (key, _) in &self.resolve.worlds[self.world].exports {
803            let name = &self.resolve.name_world_key(key);
804            self.exports.insert(name.to_string(), key.clone());
805        }
806
807        // Populate reverse map from TypeId to ResourceIndex
808        // Populate the resource type to resource index map
809        for (key, item) in &self.resolve.worlds[self.world].imports {
810            let name = &self.resolve.name_world_key(key);
811            let Some((_, (_, import))) = self
812                .component
813                .import_types
814                .iter()
815                .find(|(_, (impt_name, _))| impt_name == name)
816            else {
817                match item {
818                    WorldItem::Interface { .. } => {
819                        unreachable!("unexpected interface in import types during initialization")
820                    }
821                    WorldItem::Function(_) => {
822                        unreachable!("unexpected function in import types during initialization")
823                    }
824                    WorldItem::Type { id, .. } => {
825                        assert!(!matches!(
826                            self.resolve.types[*id].kind,
827                            TypeDefKind::Resource
828                        ))
829                    }
830                }
831                continue;
832            };
833            match item {
834                WorldItem::Interface { id, .. } => {
835                    let TypeDef::ComponentInstance(instance) = &import.ty else {
836                        unreachable!("unexpectedly non-component instance import in interface")
837                    };
838                    let import_ty = &self.types[*instance];
839                    let iface = &self.resolve.interfaces[*id];
840                    for (ty_name, ty) in &iface.types {
841                        match &import_ty.exports.get(ty_name) {
842                            None => {}
843                            Some(ComponentExtern {
844                                ty: TypeDef::Resource(resource_table_idx),
845                                ..
846                            }) => {
847                                let ty = crate::dealias(self.resolve, *ty);
848                                let resource_table_ty = &self.types[*resource_table_idx];
849                                let concrete_ty = resource_table_ty.unwrap_concrete_ty();
850                                self.imports_resource_types.insert(ty, concrete_ty);
851                                self.imports_resource_index_types.insert(concrete_ty, ty);
852                            }
853                            Some(ComponentExtern {
854                                ty: TypeDef::Interface(_),
855                                ..
856                            }) => {}
857                            Some(_) => unreachable!("unexpected type in interface"),
858                        }
859                    }
860                }
861                WorldItem::Function(_) => {}
862                WorldItem::Type { id, .. } => match import {
863                    ComponentExtern {
864                        ty: TypeDef::Resource(resource),
865                        ..
866                    } => {
867                        let ty = crate::dealias(self.resolve, *id);
868                        let resource_table_ty = &self.types[*resource];
869                        let concrete_ty = resource_table_ty.unwrap_concrete_ty();
870                        self.imports_resource_types.insert(ty, concrete_ty);
871                        self.imports_resource_index_types.insert(concrete_ty, ty);
872                    }
873                    ComponentExtern {
874                        ty: TypeDef::Interface(_),
875                        ..
876                    } => {}
877                    _ => unreachable!("unexpected type in import world item"),
878                },
879            }
880        }
881        self.exports_resource_types = self.imports_resource_types.clone();
882        self.exports_resource_index_types = self.imports_resource_index_types.clone();
883
884        for (key, item) in &self.resolve.worlds[self.world].exports {
885            let name = &self.resolve.name_world_key(key);
886            let (_, (export_idx, _extern_data)) = self
887                .component
888                .exports
889                .raw_iter()
890                .find(|(expt_name, _)| ***expt_name == **name)
891                .unwrap();
892            let export = &self.component.export_items[*export_idx];
893            match item {
894                WorldItem::Interface { id, .. } => {
895                    let iface = &self.resolve.interfaces[*id];
896                    let Export::Instance { exports, .. } = &export else {
897                        unreachable!("unexpectedly non export instance item")
898                    };
899                    for (ty_name, ty) in &iface.types {
900                        let (export_idx, _exern_data) =
901                            exports.get(ty_name, &NameMapNoIntern).unwrap();
902                        match self.component.export_items[*export_idx] {
903                            Export::Type(TypeDef::Resource(resource)) => {
904                                let ty = crate::dealias(self.resolve, *ty);
905                                let resource_table_ty = &self.types[resource];
906                                let concrete_ty = resource_table_ty.unwrap_concrete_ty();
907                                self.exports_resource_types.insert(ty, concrete_ty);
908                                self.exports_resource_index_types.insert(concrete_ty, ty);
909                            }
910                            Export::Type(_) => {}
911                            _ => unreachable!(
912                                "unexpected type in component export items on iface [{iface_name}]",
913                                iface_name = iface.name.as_deref().unwrap_or("<unknown>"),
914                            ),
915                        }
916                    }
917                }
918                WorldItem::Function(_) => {}
919                WorldItem::Type { .. } => unreachable!("unexpected exported world item type"),
920            }
921        }
922    }
923
924    fn instantiate(&mut self) {
925        // Handle all built in trampolines
926        for (i, trampoline) in self.translation.trampolines.iter() {
927            let Trampoline::LowerImport {
928                index,
929                lower_ty,
930                options,
931            } = trampoline
932            else {
933                continue;
934            };
935
936            let options = self
937                .component
938                .options
939                .get(*options)
940                .expect("failed to find canon options");
941
942            let i = self.lowering_options.push((options, i, *lower_ty));
943            assert_eq!(i, *index);
944        }
945
946        if let Some(InstantiationMode::Async) = self.bindgen.opts.instantiation_mode {
947            // To avoid uncaught promise rejection errors, we attach an intermediate
948            // Promise.all with a rejection handler, if there are multiple promises.
949            if self.modules.len() > 1 {
950                self.src.js_init.push_str("Promise.all([");
951                for i in 0..self.modules.len() {
952                    if i > 0 {
953                        self.src.js_init.push_str(", ");
954                    }
955                    self.src.js_init.push_str(&format!("module{i}"));
956                }
957                uwriteln!(self.src.js_init, "]).catch(() => {{}});");
958            }
959        }
960
961        // Set up global stream map, which is used by intrinsics like stream.transfer.
962        // Register the intrinsic so the `const STREAM_TABLES = {};` declaration
963        // is emitted before these per-table assignments — without that, the
964        // generated module references an undeclared identifier and fails to
965        // load (ReferenceError: STREAM_TABLES is not defined).
966        if !self.stream_tables.is_empty() {
967            let global_stream_table_map = self.bindgen.intrinsic(Intrinsic::AsyncStream(
968                AsyncStreamIntrinsic::GlobalStreamTableMap,
969            ));
970            let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
971            for (table_idx, component_idx) in self.stream_tables.iter() {
972                self.src.js.push_str(&format!(
973                    "{global_stream_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
974                    table_idx.as_u32(),
975                    component_idx.as_u32(),
976                ));
977            }
978        }
979
980        // Set up global future map, which is used by intrinsics like future.transfer.
981        // Same registration fix as above for FUTURE_TABLES.
982        if !self.future_tables.is_empty() {
983            let global_future_table_map = self.bindgen.intrinsic(Intrinsic::AsyncFuture(
984                AsyncFutureIntrinsic::GlobalFutureTableMap,
985            ));
986            let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
987            for (table_idx, component_idx) in self.future_tables.iter() {
988                self.src.js.push_str(&format!(
989                    "{global_future_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
990                    table_idx.as_u32(),
991                    component_idx.as_u32(),
992                ));
993            }
994        }
995
996        // Set up global error context map, which is used by intrinsics like err_ctx.transfer.
997        // Same registration fix as above for ERR_CTX_TABLES.
998        if !self.err_ctx_tables.is_empty() {
999            let global_err_ctx_table_map = self
1000                .bindgen
1001                .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::GlobalErrCtxTableMap));
1002            let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
1003            for (table_idx, component_idx) in self.err_ctx_tables.iter() {
1004                self.src.js.push_str(&format!(
1005                    "{global_err_ctx_table_map}[{}] = {{ componentIdx: {}, table: new {rep_table_class}() }};\n",
1006                    table_idx.as_u32(),
1007                    component_idx.as_u32(),
1008                ));
1009            }
1010        }
1011
1012        // Process global initializers
1013        //
1014        // The order of initialization is unfortunately quite fragile.
1015        //
1016        // We take care in processing module instantiations because we must ensure that
1017        // $wit-component.fixups must be instantiated directly after $wit-component.shim
1018        //
1019        let mut lower_import_initializers = Vec::new();
1020
1021        // Process first n lower import initializers until the first instantiate module initializer
1022        for init in self.component.initializers.iter() {
1023            match init {
1024                GlobalInitializer::InstantiateModule(_m, _maybe_idx) => {
1025                    // Ensure lower import initializers are processed before the first module instantiation
1026                    for lower_import_init in lower_import_initializers.drain(..) {
1027                        self.instantiation_global_initializer(lower_import_init);
1028                    }
1029                }
1030
1031                // We push lower import initializers down to right before instantiate, so that the
1032                // memory, realloc and postReturn functions are available to the import lowerings
1033                // for optimized bindgen
1034                GlobalInitializer::LowerImport { .. } => {
1035                    lower_import_initializers.push(init);
1036                    continue;
1037                }
1038                _ => {}
1039            }
1040
1041            self.instantiation_global_initializer(init);
1042        }
1043
1044        // Process lower import initializers that were discovered after the last module instantiation
1045        for init in lower_import_initializers.drain(..) {
1046            self.instantiation_global_initializer(init);
1047        }
1048
1049        // Process imports and build mappings
1050        self.process_imports();
1051
1052        // Process exports and build mappings
1053        self.process_exports();
1054
1055        // Some trampolines that correspond to host-provided imports need to be defined before the
1056        // instantiation bits since they are referred to.
1057        for (i, trampoline) in self
1058            .translation
1059            .trampolines
1060            .iter()
1061            .filter(|(_, t)| Instantiator::is_early_trampoline(t))
1062        {
1063            self.trampoline(i, trampoline);
1064        }
1065
1066        self.wrap_initialization_in_context_tasks();
1067
1068        if self.bindgen.opts.instantiation_mode.is_some() {
1069            let js_init = mem::take(&mut self.src.js_init);
1070            self.src.js.push_str(&js_init);
1071        }
1072
1073        // Trampolines here so we have static module indices, and resource maps populated
1074        // (both imports and exports may still be populting resource map)
1075        for (i, trampoline) in self
1076            .translation
1077            .trampolines
1078            .iter()
1079            .filter(|(_, t)| !Instantiator::is_early_trampoline(t))
1080        {
1081            self.trampoline(i, trampoline);
1082        }
1083    }
1084
1085    fn wrap_initialization_in_context_tasks(&mut self) {
1086        let component_indices = self
1087            .context_components
1088            .borrow()
1089            .iter()
1090            .copied()
1091            .collect::<Vec<_>>();
1092        if component_indices.is_empty() {
1093            return;
1094        }
1095
1096        let create_task = self.bindgen.intrinsic(Intrinsic::AsyncTask(
1097            AsyncTaskIntrinsic::CreateNewCurrentTask,
1098        ));
1099        let clear_task = self
1100            .bindgen
1101            .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::ClearCurrentTask));
1102        let set_task_meta = self
1103            .bindgen
1104            .intrinsic(Intrinsic::SetGlobalCurrentTaskMetaFn);
1105        let clear_task_meta = self
1106            .bindgen
1107            .intrinsic(Intrinsic::ClearGlobalCurrentTaskMetaFn);
1108
1109        let mut setup = source::Source::default();
1110        for component_idx in &component_indices {
1111            uwriteln!(setup, "let _initTaskID{};", component_idx.as_u32());
1112        }
1113        uwriteln!(setup, "try {{");
1114        for component_idx in &component_indices {
1115            let component_idx = component_idx.as_u32();
1116            uwriteln!(
1117                setup,
1118                r#"
1119                  [, _initTaskID{component_idx}] = {create_task}({{
1120                      componentIdx: {component_idx},
1121                      isAsync: false,
1122                      callingWasmExport: true,
1123                      entryFnName: '<initialize>',
1124                  }});
1125                  {set_task_meta}({{ componentIdx: {component_idx}, taskID: _initTaskID{component_idx} }});
1126                "#,
1127            );
1128        }
1129        self.src.js_init.prepend_str(&setup);
1130
1131        uwriteln!(self.src.js_init, "}} finally {{");
1132        for component_idx in component_indices.iter().rev() {
1133            let component_idx = component_idx.as_u32();
1134            uwriteln!(
1135                self.src.js_init,
1136                r#"
1137                  {clear_task_meta}({{ componentIdx: {component_idx}, taskID: _initTaskID{component_idx} }});
1138                  {clear_task}({component_idx}, _initTaskID{component_idx});
1139                "#,
1140            );
1141        }
1142        uwriteln!(self.src.js_init, "}}");
1143    }
1144
1145    fn ensure_local_resource_class(&mut self, local_name: String) {
1146        if !self.defined_resource_classes.contains(&local_name) {
1147            uwriteln!(
1148                self.src.js,
1149                "\nclass {local_name} {{
1150                constructor () {{
1151                    throw new Error('\"{local_name}\" resource does not define a constructor');
1152                }}
1153            }}"
1154            );
1155            self.defined_resource_classes.insert(local_name.to_string());
1156        }
1157    }
1158
1159    fn resource_definitions(&mut self) {
1160        // It is theoretically possible for locally defined resources used in no functions
1161        // to still be exported
1162        for resource in 0..self.component.num_resources {
1163            let resource = ResourceIndex::from_u32(resource);
1164            let is_imported = self.component.defined_resource_index(resource).is_none();
1165            if is_imported {
1166                continue;
1167            }
1168            if let Some(local_name) = self.bindgen.local_names.try_get(resource) {
1169                self.ensure_local_resource_class(local_name.to_string());
1170            }
1171        }
1172
1173        // TODO(feat): In the past, we could eagerly build a mapping of resources defined to the tables they correspond to
1174        // to make runtime checks of which table a resource must have been created into first (i.e. the component that implements
1175        // creation of a given resource) a particular resource faster.
1176        //
1177        // This logic was based on component.num_resources and was broken for composed components --
1178        // wasmtime-environ reported a smaller number of resources, and the check was geared towards a *single* component,
1179        // not tying a particular component to a particular table (it is possible for *sub components* to originate different
1180        // resources).
1181        //
1182        // In theory, it should be posible to build this knowledge statically rather than at resource creation,
1183        // so in the future we should attempt to rebulid that code, if possible.
1184        //
1185        // Note that at runtime wasmtime maintains this information and looks it up during a transfer operation, see:
1186        //   - https://github.com/bytecodealliance/wasmtime/blob/5f3b67ea055857020bd1ac1f2c3f7fa2e6c31ec0/crates/wasmtime/src/runtime/component/instance.rs#L424
1187        //   - https://github.com/bytecodealliance/wasmtime/blob/9c49989a2e71382fd8639288088472f150f2f534/crates/wasmtime/src/runtime/vm/component.rs#L847
1188    }
1189
1190    /// Ensure a component-local `error-context` table has been created
1191    ///
1192    /// # Arguments
1193    ///
1194    /// * `component_idx` - component index
1195    /// * `err_ctx_tbl_idx` - The component-local error-context table index
1196    ///
1197    fn ensure_error_context_local_table(
1198        &mut self,
1199        component_idx: RuntimeComponentInstanceIndex,
1200        err_ctx_tbl_idx: TypeComponentLocalErrorContextTableIndex,
1201    ) {
1202        if self.error_context_component_initialized[component_idx]
1203            && self.error_context_component_table_initialized[err_ctx_tbl_idx]
1204        {
1205            return;
1206        }
1207        let err_ctx_local_tables = self
1208            .bindgen
1209            .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ComponentLocalTable));
1210        let rep_table_class = self.bindgen.intrinsic(Intrinsic::RepTableClass);
1211        let c = component_idx.as_u32();
1212        if !self.error_context_component_initialized[component_idx] {
1213            uwriteln!(self.src.js, "{err_ctx_local_tables}.set({c}, new Map());");
1214            self.error_context_component_initialized[component_idx] = true;
1215        }
1216        if !self.error_context_component_table_initialized[err_ctx_tbl_idx] {
1217            let t = err_ctx_tbl_idx.as_u32();
1218            uwriteln!(
1219                self.src.js,
1220                "{err_ctx_local_tables}.get({c}).set({t}, new {rep_table_class}({{ target: `component [{c}] local error ctx table [{t}]` }}));"
1221            );
1222            self.error_context_component_table_initialized[err_ctx_tbl_idx] = true;
1223        }
1224    }
1225
1226    /// Ensure that a resource table has been initialized
1227    ///
1228    /// For the relevant resource table, this function will generate initialization
1229    /// blocks, exactly once.
1230    ///
1231    /// This is not done for *all* resources, but instead for those that are explicitly used.
1232    fn ensure_resource_table(&mut self, resource_table_idx: TypeResourceTableIndex) {
1233        if self
1234            .resource_tables_initialized
1235            .contains_key(&resource_table_idx)
1236        {
1237            return;
1238        }
1239
1240        let resource_table_ty = &self.types[resource_table_idx];
1241        let resource_idx = resource_table_ty.unwrap_concrete_ty();
1242        let component_idx = resource_table_ty.unwrap_concrete_instance().as_u32();
1243
1244        let (is_imported, maybe_dtor) = if let Some(resource_idx) =
1245            self.component.defined_resource_index(resource_idx)
1246        {
1247            let resource_def = self
1248                .component
1249                .initializers
1250                .iter()
1251                .find_map(|i| match i {
1252                    GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
1253                    _ => None,
1254                })
1255                .unwrap();
1256
1257            if let Some(dtor) = &resource_def.dtor {
1258                let dtor = self.core_def(dtor);
1259                let maybe_dtor = if self
1260                    .context_components
1261                    .borrow()
1262                    .contains(&resource_table_ty.unwrap_concrete_instance())
1263                {
1264                    let call_resource_destructor = self.bindgen.intrinsic(Intrinsic::Resource(
1265                        ResourceIntrinsic::ResourceDestructorCall,
1266                    ));
1267                    format!(
1268                        "\n{call_resource_destructor}({{ componentIdx: {component_idx}, dtor: {}, rep }});",
1269                        dtor,
1270                    )
1271                } else {
1272                    format!("\n{dtor}(rep);")
1273                };
1274                (false, maybe_dtor)
1275            } else {
1276                (false, "".into())
1277            }
1278        } else {
1279            (true, "".into())
1280        };
1281
1282        let handle_tables = self.bindgen.intrinsic(Intrinsic::HandleTables);
1283        let rsc_table_flag = self
1284            .bindgen
1285            .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
1286        let rsc_table_remove = self
1287            .bindgen
1288            .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
1289
1290        // Create the relevant handle table
1291        let rtid = resource_table_idx.as_u32();
1292        if is_imported {
1293            // imported
1294            uwriteln!(
1295                self.src.js,
1296                r#"
1297                  const handleTable{rtid} = [{rsc_table_flag}, 0];
1298                  handleTable{rtid}._createdReps = new Set();
1299                "#,
1300            );
1301            if !self.resources_initialized.contains_key(&resource_idx) {
1302                let ridx = resource_idx.as_u32();
1303                uwriteln!(
1304                    self.src.js,
1305                    r#"
1306                      const captureTable{ridx} = new Map();
1307                      let captureCnt{ridx} = 0;
1308                    "#
1309                );
1310                self.resources_initialized.insert(resource_idx, true);
1311            }
1312        } else {
1313            // non imported
1314            let finalization_registry_create = self
1315                .bindgen
1316                .intrinsic(Intrinsic::FinalizationRegistryCreate);
1317            uwriteln!(
1318                self.src.js,
1319                r#"
1320                   const handleTable{rtid} = [{rsc_table_flag}, 0];
1321                   handleTable{rtid}._createdReps = new Set();
1322                   const finalizationRegistry{rtid} = {finalization_registry_create}((handle) => {{
1323                       const {{ rep }} = {rsc_table_remove}(handleTable{rtid}, handle);{maybe_dtor}
1324                   }});
1325                "#,
1326            );
1327        }
1328
1329        // Add the handle table to the global list
1330        uwriteln!(self.src.js, "{handle_tables}[{rtid}] = handleTable{rtid};");
1331        self.resource_tables_initialized
1332            .insert(resource_table_idx, true);
1333    }
1334
1335    fn instance_flags(&mut self) {
1336        let used_instance_flags = self
1337            .used_instance_flags
1338            .borrow()
1339            .iter()
1340            .copied()
1341            .collect::<Vec<_>>();
1342        if used_instance_flags.is_empty() {
1343            return;
1344        }
1345
1346        let instance_flags_map = self.bindgen.intrinsic(Intrinsic::Component(
1347            ComponentIntrinsic::GlobalInstanceFlagsMap,
1348        ));
1349        let mut instance_flag_defs = String::new();
1350        for used in used_instance_flags {
1351            let i = used.as_u32();
1352            // As of wasmtime-environ 47 the per-instance flags global holds a
1353            // single boolean `may_leave` flag, so initialize it to `1`.
1354            uwriteln!(
1355                &mut instance_flag_defs,
1356                "const instanceFlags{i} = new WebAssembly.Global({{ value: \"i32\", mutable: true }}, 1);",
1357            );
1358            uwriteln!(
1359                &mut instance_flag_defs,
1360                "{instance_flags_map}.set({i}, instanceFlags{i});",
1361            );
1362        }
1363        self.src.js_init.prepend_str(&instance_flag_defs);
1364    }
1365
1366    /// Return the component instance whose canonical ABI `may_leave` flag a
1367    /// guest-callable trampoline must check.
1368    fn trampoline_may_leave_instance(
1369        &self,
1370        trampoline: &Trampoline,
1371    ) -> Option<RuntimeComponentInstanceIndex> {
1372        let instance = match trampoline {
1373            Trampoline::ResourceRep { .. }
1374            | Trampoline::ThreadIndex
1375            | Trampoline::BackpressureInc { .. }
1376            | Trampoline::BackpressureDec { .. }
1377            | Trampoline::ResourceTransferOwn
1378            | Trampoline::ResourceTransferBorrow
1379            | Trampoline::PrepareCall { .. }
1380            | Trampoline::SyncStartCall { .. }
1381            | Trampoline::AsyncStartCall { .. }
1382            | Trampoline::FutureTransfer
1383            | Trampoline::StreamTransfer
1384            | Trampoline::ErrorContextTransfer
1385            | Trampoline::Trap
1386            | Trampoline::EnterSyncCall
1387            | Trampoline::ExitSyncCall
1388            | Trampoline::Transcoder { .. } => return None,
1389
1390            Trampoline::LowerImport { options, .. } => {
1391                self.component
1392                    .options
1393                    .get(*options)
1394                    .expect("failed to find lower import options")
1395                    .instance
1396            }
1397
1398            Trampoline::ResourceNew { instance, .. }
1399            | Trampoline::ResourceDrop { instance, .. }
1400            | Trampoline::TaskReturn { instance, .. }
1401            | Trampoline::TaskCancel { instance }
1402            | Trampoline::WaitableSetNew { instance }
1403            | Trampoline::WaitableSetWait { instance, .. }
1404            | Trampoline::WaitableSetPoll { instance, .. }
1405            | Trampoline::WaitableSetDrop { instance }
1406            | Trampoline::WaitableJoin { instance }
1407            | Trampoline::ThreadYield { instance, .. }
1408            | Trampoline::ThreadNewIndirect { instance, .. }
1409            | Trampoline::ThreadSuspend { instance, .. }
1410            | Trampoline::ThreadSuspendToSuspended { instance, .. }
1411            | Trampoline::ThreadSuspendTo { instance, .. }
1412            | Trampoline::ThreadUnsuspend { instance, .. }
1413            | Trampoline::ThreadYieldToSuspended { instance, .. }
1414            | Trampoline::SubtaskDrop { instance }
1415            | Trampoline::SubtaskCancel { instance, .. }
1416            | Trampoline::ErrorContextNew { instance, .. }
1417            | Trampoline::ErrorContextDebugMessage { instance, .. }
1418            | Trampoline::ErrorContextDrop { instance, .. }
1419            | Trampoline::StreamNew { instance, .. }
1420            | Trampoline::StreamRead { instance, .. }
1421            | Trampoline::StreamWrite { instance, .. }
1422            | Trampoline::StreamCancelRead { instance, .. }
1423            | Trampoline::StreamCancelWrite { instance, .. }
1424            | Trampoline::StreamDropReadable { instance, .. }
1425            | Trampoline::StreamDropWritable { instance, .. }
1426            | Trampoline::FutureNew { instance, .. }
1427            | Trampoline::FutureRead { instance, .. }
1428            | Trampoline::FutureWrite { instance, .. }
1429            | Trampoline::FutureCancelRead { instance, .. }
1430            | Trampoline::FutureCancelWrite { instance, .. }
1431            | Trampoline::FutureDropReadable { instance, .. }
1432            | Trampoline::FutureDropWritable { instance, .. } => *instance,
1433        };
1434        Some(instance)
1435    }
1436
1437    /// These trampolines check `may_leave` inside their JSPI-compatible
1438    /// wrapper (or, for lower imports, inside the lowering helper itself).
1439    fn trampoline_checks_may_leave_internally(trampoline: &Trampoline) -> bool {
1440        matches!(
1441            trampoline,
1442            Trampoline::LowerImport { .. }
1443                | Trampoline::SubtaskCancel { .. }
1444                | Trampoline::WaitableSetWait { .. }
1445                | Trampoline::StreamRead { .. }
1446                | Trampoline::StreamWrite { .. }
1447                | Trampoline::StreamCancelRead { .. }
1448                | Trampoline::StreamCancelWrite { .. }
1449                | Trampoline::FutureRead { .. }
1450                | Trampoline::FutureWrite { .. }
1451                | Trampoline::FutureCancelRead { .. }
1452                | Trampoline::FutureCancelWrite { .. }
1453                | Trampoline::FutureDropReadable { .. }
1454                | Trampoline::FutureDropWritable { .. }
1455                | Trampoline::ThreadYield { .. }
1456        )
1457    }
1458
1459    // Trampolines defined in is_early_trampoline() below that use:
1460    //   const trampoline{} = ...
1461    // require early initialization since their bindings aren't auto-hoisted
1462    // like JS functions are in the JS runtime.
1463    fn is_early_trampoline(trampoline: &Trampoline) -> bool {
1464        matches!(
1465            trampoline,
1466            Trampoline::AsyncStartCall { .. }
1467                | Trampoline::BackpressureDec { .. }
1468                | Trampoline::BackpressureInc { .. }
1469                | Trampoline::EnterSyncCall
1470                | Trampoline::ErrorContextDebugMessage { .. }
1471                | Trampoline::ErrorContextDrop { .. }
1472                | Trampoline::ErrorContextNew { .. }
1473                | Trampoline::ErrorContextTransfer
1474                | Trampoline::ExitSyncCall
1475                | Trampoline::FutureCancelRead { .. }
1476                | Trampoline::FutureCancelWrite { .. }
1477                | Trampoline::FutureDropReadable { .. }
1478                | Trampoline::FutureDropWritable { .. }
1479                | Trampoline::FutureNew { .. }
1480                | Trampoline::FutureRead { .. }
1481                | Trampoline::FutureTransfer
1482                | Trampoline::FutureWrite { .. }
1483                | Trampoline::LowerImport { .. }
1484                | Trampoline::PrepareCall { .. }
1485                | Trampoline::ResourceDrop { .. }
1486                | Trampoline::ResourceNew { .. }
1487                | Trampoline::ResourceRep { .. }
1488                | Trampoline::ResourceTransferBorrow
1489                | Trampoline::ResourceTransferOwn
1490                | Trampoline::StreamCancelRead { .. }
1491                | Trampoline::StreamCancelWrite { .. }
1492                | Trampoline::StreamDropReadable { .. }
1493                | Trampoline::StreamDropWritable { .. }
1494                | Trampoline::StreamNew { .. }
1495                | Trampoline::StreamRead { .. }
1496                | Trampoline::StreamTransfer
1497                | Trampoline::StreamWrite { .. }
1498                | Trampoline::SubtaskCancel { .. }
1499                | Trampoline::SubtaskDrop { .. }
1500                | Trampoline::SyncStartCall { .. }
1501                | Trampoline::TaskCancel { .. }
1502                | Trampoline::TaskReturn { .. }
1503                | Trampoline::ThreadYield { .. }
1504                | Trampoline::ThreadYieldToSuspended { .. }
1505                | Trampoline::WaitableJoin { .. }
1506                | Trampoline::WaitableSetDrop { .. }
1507                | Trampoline::WaitableSetNew { .. }
1508                | Trampoline::WaitableSetPoll { .. }
1509                | Trampoline::WaitableSetWait { .. }
1510        )
1511    }
1512
1513    fn trampoline(&mut self, i: TrampolineIndex, trampoline: &'a Trampoline) {
1514        let i = i.as_u32();
1515        match trampoline {
1516            Trampoline::TaskCancel { instance } => {
1517                let task_cancel_fn = self
1518                    .bindgen
1519                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::TaskCancel));
1520                uwriteln!(
1521                    self.src.js,
1522                    "const trampoline{i} = {task_cancel_fn}.bind(null, {instance_idx});\n",
1523                    instance_idx = instance.as_u32(),
1524                );
1525            }
1526
1527            Trampoline::SubtaskCancel { instance, async_ } => {
1528                let subtask_cancel_fn = self
1529                    .bindgen
1530                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::SubtaskCancel));
1531                let suspending_wrap_fn =
1532                    self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
1533                // NOTE: core wasm passes the subtask handle as the remaining argument.
1534                // The intrinsic is async (a sync-lowered cancel may need to block until
1535                // the subtask resolves), so it must be JSPI-wrapped.
1536                uwriteln!(
1537                    self.src.js,
1538                    "const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({instance_idx}, {subtask_cancel_fn}.bind(null, {instance_idx}, {async_})));\n",
1539                    instance_idx = instance.as_u32(),
1540                );
1541            }
1542
1543            Trampoline::SubtaskDrop { instance } => {
1544                let component_idx = instance.as_u32();
1545                let subtask_drop_fn = self
1546                    .bindgen
1547                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::SubtaskDrop));
1548                uwriteln!(
1549                    self.src.js,
1550                    "const trampoline{i} = {subtask_drop_fn}.bind(
1551                         null,
1552                         {component_idx},
1553                     );"
1554                );
1555            }
1556
1557            Trampoline::WaitableSetNew { instance } => {
1558                let waitable_set_new_fn = self
1559                    .bindgen
1560                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetNew));
1561                uwriteln!(
1562                    self.src.js,
1563                    "const trampoline{i} = {waitable_set_new_fn}.bind(null, {});\n",
1564                    instance.as_u32(),
1565                );
1566            }
1567
1568            Trampoline::WaitableSetWait { instance, options } => {
1569                let options = self
1570                    .component
1571                    .options
1572                    .get(*options)
1573                    .expect("failed to find options");
1574                assert_eq!(
1575                    instance.as_u32(),
1576                    options.instance.as_u32(),
1577                    "options index instance must match trampoline"
1578                );
1579
1580                let CanonicalOptions {
1581                    instance,
1582                    async_,
1583                    data_model:
1584                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
1585                    ..
1586                } = options
1587                else {
1588                    panic!("unexpected/missing memory data model during waitable-set.wait");
1589                };
1590
1591                let instance_idx = instance.as_u32();
1592                let memory_idx = memory
1593                    .expect("missing memory idx for waitable-set.wait")
1594                    .as_u32();
1595                let waitable_set_wait_fn = self
1596                    .bindgen
1597                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetWait));
1598                let suspending_wrap_fn =
1599                    self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
1600
1601                uwriteln!(
1602                    self.src.js,
1603                    r#"
1604                    const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({instance_idx}, {waitable_set_wait_fn}.bind(null, {{
1605                        componentIdx: {instance_idx},
1606                        isAsync: {async_},
1607                        memoryIdx: {memory_idx},
1608                        getMemoryFn: () => memory{memory_idx},
1609                    }})));
1610                    "#,
1611                );
1612            }
1613
1614            Trampoline::WaitableSetPoll { options, .. } => {
1615                let CanonicalOptions {
1616                    instance,
1617                    async_,
1618                    data_model:
1619                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
1620                    cancellable,
1621                    ..
1622                } = self
1623                    .component
1624                    .options
1625                    .get(*options)
1626                    .expect("failed to find options")
1627                else {
1628                    panic!("unexpected memory data model during waitable-set.poll");
1629                };
1630
1631                let instance_idx = instance.as_u32();
1632                let memory_idx = memory
1633                    .expect("missing memory idx for waitable-set.poll")
1634                    .as_u32();
1635                let waitable_set_poll_fn = self
1636                    .bindgen
1637                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetPoll));
1638
1639                uwriteln!(
1640                    self.src.js,
1641                    r#"
1642                    const trampoline{i} = {waitable_set_poll_fn}.bind(
1643                        null,
1644                        {{
1645                            componentIdx: {instance_idx},
1646                            isAsync: {async_},
1647                            isCancellable: {cancellable},
1648                            memoryIdx: {memory_idx},
1649                            getMemoryFn: () => memory{memory_idx},
1650                        }}
1651                    );
1652                    "#,
1653                );
1654            }
1655
1656            Trampoline::WaitableSetDrop { instance } => {
1657                let waitable_set_drop_fn = self
1658                    .bindgen
1659                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableSetDrop));
1660                uwriteln!(
1661                    self.src.js,
1662                    "const trampoline{i} = {waitable_set_drop_fn}.bind(null, {instance_idx});\n",
1663                    instance_idx = instance.as_u32(),
1664                );
1665            }
1666
1667            Trampoline::WaitableJoin { instance } => {
1668                let waitable_join_fn = self
1669                    .bindgen
1670                    .intrinsic(Intrinsic::Waitable(WaitableIntrinsic::WaitableJoin));
1671                uwriteln!(
1672                    self.src.js,
1673                    "const trampoline{i} = {waitable_join_fn}.bind(null, {instance_idx});\n",
1674                    instance_idx = instance.as_u32(),
1675                );
1676            }
1677
1678            Trampoline::StreamNew { ty, instance } => {
1679                let stream_new_fn = self
1680                    .bindgen
1681                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamNew));
1682                let instance_idx = instance.as_u32();
1683                let stream_table_idx = ty.as_u32();
1684
1685                // Get to the payload type for the given stream table idx
1686                let table_ty = &self.types[*ty];
1687                let stream_ty_idx = table_ty.ty;
1688                let stream_ty = &self.types[stream_ty_idx];
1689
1690                // TODO(???): do we have no way to go from interface type to in-component type idx?
1691                // TODO(???): does this work under type aliases?? we need the type def?
1692                // TODO(???): can the stream type be treated as a unique indicator of the payload type? maybe not?
1693                // need a way to go from iface type + stream type -> payload type idx?
1694                let payload_ty_name_js = stream_ty
1695                    .payload
1696                    .map(|iface_ty| format!("'{iface_ty:?}'"))
1697                    .unwrap_or_else(|| "null".into());
1698
1699                // Gather type metadata
1700                let (
1701                    align_32_js,
1702                    size_32_js,
1703                    flat_count_js,
1704                    lift_fn_js,
1705                    lower_fn_js,
1706                    is_none_js,
1707                    is_numeric_type_js,
1708                    is_borrow_js,
1709                    is_async_value_js,
1710                    typed_array_js,
1711                ) = match stream_ty.payload {
1712                    // If there is no payload for the stream, we know the values
1713                    None => (
1714                        "0".into(),
1715                        "0".into(),
1716                        "0".into(),
1717                        "null".into(),
1718                        "null".into(),
1719                        "true",
1720                        "false".into(),
1721                        "false".into(),
1722                        "false".into(),
1723                        "undefined",
1724                    ),
1725                    // If there is a payload, generate relevant lift/lower and other metadata
1726                    Some(ty) => (
1727                        self.types.canonical_abi(&ty).align32.to_string(),
1728                        self.types.canonical_abi(&ty).size32.to_string(),
1729                        self.types
1730                            .canonical_abi(&ty)
1731                            .flat_count
1732                            .map(|v| v.to_string())
1733                            .unwrap_or_else(|| "null".into()),
1734                        gen_flat_lift_fn_js_expr(self, &ty, &None),
1735                        gen_flat_lower_fn_js_expr(self, &ty, &None),
1736                        "false",
1737                        format!(
1738                            "{}",
1739                            matches!(
1740                                ty,
1741                                InterfaceType::U8
1742                                    | InterfaceType::U16
1743                                    | InterfaceType::U32
1744                                    | InterfaceType::U64
1745                                    | InterfaceType::S8
1746                                    | InterfaceType::S16
1747                                    | InterfaceType::S32
1748                                    | InterfaceType::S64
1749                                    | InterfaceType::Float32
1750                                    | InterfaceType::Float64
1751                            )
1752                        ),
1753                        format!("{}", matches!(ty, InterfaceType::Borrow(_))),
1754                        format!(
1755                            "{}",
1756                            matches!(ty, InterfaceType::Stream(_) | InterfaceType::Future(_))
1757                        ),
1758                        js_typed_array_ctor(&ty).unwrap_or("undefined"),
1759                    ),
1760                };
1761
1762                uwriteln!(
1763                    self.src.js,
1764                    "const trampoline{i} = {stream_new_fn}.bind(null, {{
1765                        streamTableIdx: {stream_table_idx},
1766                        callerComponentIdx: {instance_idx},
1767                        elemMeta: {{
1768                            liftFn: {lift_fn_js},
1769                            lowerFn: {lower_fn_js},
1770                            payloadTypeName: {payload_ty_name_js},
1771                            isNone: {is_none_js},
1772                            isNumeric: {is_numeric_type_js},
1773                            isBorrowed: {is_borrow_js},
1774                            isAsyncValue: {is_async_value_js},
1775                            typedArray: {typed_array_js},
1776                            flatCount: {flat_count_js},
1777                            align32: {align_32_js},
1778                            size32: {size_32_js},
1779                        }},
1780                    }});\n",
1781                );
1782            }
1783
1784            Trampoline::StreamRead {
1785                instance,
1786                ty,
1787                options,
1788            } => {
1789                let options = self
1790                    .component
1791                    .options
1792                    .get(*options)
1793                    .expect("failed to find options");
1794                assert_eq!(
1795                    instance.as_u32(),
1796                    options.instance.as_u32(),
1797                    "options index instance must match trampoline"
1798                );
1799
1800                let CanonicalOptions {
1801                    instance,
1802                    string_encoding,
1803                    async_,
1804                    data_model:
1805                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
1806                    ..
1807                } = options
1808                else {
1809                    unreachable!("missing/invalid data model for options during stream.read")
1810                };
1811                let (memory_idx_js, get_memory_fn_js) = match memory {
1812                    Some(idx) => (
1813                        idx.as_u32().to_string(),
1814                        format!("() => memory{}", idx.as_u32()),
1815                    ),
1816                    None => ("undefined".into(), "undefined".into()),
1817                };
1818                let (realloc_idx, get_realloc_fn_js) = match realloc {
1819                    Some(v) => {
1820                        let v = v.as_u32().to_string();
1821                        (v.to_string(), format!("() => realloc{v}"))
1822                    }
1823                    None => ("undefined".into(), "undefined".into()),
1824                };
1825
1826                let component_instance_id = instance.as_u32();
1827                let string_encoding = string_encoding_js_literal(string_encoding);
1828                let stream_table_idx = ty.as_u32();
1829                let stream_read_fn = self
1830                    .bindgen
1831                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamRead));
1832
1833                // PrepareCall for an async call is sometimes missing memories,
1834                // so we augment and save here, knowing that any stream.write/read operation
1835                // that uses a memory is indicative of that component's memory
1836                //
1837                if let Some(memory_idx) = memory {
1838                    let memory_idx = memory_idx.as_u32();
1839                    let register_global_memory_for_component_fn = self
1840                        .bindgen
1841                        .intrinsic(Intrinsic::RegisterGlobalMemoryForComponent);
1842                    uwriteln!(
1843                        self.src.js_init,
1844                        r#"{register_global_memory_for_component_fn}({{
1845                             componentIdx: {component_instance_id},
1846                             memoryIdx: {memory_idx},
1847                             memory: memory{memory_idx},
1848                         }});"#
1849                    );
1850                }
1851
1852                uwriteln!(
1853                    self.src.js,
1854                    r#"const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_instance_id}, {stream_read_fn}.bind(
1855                         null,
1856                         {{
1857                             componentIdx: {component_instance_id},
1858                             memoryIdx: {memory_idx_js},
1859                             getMemoryFn: {get_memory_fn_js},
1860                             reallocIdx: {realloc_idx},
1861                             getReallocFn: {get_realloc_fn_js},
1862                             stringEncoding: {string_encoding},
1863                             isAsync: {async_},
1864                             streamTableIdx: {stream_table_idx},
1865                         }}
1866                     )));
1867                    "#,
1868                    suspending_wrap_fn =
1869                        self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
1870                );
1871            }
1872
1873            Trampoline::StreamWrite {
1874                instance,
1875                ty,
1876                options,
1877            } => {
1878                let options = self
1879                    .component
1880                    .options
1881                    .get(*options)
1882                    .expect("failed to find options");
1883                assert_eq!(
1884                    instance.as_u32(),
1885                    options.instance.as_u32(),
1886                    "options index instance must match trampoline"
1887                );
1888
1889                let CanonicalOptions {
1890                    instance,
1891                    string_encoding,
1892                    async_,
1893                    data_model:
1894                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
1895                    ..
1896                } = options
1897                else {
1898                    unreachable!("unexpected memory data model during stream.write");
1899                };
1900                let component_instance_id = instance.as_u32();
1901                let (memory_idx_js, get_memory_fn_js) = match memory {
1902                    Some(idx) => (
1903                        idx.as_u32().to_string(),
1904                        format!("() => memory{}", idx.as_u32()),
1905                    ),
1906                    None => ("undefined".into(), "undefined".into()),
1907                };
1908                let (realloc_idx, get_realloc_fn_js) = match realloc {
1909                    Some(v) => {
1910                        let v = v.as_u32().to_string();
1911                        (v.to_string(), format!("() => realloc{v}"))
1912                    }
1913                    None => ("undefined".into(), "undefined".into()),
1914                };
1915
1916                let string_encoding = string_encoding_js_literal(string_encoding);
1917                let stream_table_idx = ty.as_u32();
1918                let stream_write_fn = self
1919                    .bindgen
1920                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamWrite));
1921
1922                // PrepareCall for an async call is sometimes missing memories,
1923                // so we augment and save here, knowing that any stream.write/read operation
1924                // that uses a memory is indicative of that component's memory
1925                if let Some(memory_idx) = memory {
1926                    let memory_idx = memory_idx.as_u32();
1927                    let register_global_memory_for_component_fn = self
1928                        .bindgen
1929                        .intrinsic(Intrinsic::RegisterGlobalMemoryForComponent);
1930                    uwriteln!(
1931                        self.src.js_init,
1932                        r#"{register_global_memory_for_component_fn}({{
1933                             componentIdx: {component_instance_id},
1934                             memoryIdx: {memory_idx},
1935                             memory: memory{memory_idx},
1936                         }});"#
1937                    );
1938                }
1939
1940                uwriteln!(
1941                    self.src.js,
1942                    r#"
1943                     const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_instance_id}, {stream_write_fn}.bind(
1944                         null,
1945                         {{
1946                             componentIdx: {component_instance_id},
1947                             memoryIdx: {memory_idx_js},
1948                             getMemoryFn: {get_memory_fn_js},
1949                             reallocIdx: {realloc_idx},
1950                             getReallocFn: {get_realloc_fn_js},
1951                             stringEncoding: {string_encoding},
1952                             isAsync: {async_},
1953                             streamTableIdx: {stream_table_idx},
1954                         }}
1955                     )));
1956                    "#,
1957                    suspending_wrap_fn =
1958                        self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
1959                );
1960            }
1961
1962            Trampoline::StreamCancelRead {
1963                instance,
1964                ty,
1965                async_,
1966            }
1967            | Trampoline::StreamCancelWrite {
1968                instance,
1969                ty,
1970                async_,
1971            } => {
1972                let stream_cancel_fn = match trampoline {
1973                    Trampoline::StreamCancelRead { .. } => self.bindgen.intrinsic(
1974                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamCancelRead),
1975                    ),
1976                    Trampoline::StreamCancelWrite { .. } => self.bindgen.intrinsic(
1977                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamCancelWrite),
1978                    ),
1979                    _ => unreachable!("unexpected trampoline"),
1980                };
1981
1982                let stream_table_idx = ty.as_u32();
1983                let component_idx = instance.as_u32();
1984                uwriteln!(
1985                    self.src.js,
1986                    r#"
1987                      const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {stream_cancel_fn}.bind(null, {{
1988                          streamTableIdx: {stream_table_idx},
1989                          isAsync: {async_},
1990                          componentIdx: {component_idx},
1991                      }})));
1992                    "#,
1993                    suspending_wrap_fn =
1994                        self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
1995                );
1996            }
1997
1998            Trampoline::StreamDropReadable { ty, instance }
1999            | Trampoline::StreamDropWritable { ty, instance } => {
2000                let intrinsic_fn = match trampoline {
2001                    Trampoline::StreamDropReadable { .. } => self.bindgen.intrinsic(
2002                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamDropReadable),
2003                    ),
2004                    Trampoline::StreamDropWritable { .. } => self.bindgen.intrinsic(
2005                        Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamDropWritable),
2006                    ),
2007                    _ => unreachable!("unexpected trampoline"),
2008                };
2009                let stream_idx = ty.as_u32();
2010                let instance_idx = instance.as_u32();
2011                uwriteln!(
2012                    self.src.js,
2013                    "const trampoline{i} = {intrinsic_fn}.bind(null, {{
2014                        streamTableIdx: {stream_idx},
2015                        componentIdx: {instance_idx},
2016                    }});\n",
2017                );
2018            }
2019
2020            Trampoline::StreamTransfer => {
2021                let stream_transfer_fn = self
2022                    .bindgen
2023                    .intrinsic(Intrinsic::AsyncStream(AsyncStreamIntrinsic::StreamTransfer));
2024                uwriteln!(self.src.js, "const trampoline{i} = {stream_transfer_fn};\n",);
2025            }
2026
2027            Trampoline::FutureNew { instance, ty } => {
2028                let future_new_fn = self
2029                    .bindgen
2030                    .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureNew));
2031                let future_table_idx = ty.as_u32();
2032                let component_idx = instance.as_u32();
2033
2034                // Build element metadata
2035                let future_table_ty = &self.types[*ty];
2036                let future_ty = &self.types[future_table_ty.ty];
2037                let (
2038                    payload_size32,
2039                    payload_align32,
2040                    payload_flat_count_js,
2041                    payload_lift_fn_js,
2042                    payload_lower_fn_js,
2043                    is_borrowed,
2044                    is_none_type,
2045                    is_numeric_type,
2046                    is_async_value,
2047                ) = match future_ty.payload {
2048                    None => (
2049                        0,
2050                        0,
2051                        "0".into(),
2052                        "() => {{ throw new Error('empty future payload'); }}".into(),
2053                        "() => {{ throw new Error('empty future payload'); }}".into(),
2054                        false,
2055                        true,
2056                        false,
2057                        false,
2058                    ),
2059                    Some(payload_ty) => {
2060                        let cabi = self.types.canonical_abi(&payload_ty);
2061                        (
2062                            cabi.size32,
2063                            cabi.align32,
2064                            cabi.flat_count
2065                                .map(|v| format!("{v}"))
2066                                .unwrap_or_else(|| "null".into()),
2067                            gen_flat_lift_fn_js_expr(self, &payload_ty, &None),
2068                            gen_flat_lower_fn_js_expr(self, &payload_ty, &None),
2069                            matches!(payload_ty, InterfaceType::Borrow(_)),
2070                            false,
2071                            matches!(
2072                                payload_ty,
2073                                InterfaceType::U8
2074                                    | InterfaceType::U16
2075                                    | InterfaceType::U32
2076                                    | InterfaceType::U64
2077                                    | InterfaceType::S8
2078                                    | InterfaceType::S16
2079                                    | InterfaceType::S32
2080                                    | InterfaceType::S64
2081                                    | InterfaceType::Float32
2082                                    | InterfaceType::Float64
2083                            ),
2084                            matches!(
2085                                payload_ty,
2086                                InterfaceType::Stream(_) | InterfaceType::Future(_)
2087                            ),
2088                        )
2089                    }
2090                };
2091                let payload_ty_name_js = future_ty
2092                    .payload
2093                    .map(|iface_ty| format!("'{iface_ty:?}'"))
2094                    .unwrap_or_else(|| "null".into());
2095
2096                uwriteln!(
2097                    self.src.js,
2098                    r#"
2099                      const trampoline{i} = {future_new_fn}.bind(null, {{
2100                          componentIdx: {component_idx},
2101                          futureTableIdx: {future_table_idx},
2102                          elemMeta: {{
2103                              liftFn: {payload_lift_fn_js},
2104                              lowerFn: {payload_lower_fn_js},
2105                              payloadTypeName: {payload_ty_name_js},
2106                              isNone: {is_none_type},
2107                              isNumeric: {is_numeric_type},
2108                              isBorrowed: {is_borrowed},
2109                              isAsyncValue: {is_async_value},
2110                              flatCount: {payload_flat_count_js},
2111                              align32: {payload_align32},
2112                              size32: {payload_size32},
2113                          }},
2114                      }});
2115                    "#,
2116                );
2117            }
2118
2119            Trampoline::FutureWrite {
2120                instance,
2121                ty,
2122                options,
2123            }
2124            | Trampoline::FutureRead {
2125                instance,
2126                ty,
2127                options,
2128            } => {
2129                let intrinsic_fn = match trampoline {
2130                    Trampoline::FutureRead { .. } => self
2131                        .bindgen
2132                        .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureRead)),
2133                    Trampoline::FutureWrite { .. } => self
2134                        .bindgen
2135                        .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureWrite)),
2136                    _ => unreachable!("invalid trampoline"),
2137                };
2138
2139                let options = self
2140                    .component
2141                    .options
2142                    .get(*options)
2143                    .expect("failed to find options");
2144                let CanonicalOptions {
2145                    async_,
2146                    string_encoding,
2147                    callback,
2148                    post_return,
2149                    data_model:
2150                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
2151                    ..
2152                } = options
2153                else {
2154                    unreachable!("unexpected memory data model during future intrinsic");
2155                };
2156
2157                assert_eq!(
2158                    *instance, options.instance,
2159                    "component instances should match"
2160                );
2161                assert!(
2162                    callback.is_none(),
2163                    "callback should not be present for future intrinsic"
2164                );
2165                assert!(
2166                    post_return.is_none(),
2167                    "post_return should not be present for future intrinsic"
2168                );
2169
2170                let future_table_idx = ty.as_u32();
2171                let component_idx = instance.as_u32();
2172                let (memory_idx_js, get_memory_fn_js) = match memory {
2173                    Some(idx) => (
2174                        idx.as_u32().to_string(),
2175                        format!("() => memory{}", idx.as_u32()),
2176                    ),
2177                    None => ("undefined".into(), "undefined".into()),
2178                };
2179                let (realloc_idx, get_realloc_fn_js) = match realloc {
2180                    Some(idx) => (
2181                        idx.as_u32().to_string(),
2182                        format!("() => realloc{}", idx.as_u32()),
2183                    ),
2184                    None => ("undefined".into(), "undefined".to_string()),
2185                };
2186                let string_encoding = string_encoding_js_literal(string_encoding);
2187
2188                uwriteln!(
2189                    self.src.js,
2190                    r#"
2191                      const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {intrinsic_fn}.bind(
2192                          null,
2193                          {{
2194                              componentIdx: {component_idx},
2195                              memoryIdx: {memory_idx_js},
2196                              getMemoryFn: {get_memory_fn_js},
2197                              reallocIdx: {realloc_idx},
2198                              getReallocFn: {get_realloc_fn_js},
2199                              stringEncoding: {string_encoding},
2200                              futureTableIdx: {future_table_idx},
2201                              isAsync: {async_},
2202                          }},
2203                      )));
2204                    "#,
2205                    suspending_wrap_fn =
2206                        self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
2207                );
2208            }
2209
2210            Trampoline::FutureCancelRead {
2211                instance,
2212                ty,
2213                async_,
2214            }
2215            | Trampoline::FutureCancelWrite {
2216                instance,
2217                ty,
2218                async_,
2219            } => {
2220                let future_cancel_op_fn = match trampoline {
2221                    Trampoline::FutureCancelRead { .. } => self.bindgen.intrinsic(
2222                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureCancelRead),
2223                    ),
2224                    Trampoline::FutureCancelWrite { .. } => self.bindgen.intrinsic(
2225                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureCancelWrite),
2226                    ),
2227                    _ => unreachable!(),
2228                };
2229
2230                let component_idx = instance.as_u32();
2231                let future_table_idx = ty.as_u32();
2232
2233                uwriteln!(
2234                    self.src.js,
2235                    r#"
2236                      const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {future_cancel_op_fn}.bind(
2237                          null,
2238                          {{
2239                              futureTableIdx: {future_table_idx},
2240                              componentIdx: {component_idx},
2241                              isAsync: {async_},
2242                          }},
2243                      )));
2244                    "#,
2245                    suspending_wrap_fn =
2246                        self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
2247                );
2248            }
2249
2250            Trampoline::FutureDropReadable { instance, ty }
2251            | Trampoline::FutureDropWritable { instance, ty } => {
2252                let future_drop_op_fn = match trampoline {
2253                    Trampoline::FutureDropReadable { .. } => self.bindgen.intrinsic(
2254                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureDropReadable),
2255                    ),
2256                    Trampoline::FutureDropWritable { .. } => self.bindgen.intrinsic(
2257                        Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureDropWritable),
2258                    ),
2259                    _ => unreachable!(),
2260                };
2261
2262                let component_idx = instance.as_u32();
2263                let future_table_idx = ty.as_u32();
2264
2265                uwriteln!(
2266                    self.src.js,
2267                    r#"
2268                      const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {future_drop_op_fn}.bind(
2269                          null,
2270                          {{
2271                              futureTableIdx: {future_table_idx},
2272                              componentIdx: {component_idx},
2273                          }},
2274                      )));
2275                "#,
2276                    suspending_wrap_fn =
2277                        self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn),
2278                );
2279            }
2280
2281            Trampoline::FutureTransfer => {
2282                let future_transfer_fn = self
2283                    .bindgen
2284                    .intrinsic(Intrinsic::AsyncFuture(AsyncFutureIntrinsic::FutureTransfer));
2285                uwriteln!(self.src.js, "const trampoline{i} = {future_transfer_fn};");
2286            }
2287
2288            Trampoline::ErrorContextNew { ty, options, .. } => {
2289                let CanonicalOptions {
2290                    instance,
2291                    string_encoding,
2292                    data_model:
2293                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, .. }),
2294                    ..
2295                } = self
2296                    .component
2297                    .options
2298                    .get(*options)
2299                    .expect("failed to find options")
2300                else {
2301                    panic!("unexpected memory data model during error-context.new");
2302                };
2303
2304                self.ensure_error_context_local_table(*instance, *ty);
2305
2306                let local_err_tbl_idx = ty.as_u32();
2307                let component_idx = instance.as_u32();
2308
2309                let memory_idx = memory
2310                    .expect("missing realloc fn idx for error-context.debug-message")
2311                    .as_u32();
2312
2313                // Generate a string decoding function to match this trampoline that does appropriate encoding
2314                let decoder = match string_encoding {
2315                    wasmtime_environ::component::StringEncoding::Utf8 => self
2316                        .bindgen
2317                        .intrinsic(Intrinsic::String(StringIntrinsic::GlobalTextDecoderUtf8)),
2318                    wasmtime_environ::component::StringEncoding::Utf16 => self
2319                        .bindgen
2320                        .intrinsic(Intrinsic::String(StringIntrinsic::Utf16Decoder)),
2321                    enc => panic!(
2322                        "unsupported string encoding [{enc:?}] for error-context.debug-message"
2323                    ),
2324                };
2325                uwriteln!(
2326                    self.src.js,
2327                    "function trampoline{i}InputStr(ptr, len) {{
2328                         return {decoder}.decode(new DataView(memory{memory_idx}.buffer, ptr, len));
2329                    }}"
2330                );
2331
2332                let err_ctx_new_fn = self
2333                    .bindgen
2334                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextNew));
2335                // Store the options associated with this new error context for later use in the global array
2336                uwriteln!(
2337                    self.src.js,
2338                    "const trampoline{i} = {err_ctx_new_fn}.bind(
2339                         null,
2340                         {{
2341                             componentIdx: {component_idx},
2342                             localTableIdx: {local_err_tbl_idx},
2343                             readStrFn: trampoline{i}InputStr,
2344                         }}
2345                     );
2346                    "
2347                );
2348            }
2349
2350            Trampoline::ErrorContextDebugMessage {
2351                instance, options, ..
2352            } => {
2353                let CanonicalOptions {
2354                    async_,
2355                    callback,
2356                    post_return,
2357                    string_encoding,
2358                    data_model:
2359                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
2360                    ..
2361                } = self
2362                    .component
2363                    .options
2364                    .get(*options)
2365                    .expect("failed to find options")
2366                else {
2367                    panic!("unexpected memory data model during error-context.debug-message");
2368                };
2369
2370                let debug_message_fn = self
2371                    .bindgen
2372                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextDebugMessage));
2373
2374                let realloc_fn_idx = realloc
2375                    .expect("missing realloc fn idx for error-context.debug-message")
2376                    .as_u32();
2377                let memory_idx = memory
2378                    .expect("missing realloc fn idx for error-context.debug-message")
2379                    .as_u32();
2380
2381                // Generate a string encoding function to match this trampoline that does appropriate encoding
2382                match string_encoding {
2383                    wasmtime_environ::component::StringEncoding::Utf8 => {
2384                        let encode_fn = self
2385                            .bindgen
2386                            .intrinsic(Intrinsic::String(StringIntrinsic::Utf8Encode));
2387                        uwriteln!(
2388                            self.src.js,
2389                            "function trampoline{i}OutputStr(s, outputPtr) {{
2390                                 const memory = memory{memory_idx};
2391                                 const reallocFn = realloc{realloc_fn_idx};
2392                                 let {{ ptr, len }} = {encode_fn}(s, reallocFn, memory);
2393                                 new DataView(memory.buffer).setUint32(outputPtr, ptr, true)
2394                                 new DataView(memory.buffer).setUint32(outputPtr + 4, len, true)
2395                             }}"
2396                        );
2397                    }
2398                    wasmtime_environ::component::StringEncoding::Utf16 => {
2399                        let encode_fn = self
2400                            .bindgen
2401                            .intrinsic(Intrinsic::String(StringIntrinsic::Utf16Encode));
2402                        uwriteln!(
2403                            self.src.js,
2404                            "function trampoline{i}OutputStr(s, outputPtr) {{
2405                                 const memory = memory{memory_idx};
2406                                 const reallocFn = realloc{realloc_fn_idx};
2407                                 let ptr = {encode_fn}(s, reallocFn, memory);
2408                                 let len = s.length;
2409                                 new DataView(memory.buffer).setUint32(outputPtr, ptr, true)
2410                                 new DataView(memory.buffer).setUint32(outputPtr + 4, len, true)
2411                             }}"
2412                        );
2413                    }
2414                    enc => panic!(
2415                        "unsupported string encoding [{enc:?}] for error-context.debug-message"
2416                    ),
2417                };
2418
2419                let options_obj = format!(
2420                    "{{callback:{callback}, postReturn: {post_return}, async: {async_}}}",
2421                    callback = callback
2422                        .map(|v| v.as_u32().to_string())
2423                        .unwrap_or_else(|| "null".into()),
2424                    post_return = post_return
2425                        .map(|v| v.as_u32().to_string())
2426                        .unwrap_or_else(|| "null".into()),
2427                );
2428
2429                let component_idx = instance.as_u32();
2430                uwriteln!(
2431                    self.src.js,
2432                    "const trampoline{i} = {debug_message_fn}.bind(
2433                         null,
2434                         {{
2435                             componentIdx: {component_idx},
2436                             options: {options_obj},
2437                             writeStrFn: trampoline{i}OutputStr,
2438                         }}
2439                     );"
2440                );
2441            }
2442
2443            Trampoline::ErrorContextDrop { instance, ty } => {
2444                let drop_fn = self
2445                    .bindgen
2446                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextDrop));
2447                let local_err_tbl_idx = ty.as_u32();
2448                let component_idx = instance.as_u32();
2449                uwriteln!(
2450                    self.src.js,
2451                    r#"
2452                      const trampoline{i} = {drop_fn}.bind(
2453                          null,
2454                          {{ componentIdx: {component_idx}, localTableIdx: {local_err_tbl_idx} }},
2455                      );
2456                    "#
2457                );
2458            }
2459
2460            Trampoline::ErrorContextTransfer => {
2461                let transfer_fn = self
2462                    .bindgen
2463                    .intrinsic(Intrinsic::ErrCtx(ErrCtxIntrinsic::ErrorContextTransfer));
2464                uwriteln!(self.src.js, "const trampoline{i} = {transfer_fn};");
2465            }
2466
2467            // This sets up a subtask (sets parent, etc) for guest -> guest calls
2468            Trampoline::PrepareCall { memory } => {
2469                let prepare_call_fn = self
2470                    .bindgen
2471                    .intrinsic(Intrinsic::Host(HostIntrinsic::PrepareCall));
2472                let (memory_idx_js, memory_fn_js) = memory
2473                    .map(|v| {
2474                        (
2475                            v.as_u32().to_string(),
2476                            format!("() => memory{}", v.as_u32()),
2477                        )
2478                    })
2479                    .unwrap_or_else(|| ("null".into(), "() => null".into()));
2480                uwriteln!(
2481                    self.src.js,
2482                    "const trampoline{i} = {prepare_call_fn}.bind(null, {memory_idx_js}, {memory_fn_js});",
2483                )
2484            }
2485
2486            Trampoline::SyncStartCall { callback } => {
2487                let sync_start_call_fn = self
2488                    .bindgen
2489                    .intrinsic(Intrinsic::Host(HostIntrinsic::SyncStartCall));
2490                let (callback_idx, callback_fn) = callback
2491                    .map(|v| (v.as_u32().to_string(), format!("callback_{}", v.as_u32())))
2492                    .unwrap_or_else(|| ("null".into(), "null".into()));
2493
2494                // NOTE: the intrinsic blocks the (sync-lowered) caller until the
2495                // async-lifted callee resolves via task.return, so it must be
2496                // JSPI-wrapped.
2497                uwriteln!(
2498                    self.src.js,
2499                    "const trampoline{i} = new WebAssembly.Suspending({sync_start_call_fn}.bind(
2500                         null,
2501                         {{
2502                             callbackIdx: {callback_idx},
2503                             getCallbackFn: () => {callback_fn},
2504                         }},
2505                     ));",
2506                );
2507            }
2508
2509            // This actually starts a Task (whose parent is a subtask generated during PrepareCall)
2510            // for a from-component async import call
2511            Trampoline::AsyncStartCall {
2512                callback,
2513                post_return,
2514            } => {
2515                let async_start_call_fn = self
2516                    .bindgen
2517                    .intrinsic(Intrinsic::Host(HostIntrinsic::AsyncStartCall));
2518                let (callback_idx, callback_fn) = callback
2519                    .map(|v| (v.as_u32().to_string(), format!("callback_{}", v.as_u32())))
2520                    .unwrap_or_else(|| ("null".into(), "null".into()));
2521                let (post_return_idx, post_return_fn) = post_return
2522                    .map(|v| (v.as_u32().to_string(), format!("postReturn{}", v.as_u32())))
2523                    .unwrap_or_else(|| ("null".into(), "null".into()));
2524
2525                uwriteln!(
2526                    self.src.js,
2527                    "const trampoline{i} = {async_start_call_fn}.bind(
2528                         null,
2529                         {{
2530                             postReturnIdx: {post_return_idx},
2531                             getPostReturnFn: () => {post_return_fn},
2532                             callbackIdx: {callback_idx},
2533                             getCallbackFn: () => {callback_fn},
2534                         }},
2535                     );",
2536                );
2537            }
2538
2539            Trampoline::LowerImport {
2540                index: _,
2541                lower_ty,
2542                options,
2543            } => {
2544                let canon_opts = self
2545                    .component
2546                    .options
2547                    .get(*options)
2548                    .expect("failed to find options");
2549
2550                // TODO(fix): remove Global lowers, should enable using just exports[x] to export[y] call
2551                // TODO(fix): promising for the run (*as well as exports*)
2552                // TODO(fix): delete all asyncImports/exports
2553                // TODO(opt): opt-in sync import
2554
2555                let component_idx = canon_opts.instance.as_u32();
2556                let is_async = canon_opts.async_;
2557
2558                let cancellable = canon_opts.cancellable;
2559
2560                let func_ty = self.types.index(*lower_ty);
2561
2562                // Build list of lift functions for the params of the lowered import
2563                let param_types = &self.types.index(func_ty.params).types;
2564                let param_lift_fns_js =
2565                    gen_flat_lift_fn_list_js_expr(self, param_types.iter().as_slice(), &None);
2566
2567                // Build list of lower functions for the results of the lowered import
2568                let result_types = &self.types.index(func_ty.results).types;
2569                let result_lower_fns_js =
2570                    gen_flat_lower_fn_list_js_expr(self, result_types.iter().as_slice(), &None);
2571                let result_flat_count = result_types.iter().try_fold(0usize, |count, ty| {
2572                    self.types
2573                        .canonical_abi(ty)
2574                        .flat_count
2575                        .map(|flat_count| count + usize::from(flat_count))
2576                });
2577
2578                let get_callback_fn_js = canon_opts
2579                    .callback
2580                    .map(|idx| format!("() => callback_{}", idx.as_u32()))
2581                    .unwrap_or_else(|| "() => null".into());
2582                let get_post_return_fn_js = canon_opts
2583                    .post_return
2584                    .map(|idx| format!("() => postReturn{}", idx.as_u32()))
2585                    .unwrap_or_else(|| "() => null".into());
2586
2587                // Build the memory and realloc js expressions, retrieving the memory index and getter functions
2588                let (memory_exprs, realloc_expr_js) =
2589                    if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
2590                        memory,
2591                        realloc,
2592                    }) = canon_opts.data_model
2593                    {
2594                        (
2595                            memory.map(|idx| {
2596                                (
2597                                    idx.as_u32().to_string(),
2598                                    format!("() => memory{}", idx.as_u32()),
2599                                )
2600                            }),
2601                            realloc.map(|idx| format!("() => realloc{}", idx.as_u32())),
2602                        )
2603                    } else {
2604                        (None, None)
2605                    };
2606                let (memory_idx_js, memory_expr_js) =
2607                    memory_exprs.unwrap_or_else(|| ("null".into(), "() => null".into()));
2608                let realloc_expr_js = realloc_expr_js.unwrap_or_else(|| "undefined".into());
2609                let string_encoding_js = string_encoding_js_literal(&canon_opts.string_encoding);
2610
2611                // Build the lower import call that will wrap the actual trampoline
2612                let func_ty_async = func_ty.async_;
2613                let max_direct_results = if is_async || func_ty_async {
2614                    0
2615                } else {
2616                    MAX_FLAT_RESULTS
2617                };
2618                let has_result_pointer = result_flat_count
2619                    .map(|count| count > max_direct_results)
2620                    .unwrap_or(true);
2621                let call = format!(
2622                    r#"{lower_import_intrinsic}.bind(
2623                        null,
2624                        {{
2625                            trampolineIdx: {i},
2626                            componentIdx: {component_idx},
2627                            isAsync: {is_async},
2628                            isManualAsync: _trampoline{i}.manuallyAsync,
2629                            paramLiftFns: {param_lift_fns_js},
2630                            resultLowerFns: {result_lower_fns_js},
2631                            hasResultPointer: {has_result_pointer},
2632                            funcTypeIsAsync: {func_ty_async},
2633                            getCallbackFn: {get_callback_fn_js},
2634                            getPostReturnFn: {get_post_return_fn_js},
2635                            isCancellable: {cancellable},
2636                            memoryIdx: {memory_idx_js},
2637                            stringEncoding: {string_encoding_js},
2638                            getMemoryFn: {memory_expr_js},
2639                            getReallocFn: {realloc_expr_js},
2640                            importFn: _trampoline{i},
2641                        }},
2642                    )"#,
2643                    lower_import_intrinsic = if is_async || func_ty_async {
2644                        self.bindgen
2645                            .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::LowerImport))
2646                    } else {
2647                        self.bindgen.intrinsic(Intrinsic::AsyncTask(
2648                            AsyncTaskIntrinsic::LowerImportBackwardsCompat,
2649                        ))
2650                    }
2651                );
2652
2653                // NOTE: For Trampoline::LowerImport, the trampoline index is actually already defined,
2654                // but we *redefine* it to call the lower import function first.
2655                let suspending_wrap_fn =
2656                    self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
2657                if is_async || func_ty_async {
2658                    uwriteln!(
2659                        self.src.js,
2660                        "let trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {call}));"
2661                    );
2662                } else {
2663                    // TODO(breaking): once manually specifying async imports is removed,
2664                    // we can avoid the second check below.
2665                    uwriteln!(
2666                        self.src.js,
2667                        "let trampoline{i} = _trampoline{i}.manuallyAsync ? new WebAssembly.Suspending({suspending_wrap_fn}({component_idx}, {call})) : {call};"
2668                    );
2669                }
2670            }
2671
2672            Trampoline::Transcoder {
2673                op,
2674                from,
2675                from64,
2676                to,
2677                to64,
2678            } => {
2679                if *from64 || *to64 {
2680                    unimplemented!("memory 64 transcoder");
2681                }
2682                let from = from.as_u32();
2683                let to = to.as_u32();
2684                match op {
2685                    Transcode::Copy(FixedEncoding::Utf8) => {
2686                        uwriteln!(
2687                            self.src.js,
2688                            r#"
2689                              function trampoline{i} (from_ptr, len, to_ptr) {{
2690                                  new Uint8Array(memory{to}.buffer, to_ptr, len).set(new Uint8Array(memory{from}.buffer, from_ptr, len));
2691                              }}
2692                            "#
2693                        );
2694                    }
2695                    Transcode::Copy(FixedEncoding::Utf16) => unimplemented!("utf16 copier"),
2696                    Transcode::Copy(FixedEncoding::Latin1) => unimplemented!("latin1 copier"),
2697                    Transcode::Latin1ToUtf16 => unimplemented!("latin to utf16 transcoder"),
2698                    Transcode::Latin1ToUtf8 => unimplemented!("latin to utf8 transcoder"),
2699                    Transcode::Utf16ToCompactProbablyUtf16 => {
2700                        unimplemented!("utf16 to compact wtf16 transcoder")
2701                    }
2702                    Transcode::Utf16ToCompactUtf16 => {
2703                        unimplemented!("utf16 to compact utf16 transcoder")
2704                    }
2705                    Transcode::Utf16ToLatin1 => unimplemented!("utf16 to latin1 transcoder"),
2706                    Transcode::Utf16ToUtf8 => {
2707                        uwriteln!(
2708                            self.src.js,
2709                            r#"
2710                              function trampoline{i} (src, src_len, dst, dst_len) {{
2711                                  const encoder = new TextEncoder();
2712                                  const {{ read, written }} = encoder.encodeInto(String.fromCharCode.apply(null, new Uint16Array(memory{from}.buffer, src, src_len)), new Uint8Array(memory{to}.buffer, dst, dst_len));
2713                                  return [read, written];
2714                              }}
2715                            "#,
2716                        );
2717                    }
2718                    Transcode::Utf8ToCompactUtf16 => {
2719                        unimplemented!("utf8 to compact utf16 transcoder")
2720                    }
2721                    Transcode::Utf8ToLatin1 => unimplemented!("utf8 to latin1 transcoder"),
2722                    Transcode::Utf8ToUtf16 => {
2723                        uwriteln!(
2724                            self.src.js,
2725                            r#"
2726                              function trampoline{i} (from_ptr, len, to_ptr) {{
2727                                  const decoder = new TextDecoder();
2728                                  const content = decoder.decode(new Uint8Array(memory{from}.buffer, from_ptr, len));
2729                                  const codeUnits = content.length;
2730                                  const view = new Uint16Array(memory{to}.buffer, to_ptr, codeUnits);
2731                                  for (var i = 0; i < codeUnits; i++) {{
2732                                      view[i] = content.charCodeAt(i);
2733                                  }}
2734                                  return codeUnits;
2735                              }}
2736                            "#,
2737                        );
2738                    }
2739                };
2740            }
2741
2742            Trampoline::ResourceNew {
2743                ty: resource_ty_idx,
2744                ..
2745            } => {
2746                self.ensure_resource_table(*resource_ty_idx);
2747                let rid = resource_ty_idx.as_u32();
2748                let rsc_table_create_own = self.bindgen.intrinsic(Intrinsic::Resource(
2749                    ResourceIntrinsic::ResourceTableCreateOwn,
2750                ));
2751                uwriteln!(
2752                    self.src.js,
2753                    "const trampoline{i} = {rsc_table_create_own}.bind(null, handleTable{rid});"
2754                );
2755            }
2756
2757            Trampoline::ResourceRep {
2758                ty: resource_ty_idx,
2759                ..
2760            } => {
2761                self.ensure_resource_table(*resource_ty_idx);
2762                let rid = resource_ty_idx.as_u32();
2763                let rsc_table_get = self
2764                    .bindgen
2765                    .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableGet));
2766                uwriteln!(
2767                    self.src.js,
2768                    "function trampoline{i} (handle) {{
2769                        return {rsc_table_get}(handleTable{rid}, handle).rep;
2770                    }}"
2771                );
2772            }
2773
2774            Trampoline::ResourceDrop {
2775                ty: resource_table_ty_idx,
2776                ..
2777            } => {
2778                self.ensure_resource_table(*resource_table_ty_idx);
2779                let tid = resource_table_ty_idx.as_u32();
2780                let resource_table_ty = &self.types[*resource_table_ty_idx];
2781                let resource_ty = resource_table_ty.unwrap_concrete_ty();
2782                let rid = resource_ty.as_u32();
2783
2784                // Build the code fragment that encapsulates calling the destructor
2785                let dtor = if let Some(resource_idx) =
2786                    self.component.defined_resource_index(resource_ty)
2787                {
2788                    let resource_def = self
2789                        .component
2790                        .initializers
2791                        .iter()
2792                        .find_map(|i| match i {
2793                            GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
2794                            _ => None,
2795                        })
2796                        .unwrap();
2797
2798                    // If a destructor index is defined for the resource, call it
2799                    if let Some(dtor) = &resource_def.dtor {
2800                        format!(
2801                            "
2802                            {}(handleEntry.rep);",
2803                            self.core_def(dtor)
2804                        )
2805                    } else {
2806                        "".into()
2807                    }
2808                } else {
2809                    // Imported resource is one without a defined resource index.
2810                    // If it is a captured instance (class instance was created externally so had to
2811                    // be assigned a rep), and there is a Symbol.dispose handler, call it explicitly
2812                    // for imported resources when the resource is dropped.
2813                    // Otherwise if it is an instance without a captured class definition, then
2814                    // call the low-level bindgen destructor.
2815                    let symbol_dispose = self.bindgen.intrinsic(Intrinsic::SymbolDispose);
2816                    let symbol_cabi_dispose = self.bindgen.intrinsic(Intrinsic::SymbolCabiDispose);
2817
2818                    // previous imports walk should define all imported resources which are accessible
2819                    if let Some(imported_resource_local_name) =
2820                        self.bindgen.local_names.try_get(resource_ty)
2821                    {
2822                        format!(
2823                                            "
2824                            const rsc = captureTable{rid}.get(handleEntry.rep);
2825                            if (rsc) {{
2826                                if (rsc[{symbol_dispose}]) rsc[{symbol_dispose}]();
2827                                captureTable{rid}.delete(handleEntry.rep);
2828                            }} else if ({imported_resource_local_name}[{symbol_cabi_dispose}]) {{
2829                                {imported_resource_local_name}[{symbol_cabi_dispose}](handleEntry.rep);
2830                            }}"
2831                                        )
2832                    } else {
2833                        // If not, then capture / disposal paths are never called
2834                        format!(
2835                            "throw new TypeError('unreachable trampoline for resource [{:?}]')",
2836                            resource_ty
2837                        )
2838                    }
2839                };
2840
2841                let rsc_table_remove = self
2842                    .bindgen
2843                    .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
2844                uwrite!(
2845                    self.src.js,
2846                    "function trampoline{i}(handle) {{
2847                        const handleEntry = {rsc_table_remove}(handleTable{tid}, handle);
2848                        if (handleEntry.own) {{
2849                            {dtor}
2850                        }}
2851                    }}
2852                    ",
2853                );
2854            }
2855
2856            Trampoline::ResourceTransferOwn => {
2857                let resource_transfer = self
2858                    .bindgen
2859                    .intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTransferOwn));
2860                uwriteln!(self.src.js, "const trampoline{i} = {resource_transfer};");
2861            }
2862
2863            Trampoline::ResourceTransferBorrow => {
2864                let resource_transfer =
2865                    self.bindgen
2866                        .intrinsic(if self.bindgen.opts.valid_lifting_optimization {
2867                            Intrinsic::Resource(
2868                                ResourceIntrinsic::ResourceTransferBorrowValidLifting,
2869                            )
2870                        } else {
2871                            Intrinsic::Resource(ResourceIntrinsic::ResourceTransferBorrow)
2872                        });
2873                uwriteln!(self.src.js, "const trampoline{i} = {resource_transfer};");
2874            }
2875
2876            Trampoline::TaskReturn {
2877                results, options, ..
2878            } => {
2879                let canon_opts = self
2880                    .component
2881                    .options
2882                    .get(*options)
2883                    .expect("failed to find options");
2884                let CanonicalOptions {
2885                    instance,
2886                    async_,
2887                    data_model:
2888                        CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions { memory, realloc }),
2889                    callback,
2890                    post_return,
2891                    string_encoding,
2892                    ..
2893                } = canon_opts
2894                else {
2895                    unreachable!("unexpected memory data model during task.return");
2896                };
2897
2898                // Validate canonopts
2899                if realloc.is_some() && memory.is_none() {
2900                    panic!("memory must be present if realloc is");
2901                }
2902                if *async_ && post_return.is_some() {
2903                    panic!("async and post return must not be specified together");
2904                }
2905                if *async_ && callback.is_none() {
2906                    panic!("callback must be specified for async");
2907                }
2908                if let Some(cb_idx) = callback {
2909                    let cb_fn = &self.types[TypeFuncIndex::from_u32(cb_idx.as_u32())];
2910                    match self.types[cb_fn.params].types[..] {
2911                        [InterfaceType::S32, InterfaceType::S32, InterfaceType::S32] => {}
2912                        _ => panic!("unexpected params for async callback fn"),
2913                    }
2914                    match self.types[cb_fn.results].types[..] {
2915                        [InterfaceType::S32] => {}
2916                        _ => panic!("unexpected results for async callback fn"),
2917                    }
2918                }
2919
2920                let result_types = &self.types[*results].types;
2921
2922                // Calculate the number of parameters required to represent the results,
2923                // and whether they'll be stored in memory
2924                let result_flat_param_total: usize = result_types
2925                    .iter()
2926                    .map(|t| {
2927                        self.types
2928                            .canonical_abi(t)
2929                            .flat_count
2930                            .map(usize::from)
2931                            .unwrap_or(0)
2932                    })
2933                    .sum();
2934                let use_direct_params = result_flat_param_total < MAX_FLAT_PARAMS;
2935
2936                // Build up a list of all the lifting functions that will be needed for the types
2937                // that are actually being passed through task.return
2938                let mut lift_fns: Vec<String> = Vec::with_capacity(result_types.len());
2939                for result_ty in result_types {
2940                    lift_fns.push(gen_flat_lift_fn_js_expr(self, result_ty, &None));
2941                }
2942                let lift_fns_js = format!("[{}]", lift_fns.join(","));
2943
2944                // Build up a list of all the lowering functions that will be needed for the types
2945                // that are actually being passed through task.return
2946                //
2947                // This is usually only necessary if this task is part of a guest->guest async call
2948                // (i.e. via prepare & async start call)
2949                let mut lower_fns: Vec<String> = Vec::with_capacity(result_types.len());
2950                for result_ty in result_types {
2951                    lower_fns.push(gen_flat_lower_fn_js_expr(self, result_ty, &None));
2952                }
2953                let lower_fns_js = format!("[{}]", lower_fns.join(","));
2954
2955                let get_memory_fn_js = memory
2956                    .map(|idx| format!("() => memory{}", idx.as_u32()))
2957                    .unwrap_or_else(|| "() => null".into());
2958                let memory_idx_js = memory
2959                    .map(|idx| idx.as_u32().to_string())
2960                    .unwrap_or_else(|| "null".into());
2961                let component_idx = instance.as_u32();
2962                let task_return_fn = self
2963                    .bindgen
2964                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::TaskReturn));
2965                let callback_fn_idx = callback
2966                    .map(|v| v.as_u32().to_string())
2967                    .unwrap_or_else(|| "null".into());
2968                let string_encoding_js = string_encoding_js_literal(string_encoding);
2969
2970                uwriteln!(
2971                    self.src.js,
2972                    "const trampoline{i} = {task_return_fn}.bind(
2973                         null,
2974                         {{
2975                             componentIdx: {component_idx},
2976                             useDirectParams: {use_direct_params},
2977                             getMemoryFn: {get_memory_fn_js},
2978                             memoryIdx: {memory_idx_js},
2979                             callbackFnIdx: {callback_fn_idx},
2980                             liftFns: {lift_fns_js},
2981                             lowerFns: {lower_fns_js},
2982                             stringEncoding: {string_encoding_js},
2983                         }},
2984                     );",
2985                );
2986            }
2987
2988            Trampoline::BackpressureInc { instance } => {
2989                let backpressure_inc_fn = self
2990                    .bindgen
2991                    .intrinsic(Intrinsic::Component(ComponentIntrinsic::BackpressureInc));
2992                uwriteln!(
2993                    self.src.js,
2994                    "const trampoline{i} = {backpressure_inc_fn}.bind(null, {instance});\n",
2995                    instance = instance.as_u32(),
2996                );
2997            }
2998
2999            Trampoline::BackpressureDec { instance } => {
3000                let backpressure_dec_fn = self
3001                    .bindgen
3002                    .intrinsic(Intrinsic::Component(ComponentIntrinsic::BackpressureDec));
3003                uwriteln!(
3004                    self.src.js,
3005                    "const trampoline{i} = {backpressure_dec_fn}.bind(null, {instance});\n",
3006                    instance = instance.as_u32(),
3007                );
3008            }
3009
3010            Trampoline::ThreadYield {
3011                cancellable,
3012                instance,
3013            } => {
3014                let yield_fn = self
3015                    .bindgen
3016                    .intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::Yield));
3017                let suspending_wrap_fn =
3018                    self.bindgen.intrinsic(Intrinsic::SuspendingImportWrapperFn);
3019                let component_instance_idx = instance.as_u32();
3020                uwriteln!(
3021                    self.src.js,
3022                    r#"
3023                      const trampoline{i} = new WebAssembly.Suspending({suspending_wrap_fn}({component_instance_idx}, {yield_fn}.bind(null, {{
3024                          isCancellable: {cancellable},
3025                          componentIdx: {component_instance_idx},
3026                      }})));
3027                    "#,
3028                );
3029            }
3030            Trampoline::ThreadIndex => todo!("Trampoline::ThreadIndex"),
3031            Trampoline::ThreadNewIndirect { .. } => todo!("Trampoline::ThreadNewIndirect"),
3032            Trampoline::ThreadSuspend { .. } => todo!("Trampoline::ThreadSuspend"),
3033            Trampoline::ThreadSuspendTo { .. } => todo!("Trampoline::ThreadSuspendTo"),
3034            Trampoline::ThreadUnsuspend { .. } => todo!("Trampoline::ThreadUnsuspend"),
3035            Trampoline::ThreadYieldToSuspended { .. } => {
3036                todo!("Trampoline::ThreadYieldToSuspended")
3037            }
3038            Trampoline::ThreadSuspendToSuspended { .. } => {
3039                todo!("Trampoline::ThreadYieldToSuspended")
3040            }
3041
3042            Trampoline::Trap => {
3043                uwriteln!(
3044                    self.src.js,
3045                    "function trampoline{i}(rep) {{ throw new TypeError('Trap'); }}"
3046                );
3047            }
3048
3049            Trampoline::EnterSyncCall => {
3050                let enter_symmetric_sync_guest_call_fn = self.bindgen.intrinsic(
3051                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::EnterSymmetricSyncGuestCall),
3052                );
3053                // Under JSPI, contended entry queues for the callee's per-slice
3054                // exclusive lock by returning a promise, which requires the
3055                // trampoline to be Suspending (fused sync calls then run inside
3056                // promising activations). Outside JSPI a Suspending import
3057                // would trap on every call from the plain (non-promising)
3058                // stacks such transpiles use, so the trampoline stays plain
3059                // and contended entry traps (uncontended entry is fully
3060                // synchronous either way).
3061                let uses_jspi = matches!(
3062                    self.bindgen.opts.async_mode,
3063                    Some(AsyncMode::JavaScriptPromiseIntegration { .. })
3064                );
3065                if uses_jspi {
3066                    uwriteln!(
3067                        self.src.js,
3068                        r#"
3069                          const trampoline{i} = new WebAssembly.Suspending({enter_symmetric_sync_guest_call_fn});
3070                        "#,
3071                    );
3072                } else {
3073                    uwriteln!(
3074                        self.src.js,
3075                        r#"
3076                          const trampoline{i} = {enter_symmetric_sync_guest_call_fn};
3077                        "#,
3078                    );
3079                }
3080            }
3081
3082            Trampoline::ExitSyncCall => {
3083                let exit_symmetric_sync_guest_call_fn = self.bindgen.intrinsic(
3084                    Intrinsic::AsyncTask(AsyncTaskIntrinsic::ExitSymmetricSyncGuestCall),
3085                );
3086                uwriteln!(
3087                    self.src.js,
3088                    "const trampoline{i} = {exit_symmetric_sync_guest_call_fn};\n",
3089                );
3090            }
3091        }
3092    }
3093
3094    fn instantiation_global_initializer(&mut self, init: &GlobalInitializer) {
3095        match init {
3096            // Extracting callbacks is a part of the async support for hosts -- it ensures that
3097            // a given core export can be turned into a callback function that will be used
3098            // later.
3099            //
3100            // Generally what we have to do here is to create a callback that can be called upon re-entrance
3101            // into the component after a related suspension.
3102            GlobalInitializer::ExtractCallback(ExtractCallback { index, def }) => {
3103                let callback_idx = index.as_u32();
3104                let core_def = self.core_def(def);
3105
3106                uwriteln!(self.src.js, "let callback_{callback_idx};",);
3107
3108                // If the function returns an async value like a stream or future,
3109                // the callback that is executed in the the event loop (`AsyncTaskIntrinsic::DriverLoop`)
3110                // may attempt to wait due to calling necessarily async host imports like {stream, future}.{write, read}.
3111                //
3112                // Here, we mark the task with an indicator that denotes whether the callback should be run this way.
3113                //
3114                // TODO: can we be more selective here rather than wrapping every callback in WebAssembly.promising?
3115                // every callback *could* do stream.write, but many may not.
3116                uwriteln!(
3117                    self.src.js_init,
3118                    r#"
3119                      callback_{callback_idx} = WebAssembly.promising({core_def});
3120                      callback_{callback_idx}.fnName = "{core_def}";
3121                    "#
3122                );
3123            }
3124
3125            GlobalInitializer::InstantiateModule(m, instance) => {
3126                // NOTE: we keep track of the current component instance index for the module being instantiatied
3127                // because some  because context.set/context.get are no longer trampolines,
3128                // and we do not have access to the correct component index that each operation belongs to at build time
3129                self.init_current_module = *instance;
3130
3131                match m {
3132                    InstantiateModule::Static(idx, args) => {
3133                        self.instantiate_static_module(*idx, args, *instance);
3134                    }
3135                    // This is only needed when instantiating an imported core wasm
3136                    // module which while easy to implement here is not possible to
3137                    // test at this time so it's left unimplemented.
3138                    InstantiateModule::Import(..) => unimplemented!(),
3139                }
3140            }
3141
3142            GlobalInitializer::LowerImport { index, import } => {
3143                self.lower_import(*index, *import);
3144            }
3145
3146            GlobalInitializer::ExtractMemory(m) => {
3147                let def = self.core_export_var_name(&m.export);
3148                let idx = m.index.as_u32();
3149                uwriteln!(self.src.js, "let memory{idx};");
3150                uwriteln!(self.src.js_init, "memory{idx} = {def};");
3151            }
3152
3153            GlobalInitializer::ExtractRealloc(r) => {
3154                let def = self.core_def(&r.def);
3155                let idx = r.index.as_u32();
3156                uwriteln!(self.src.js, "let realloc{idx};");
3157                uwriteln!(self.src.js, "let realloc{idx}Async;");
3158                uwriteln!(self.src.js_init, "realloc{idx} = {def};",);
3159                // NOTE: sometimes we may be fed a realloc that isn't a webassembly function at all
3160                // but has instead been converted to JS (see 'flavorful' test in test/runtime.js')
3161                uwriteln!(
3162                    self.src.js_init,
3163                    r#"
3164                      try {{
3165                          realloc{idx}Async = WebAssembly.promising({def});
3166                      }} catch(err) {{
3167                          realloc{idx}Async = {def};
3168                      }}
3169                    "#
3170                );
3171            }
3172
3173            GlobalInitializer::ExtractPostReturn(p) => {
3174                let def = self.core_def(&p.def);
3175                let idx = p.index.as_u32();
3176                uwriteln!(self.src.js, "let postReturn{idx};");
3177                uwriteln!(self.src.js, "let postReturn{idx}Async;");
3178                uwriteln!(self.src.js_init, "postReturn{idx} = {def};");
3179                // NOTE: sometimes we may be fed a post return fn that isn't a webassembly function
3180                // at all but has instead been converted to JS (see 'flavorful' test in test/runtime.js)
3181                uwriteln!(
3182                    self.src.js_init,
3183                    r#"
3184                      try {{
3185                          postReturn{idx}Async = WebAssembly.promising({def});
3186                      }} catch(err) {{
3187                          postReturn{idx}Async = {def};
3188                      }}
3189                    "#
3190                );
3191            }
3192
3193            GlobalInitializer::Resource(_) => {}
3194
3195            GlobalInitializer::ExtractTable(_) => {}
3196        }
3197    }
3198
3199    fn instantiate_static_module(
3200        &mut self,
3201        module_idx: StaticModuleIndex,
3202        args: &[CoreDef],
3203        instance: Option<RuntimeComponentInstanceIndex>,
3204    ) {
3205        // Build a JS "import object" which represents `args`. The `args` is a
3206        // flat representation which needs to be zip'd with the list of names to
3207        // correspond to the JS wasm embedding API. This is one of the major
3208        // differences between Wasmtime's and JS's embedding API.
3209        let mut import_obj = BTreeMap::new();
3210        for (module, name, arg) in self.modules[module_idx].imports(args) {
3211            let def = self.augmented_import_def(&arg);
3212            let dst = import_obj.entry(module).or_insert(BTreeMap::new());
3213            let prev = dst.insert(name, def);
3214            assert!(
3215                prev.is_none(),
3216                "unsupported duplicate import of `{module}::{name}`"
3217            );
3218            assert!(prev.is_none());
3219        }
3220
3221        if self.bindgen.opts.asmjs {
3222            let component_instance_idx = instance
3223                .expect("missing runtime component index during static module instantiation")
3224                .as_u32();
3225
3226            self.add_intrinsic(Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask));
3227            self.add_intrinsic(Intrinsic::GetGlobalCurrentTaskMetaFn);
3228            let current_task_get_fn =
3229                Intrinsic::AsyncTask(AsyncTaskIntrinsic::GetCurrentTask).name();
3230            let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
3231
3232            let dst = import_obj.entry("env").or_insert(BTreeMap::new());
3233            let prev = dst.insert(
3234                "setTempRet0",
3235                format!(
3236                    "(x) => {{
3237                const {{ taskID }} = {get_global_current_task_meta_fn}({component_instance_idx});
3238
3239                const taskMeta = {current_task_get_fn}({component_instance_idx}, taskID);
3240                if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}
3241
3242                const task = taskMeta.task;
3243                if (!task) {{ throw new Error('invalid/missing async task'); }}
3244
3245                task.tmpRetI64HighBits = x|0;
3246            }}"
3247                ),
3248            );
3249            assert!(
3250                prev.is_none(),
3251                "unsupported duplicate import of `env::setTempRet0`"
3252            );
3253            assert!(prev.is_none());
3254        }
3255
3256        // Build list of imports
3257        let mut imports = String::new();
3258        if !import_obj.is_empty() {
3259            imports.push_str(", {\n");
3260            for (module, names) in import_obj {
3261                imports.push_str(&maybe_quote_id(module));
3262                imports.push_str(": {\n");
3263                for (name, val) in names {
3264                    imports.push_str(&maybe_quote_id(name));
3265                    uwriteln!(imports, ": {val},");
3266                }
3267                imports.push_str("},\n");
3268            }
3269            imports.push('}');
3270        }
3271
3272        let i = self.instances.push(module_idx);
3273        let iu32 = i.as_u32();
3274        let instantiate = self.bindgen.intrinsic(Intrinsic::InstantiateCore);
3275        uwriteln!(self.src.js, "let exports{iu32};");
3276
3277        match self.bindgen.opts.instantiation_mode {
3278            Some(InstantiationMode::Async) | None => {
3279                uwriteln!(
3280                    self.src.js_init,
3281                    "({{ exports: exports{iu32} }} = yield {instantiate}(yield module{}{imports}));",
3282                    module_idx.as_u32(),
3283                )
3284            }
3285
3286            Some(InstantiationMode::Sync) => {
3287                uwriteln!(
3288                    self.src.js_init,
3289                    "({{ exports: exports{iu32} }} = {instantiate}(module{}{imports}));",
3290                    module_idx.as_u32(),
3291                );
3292            }
3293        }
3294    }
3295
3296    /// Map all types in parameters and results to local resource types
3297    ///
3298    /// # Arguments
3299    ///
3300    /// * `func` - The function in question
3301    /// * `ty_func_idx` - Type index of the function
3302    /// * `resource_map` - resource map of locally resolved types
3303    fn create_resource_fn_map(
3304        &mut self,
3305        func: &Function,
3306        ty_func_idx: TypeFuncIndex,
3307        resource_map: &mut ResourceMap,
3308    ) {
3309        // Connect resources used in parameters
3310        let params_ty = &self.types[self.types[ty_func_idx].params];
3311        for (p, iface_ty) in func.params.iter().zip(params_ty.types.iter()) {
3312            if let Type::Id(id) = p.ty {
3313                self.connect_resource_types(id, iface_ty, resource_map);
3314            }
3315        }
3316        // Connect resources used in results
3317        let results_ty = &self.types[self.types[ty_func_idx].results];
3318        if let (Some(Type::Id(id)), Some(iface_ty)) = (func.result, results_ty.types.first()) {
3319            self.connect_resource_types(id, iface_ty, resource_map);
3320        }
3321    }
3322
3323    fn resource_name(
3324        resolve: &Resolve,
3325        local_names: &'a mut LocalNames,
3326        resource: TypeId,
3327        resource_map: &BTreeMap<TypeId, ResourceIndex>,
3328    ) -> &'a str {
3329        let resource = crate::dealias(resolve, resource);
3330        local_names
3331            .get_or_create(
3332                resource_map[&resource],
3333                &resolve.types[resource]
3334                    .name
3335                    .as_ref()
3336                    .unwrap()
3337                    .to_upper_camel_case(),
3338            )
3339            .0
3340    }
3341
3342    /// Returns the local JS class name for an imported resource attached to
3343    /// the lowered import `import_index` (as the receiver class of a
3344    /// method/static or the target of a constructor).
3345    ///
3346    /// The same interface -- and thus the same `wit-parser` resource type --
3347    /// may be imported more than once under different labels via the
3348    /// component model `implements` feature, each import with its own
3349    /// resource table. The class must therefore be resolved through the
3350    /// specific import instance rather than through the wit type, which is
3351    /// shared by all labels.
3352    fn imported_resource_name(&mut self, import_index: ImportIndex, resource: TypeId) -> String {
3353        let resolve = self.resolve;
3354        let types = self.types;
3355        let component = self.component;
3356        let resource = crate::dealias(resolve, resource);
3357        let resource_wit_name = resolve.types[resource].name.as_ref().unwrap();
3358        if let (
3359            _,
3360            ComponentExtern {
3361                ty: TypeDef::ComponentInstance(inst),
3362                ..
3363            },
3364        ) = &component.import_types[import_index]
3365            && let Some(ComponentExtern {
3366                ty: TypeDef::Resource(rt_idx),
3367                ..
3368            }) = types[*inst].exports.get(resource_wit_name)
3369        {
3370            let rid = types[*rt_idx].unwrap_concrete_ty();
3371            return self
3372                .bindgen
3373                .local_names
3374                .get_or_create(rid, &resource_wit_name.to_upper_camel_case())
3375                .0
3376                .to_string();
3377        }
3378        // World-level resource imports (and any other shape) are uniquely
3379        // identified by their wit type.
3380        Instantiator::resource_name(
3381            resolve,
3382            &mut self.bindgen.local_names,
3383            resource,
3384            &self.imports_resource_types,
3385        )
3386        .to_string()
3387    }
3388
3389    /// Finds the component import that provides the given resource table.
3390    ///
3391    /// Returns the import name along with whether the resource is provided
3392    /// by an imported instance (`true`) or directly by a world-level
3393    /// resource import (`false`).
3394    ///
3395    /// The same interface may be imported under multiple labels (component
3396    /// model `implements` feature), each label with its own resource table,
3397    /// so the import is identified through the wasmtime resource index
3398    /// rather than through the wit type's owning interface, which is shared
3399    /// by all labels.
3400    fn find_import_providing_resource(
3401        &self,
3402        resource_idx: ResourceIndex,
3403    ) -> Option<(&'a str, bool)> {
3404        let component = self.component;
3405        let types = self.types;
3406        for (_, (imp_name, extern_)) in component.import_types.iter() {
3407            match &extern_.ty {
3408                TypeDef::ComponentInstance(inst) => {
3409                    for (_, export) in types[*inst].exports.iter() {
3410                        if let TypeDef::Resource(rt) = &export.ty
3411                            && types[*rt].unwrap_concrete_ty() == resource_idx
3412                        {
3413                            return Some((imp_name.as_str(), true));
3414                        }
3415                    }
3416                }
3417                TypeDef::Resource(rt) if types[*rt].unwrap_concrete_ty() == resource_idx => {
3418                    return Some((imp_name.as_str(), false));
3419                }
3420                _ => {}
3421            }
3422        }
3423        None
3424    }
3425
3426    fn lower_import(&mut self, index: LoweredIndex, import: RuntimeImportIndex) {
3427        let (options, trampoline, func_ty) = self.lowering_options[index];
3428
3429        // Get the world key for the CM import
3430        let (import_index, path) = &self.component.imports[import];
3431        let (import_name, _) = &self.component.import_types[*import_index];
3432        let world_key = &self.imports[import_name];
3433
3434        // Determine the name of the function
3435        let (func, func_name, iface_name) =
3436            match &self.resolve.worlds[self.world].imports[world_key] {
3437                WorldItem::Function(func) => {
3438                    assert_eq!(path.len(), 0);
3439                    (func, import_name, None)
3440                }
3441                WorldItem::Interface { id, .. } => {
3442                    assert_eq!(path.len(), 1);
3443                    let iface = &self.resolve.interfaces[*id];
3444                    let func = &iface.functions[&path[0]];
3445                    (
3446                        func,
3447                        &path[0],
3448                        Some(iface.name.as_deref().unwrap_or_else(|| import_name)),
3449                    )
3450                }
3451                WorldItem::Type { .. } => unreachable!("unexpected imported world item type"),
3452            };
3453
3454        let is_async = is_async_fn(func, options);
3455
3456        if options.async_ {
3457            assert!(
3458                options.post_return.is_none(),
3459                "async function {func_name} (import {import_name}) can't have post return",
3460            );
3461        }
3462
3463        // Host lifted async import (i.e. JSPI)
3464        let requires_async_porcelain = requires_async_porcelain(
3465            FunctionIdentifier::Fn(func),
3466            import_name,
3467            &self.async_imports,
3468        );
3469
3470        // A labeled import of a named interface (the component model
3471        // `implements` feature) falls back to a mapping for the implemented
3472        // interface id when the label itself has no mapping, so that e.g.
3473        // WASI shim mappings apply to labeled imports as well.
3474        let implements = self.resolve.implements_value(
3475            world_key,
3476            &self.resolve.worlds[self.world].imports[world_key],
3477        );
3478
3479        // Nested interfaces only currently possible through mapping
3480        let (import_specifier, maybe_iface_member) = map_import_with_implements(
3481            &self.bindgen.opts.map,
3482            if iface_name.is_some() {
3483                import_name
3484            } else {
3485                match func.kind {
3486                    FunctionKind::Method(_) => {
3487                        let stripped = import_name.strip_prefix("[method]").unwrap();
3488                        &stripped[0..stripped.find(".").unwrap()]
3489                    }
3490                    FunctionKind::AsyncMethod(_) => {
3491                        let stripped = import_name.strip_prefix("[async method]").unwrap();
3492                        &stripped[0..stripped.find(".").unwrap()]
3493                    }
3494                    FunctionKind::Static(_) => {
3495                        let stripped = import_name.strip_prefix("[static]").unwrap();
3496                        &stripped[0..stripped.find(".").unwrap()]
3497                    }
3498                    FunctionKind::AsyncStatic(_) => {
3499                        let stripped = import_name.strip_prefix("[async static]").unwrap();
3500                        &stripped[0..stripped.find(".").unwrap()]
3501                    }
3502                    FunctionKind::Constructor(_) => {
3503                        import_name.strip_prefix("[constructor]").unwrap()
3504                    }
3505                    FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => import_name,
3506                }
3507            },
3508            implements.as_deref(),
3509        );
3510
3511        // Create mappings for resources
3512        let mut import_resource_map = ResourceMap::new();
3513
3514        self.create_resource_fn_map(func, func_ty, &mut import_resource_map);
3515
3516        let (callee_name, call_type) = match func.kind {
3517            FunctionKind::Freestanding => (
3518                self.bindgen
3519                    .local_names
3520                    .get_or_create(
3521                        format!(
3522                            "import:{import}-{maybe_iface_member}-{func_name}",
3523                            import = import_specifier,
3524                            maybe_iface_member = maybe_iface_member.as_deref().unwrap_or(""),
3525                            func_name = func.name
3526                        ),
3527                        &func.name,
3528                    )
3529                    .0
3530                    .to_string(),
3531                CallType::Standard,
3532            ),
3533
3534            FunctionKind::AsyncFreestanding => (
3535                self.bindgen
3536                    .local_names
3537                    .get_or_create(
3538                        format!(
3539                            "import:async-{import}-{maybe_iface_member}-{func_name}",
3540                            import = import_specifier,
3541                            maybe_iface_member = maybe_iface_member.as_deref().unwrap_or(""),
3542                            func_name = func.name
3543                        ),
3544                        &func.name,
3545                    )
3546                    .0
3547                    .to_string(),
3548                CallType::AsyncStandard,
3549            ),
3550
3551            FunctionKind::Method(_) => (
3552                func.item_name().to_lower_camel_case(),
3553                CallType::CalleeResourceDispatch,
3554            ),
3555
3556            FunctionKind::AsyncMethod(_) => (
3557                func.item_name().to_lower_camel_case(),
3558                CallType::AsyncCalleeResourceDispatch,
3559            ),
3560
3561            FunctionKind::Static(resource_id) => (
3562                format!(
3563                    "{}.{}",
3564                    self.imported_resource_name(*import_index, resource_id),
3565                    func.item_name().to_lower_camel_case()
3566                ),
3567                CallType::Standard,
3568            ),
3569
3570            FunctionKind::AsyncStatic(resource_id) => (
3571                format!(
3572                    "{}.{}",
3573                    self.imported_resource_name(*import_index, resource_id),
3574                    func.item_name().to_lower_camel_case()
3575                ),
3576                CallType::AsyncStandard,
3577            ),
3578
3579            FunctionKind::Constructor(resource_id) => (
3580                format!(
3581                    "new {}",
3582                    self.imported_resource_name(*import_index, resource_id)
3583                ),
3584                CallType::Standard,
3585            ),
3586        };
3587
3588        // A function's interface type can be async while its canonical lower is
3589        // sync. In that case the core caller uses the regular flat canonical
3590        // ABI and blocks while the async callee runs. Deriving this from
3591        // `is_async` instead would incorrectly apply the async argument-buffer
3592        // ABI to sync-lowered functions with more than four flat parameters.
3593        let abi = if options.async_ {
3594            AbiVariant::GuestImportAsync
3595        } else {
3596            AbiVariant::GuestImport
3597        };
3598
3599        // Use the translated core function type as the source of truth for the
3600        // JavaScript trampoline's arity. Keep the canonical ABI calculation
3601        // checked against it since `abi::call` below uses that calculation to
3602        // generate the trampoline body.
3603        let core_ty = self.types[options.core_type].unwrap_func();
3604        let wasm_signature = self.resolve.wasm_signature(abi, func);
3605        assert_eq!(wasm_signature.params.len(), core_ty.params().len());
3606        assert_eq!(wasm_signature.results.len(), core_ty.results().len());
3607        let nparams = core_ty.params().len();
3608
3609        // Generate the JS trampoline function for a bound import
3610        let trampoline_idx = trampoline.as_u32();
3611        match self.bindgen.opts.import_bindings {
3612            None | Some(BindingsMode::Js) | Some(BindingsMode::Hybrid) => {
3613                // TODO(breaking): remove as we do not not need to manually specify async imports anymore in P3 w/ native coloring
3614                if is_async | requires_async_porcelain {
3615                    // NOTE: for async imports that will go through Trampoline::LowerImport,
3616                    // we prefix the raw import with '_' as it will later be used in the
3617                    // definition of trampoline{i} which will actually be fed into
3618                    // unbundled modules
3619                    uwrite!(
3620                        self.src.js,
3621                        "\nconst _trampoline{trampoline_idx} = async function"
3622                    );
3623                } else {
3624                    uwrite!(
3625                        self.src.js,
3626                        "\nconst _trampoline{trampoline_idx} = function"
3627                    );
3628                }
3629
3630                let iface_name = if import_name.is_empty() {
3631                    None
3632                } else {
3633                    Some(import_name.to_string())
3634                };
3635
3636                // Write out the function (brace + body + brace)
3637                self.bindgen(JsFunctionBindgenArgs {
3638                    nparams,
3639                    call_type,
3640                    iface_name: iface_name.as_deref(),
3641                    callee: &callee_name,
3642                    opts: options,
3643                    func,
3644                    resource_map: &import_resource_map,
3645                    abi,
3646                    requires_async_porcelain,
3647                    is_async,
3648                    wrap_async_future_result: false,
3649                    for_import: true,
3650                });
3651                uwriteln!(self.src.js, "");
3652
3653                uwriteln!(
3654                    self.src.js,
3655                    "_trampoline{trampoline_idx}.fnName = '{}#{callee_name}';",
3656                    iface_name.unwrap_or_default(),
3657                );
3658
3659                // TODO(breaking): remove once support for manually specified async imports is removed
3660                if requires_async_porcelain {
3661                    uwriteln!(
3662                        self.src.js,
3663                        "_trampoline{trampoline_idx}.manuallyAsync = true;"
3664                    );
3665                }
3666            }
3667
3668            Some(BindingsMode::Optimized) | Some(BindingsMode::DirectOptimized) => {
3669                uwriteln!(self.src.js, "let trampoline{trampoline_idx};");
3670            }
3671        };
3672
3673        // Build import bindings & trampolines for the import
3674        //
3675        // This is only necessary if an import binding mode is specified and not JS (the default),
3676        // (e.g. Optimized, Direct, Hybrid).
3677        if !matches!(
3678            self.bindgen.opts.import_bindings,
3679            None | Some(BindingsMode::Js)
3680        ) {
3681            let (memory, realloc) =
3682                if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
3683                    memory,
3684                    realloc,
3685                }) = options.data_model
3686                {
3687                    (
3688                        memory.map(|idx| format!(" memory: memory{},", idx.as_u32())),
3689                        realloc.map(|idx| format!(" realloc: realloc{},", idx.as_u32())),
3690                    )
3691                } else {
3692                    (None, None)
3693                };
3694            let memory = memory.unwrap_or_default();
3695            let realloc = realloc.unwrap_or_default();
3696
3697            let post_return = options
3698                .post_return
3699                .map(|idx| format!(" postReturn: postReturn{},", idx.as_u32()))
3700                .unwrap_or("".into());
3701            let string_encoding = match options.string_encoding {
3702                wasmtime_environ::component::StringEncoding::Utf8 => "",
3703                wasmtime_environ::component::StringEncoding::Utf16 => " stringEncoding: 'utf16',",
3704                wasmtime_environ::component::StringEncoding::CompactUtf16 => {
3705                    " stringEncoding: 'compact-utf16',"
3706                }
3707            };
3708
3709            let callee_name = match func.kind {
3710                FunctionKind::Constructor(_) => callee_name[4..].to_string(),
3711
3712                FunctionKind::Static(_)
3713                | FunctionKind::AsyncStatic(_)
3714                | FunctionKind::Freestanding
3715                | FunctionKind::AsyncFreestanding => callee_name.to_string(),
3716
3717                FunctionKind::Method(resource_id) | FunctionKind::AsyncMethod(resource_id) => {
3718                    format!(
3719                        "{}.prototype.{callee_name}",
3720                        self.imported_resource_name(*import_index, resource_id)
3721                    )
3722                }
3723            };
3724
3725            // Save information about imported resources for later
3726            self.resource_imports.extend(import_resource_map.clone());
3727
3728            let resource_tables = {
3729                let mut resource_table_ids: Vec<TypeResourceTableIndex> = Vec::new();
3730
3731                for (_, data) in import_resource_map {
3732                    let ResourceTable {
3733                        data: ResourceData::Host { tid, .. },
3734                        ..
3735                    } = &data
3736                    else {
3737                        unreachable!("unexpected non-host resource table");
3738                    };
3739                    resource_table_ids.push(*tid);
3740                }
3741
3742                if resource_table_ids.is_empty() {
3743                    "".to_string()
3744                } else {
3745                    format!(
3746                        " resourceTables: [{}],",
3747                        resource_table_ids
3748                            .iter()
3749                            .map(|x| format!("handleTable{}", x.as_u32()))
3750                            .collect::<Vec<String>>()
3751                            .join(", ")
3752                    )
3753                }
3754            };
3755
3756            // Build trampolines for the import
3757            match self.bindgen.opts.import_bindings {
3758                Some(BindingsMode::Hybrid) => {
3759                    let symbol_cabi_lower = self.bindgen.intrinsic(Intrinsic::SymbolCabiLower);
3760                    uwriteln!(self.src.js_init, "if ({callee_name}[{symbol_cabi_lower}]) {{
3761                        trampoline{} = {callee_name}[{symbol_cabi_lower}]({{{memory}{realloc}{post_return}{string_encoding}{resource_tables}}});
3762                    }}", trampoline.as_u32());
3763                }
3764                Some(BindingsMode::Optimized) => {
3765                    let symbol_cabi_lower = self.bindgen.intrinsic(Intrinsic::SymbolCabiLower);
3766                    if !self.bindgen.opts.valid_lifting_optimization {
3767                        uwriteln!(self.src.js_init, "if (!{callee_name}[{symbol_cabi_lower}]) {{
3768                            throw new TypeError('import for \"{import_name}\" does not define a Symbol.for(\"cabiLower\") optimized binding');
3769                        }}");
3770                    }
3771                    uwriteln!(
3772                        self.src.js_init,
3773                        "trampoline{} = {callee_name}[{symbol_cabi_lower}]({{{memory}{realloc}{post_return}{string_encoding}{resource_tables}}});",
3774                        trampoline.as_u32()
3775                    );
3776                }
3777                Some(BindingsMode::DirectOptimized) => {
3778                    uwriteln!(
3779                        self.src.js_init,
3780                        "trampoline{} = {callee_name}({{{memory}{realloc}{post_return}{string_encoding}}});",
3781                        trampoline.as_u32()
3782                    );
3783                }
3784                None | Some(BindingsMode::Js) => unreachable!("invalid bindings mode"),
3785            };
3786        }
3787
3788        // Figure out the function name and callee (e.g. class for a given resource) to use
3789        let (import_name, binding_name) = match func.kind {
3790            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
3791                (func_name.to_lower_camel_case(), callee_name)
3792            }
3793
3794            FunctionKind::Method(tid)
3795            | FunctionKind::AsyncMethod(tid)
3796            | FunctionKind::Static(tid)
3797            | FunctionKind::AsyncStatic(tid)
3798            | FunctionKind::Constructor(tid) => {
3799                let ty = &self.resolve.types[tid];
3800                let class_name = ty.name.as_ref().unwrap().to_upper_camel_case();
3801                let resource_name = self.imported_resource_name(*import_index, tid);
3802                (class_name, resource_name)
3803            }
3804        };
3805
3806        self.ensure_import(
3807            import_specifier,
3808            iface_name,
3809            maybe_iface_member.as_deref(),
3810            if iface_name.is_some() {
3811                Some(import_name.to_string())
3812            } else {
3813                None
3814            },
3815            binding_name,
3816        );
3817    }
3818
3819    /// Process an import if it has not already been processed
3820    ///
3821    /// # Arguments
3822    ///
3823    /// * `import_specifier` - The specifier of the import as used in JS (ex. `"@bytecodealliance/preview2-shim/random"`)
3824    /// * `iface_name` - The name of the WIT interface related to this binding, if present (ex. `"random"`)
3825    /// * `iface_member` - The name of the interface member, if present (ex. `"random"`)
3826    /// * `import_binding` - The name of binding, if present (ex. `"getRandomBytes"`)
3827    /// * `local_name` - Local name of the import (ex. `"getRandomBytes"`)
3828    ///
3829    fn ensure_import(
3830        &mut self,
3831        import_specifier: String,
3832        iface_name: Option<&str>,
3833        iface_member: Option<&str>,
3834        import_binding: Option<String>,
3835        local_name: String,
3836    ) {
3837        if import_specifier.starts_with("webidl:") {
3838            self.bindgen
3839                .intrinsic(Intrinsic::WebIdl(WebIdlIntrinsic::GlobalThisIdlProxy));
3840        }
3841
3842        // Build the import path depending on the kind of interface
3843        let mut import_path = Vec::with_capacity(2);
3844        import_path.push(import_specifier);
3845        if let Some(_iface_name) = iface_name {
3846            // Mapping can be used to construct virtual nested namespaces
3847            // which is used eg to support WASI interface groupings
3848            if let Some(iface_member) = iface_member {
3849                import_path.push(iface_member.to_lower_camel_case());
3850            }
3851            import_path.push(import_binding.clone().unwrap());
3852        } else if let Some(iface_member) = iface_member {
3853            import_path.push(iface_member.into());
3854        } else if let Some(import_binding) = &import_binding {
3855            import_path.push(import_binding.into());
3856        }
3857
3858        // Add the import binding that represents this import
3859        self.bindgen
3860            .esm_bindgen
3861            .add_import_binding(&import_path, local_name);
3862    }
3863
3864    /// Connect resources that have no types
3865    ///
3866    /// Commonly this is used for resources that have a type on on the import side
3867    /// but no relevant type on the receiving side, for which local types must be generated locally:
3868    /// - `error-context`
3869    /// - `future<_>`
3870    /// - `stream<_>`
3871    ///
3872    fn connect_p3_resources(
3873        &mut self,
3874        id: &TypeId,
3875        maybe_elem_ty: &Option<Type>,
3876        iface_ty: &InterfaceType,
3877        resource_map: &mut ResourceMap,
3878    ) {
3879        let remote_resource = match iface_ty {
3880            InterfaceType::Future(table_idx) => {
3881                let future_table_ty = &self.types[*table_idx];
3882                let future_ty = &self.types[future_table_ty.ty];
3883
3884                // Determine the level of future nesting
3885                let mut future_nesting_level = 0;
3886                let mut payload_ty = future_ty.payload;
3887                while let Some(InterfaceType::Future(inner_ty)) = payload_ty {
3888                    future_nesting_level += 1;
3889                    payload_ty = self.types[self.types[inner_ty].ty].payload;
3890                }
3891
3892                ResourceTable {
3893                    imported: true,
3894                    data: ResourceData::Guest {
3895                        resource_name: "Future".into(),
3896                        prefix: Some(format!("${}", table_idx.as_u32())),
3897                        extra: Some(ResourceExtraData::Future {
3898                            table_idx: *table_idx,
3899                            nesting_level: future_nesting_level,
3900                            elem_ty: maybe_elem_ty.map(|ty| {
3901                                let table_ty = &self.types[*table_idx];
3902                                let future_ty_idx = table_ty.ty;
3903                                let future_ty = &self.types[future_ty_idx];
3904                                let iface_ty = future_ty.payload.expect(
3905                                    "missing future payload despite elem type being present",
3906                                );
3907                                let abi = self.types.canonical_abi(&iface_ty);
3908                                PayloadTypeMetadata {
3909                                    ty,
3910                                    iface_ty,
3911
3912                                    // TODO: we need to use the currently-being-built resource map here,
3913                                    // because it may contain *just inserted* information (could be either imports or exports)
3914                                    // that should be used
3915                                    //
3916                                    // We need to *augment* the normal built in
3917                                    // `instantiator.resource_{exports,imports}` with things that we're resolving now.
3918                                    lift_js_expr: gen_flat_lift_fn_js_expr(
3919                                        self,
3920                                        &iface_ty,
3921                                        &Some(resource_map),
3922                                    ),
3923                                    lower_js_expr: gen_flat_lower_fn_js_expr(
3924                                        self,
3925                                        &iface_ty,
3926                                        &Some(resource_map),
3927                                    ),
3928                                    size32: abi.size32,
3929                                    align32: abi.align32,
3930                                    flat_count: abi.flat_count,
3931                                }
3932                            }),
3933                        }),
3934                    },
3935                }
3936            }
3937            InterfaceType::Stream(table_idx) => ResourceTable {
3938                imported: true,
3939                data: ResourceData::Guest {
3940                    resource_name: "Stream".into(),
3941                    prefix: Some(format!("${}", table_idx.as_u32())),
3942                    extra: Some(ResourceExtraData::Stream {
3943                        table_idx: *table_idx,
3944                        elem_ty: maybe_elem_ty.map(|ty| {
3945                            let table_ty = &self.types[*table_idx];
3946                            let stream_ty_idx = table_ty.ty;
3947                            let stream_ty = &self.types[stream_ty_idx];
3948                            let iface_ty = stream_ty
3949                                .payload
3950                                .expect("missing payload despite elem type being present");
3951                            let abi = self.types.canonical_abi(&iface_ty);
3952                            PayloadTypeMetadata {
3953                                ty,
3954                                iface_ty,
3955                                lift_js_expr: gen_flat_lift_fn_js_expr(
3956                                    self,
3957                                    &iface_ty,
3958                                    &Some(resource_map),
3959                                ),
3960                                lower_js_expr: gen_flat_lower_fn_js_expr(
3961                                    self,
3962                                    &iface_ty,
3963                                    &Some(resource_map),
3964                                ),
3965                                size32: abi.size32,
3966                                align32: abi.align32,
3967                                flat_count: abi.flat_count,
3968                            }
3969                        }),
3970                    }),
3971                },
3972            },
3973            InterfaceType::ErrorContext(table_idx) => ResourceTable {
3974                imported: true,
3975                data: ResourceData::Guest {
3976                    resource_name: "ErrorContext".into(),
3977                    prefix: Some(format!("${}", table_idx.as_u32())),
3978                    extra: Some(ResourceExtraData::ErrorContext {
3979                        table_idx: *table_idx,
3980                    }),
3981                },
3982            },
3983            _ => unreachable!("unexpected interface type [{iface_ty:?}] with no type"),
3984        };
3985
3986        resource_map.insert(*id, remote_resource);
3987    }
3988
3989    /// Connect two types as host resources
3990    ///
3991    /// # Arguments
3992    ///
3993    /// * `t` - the TypeId
3994    /// * `tid` - Index into the type resource table of the interface (foreign side)
3995    /// * `resource_map` - Resource map that holds resource pairings
3996    ///
3997    fn connect_host_resource(
3998        &mut self,
3999        t: TypeId,
4000        resource_table_ty_idx: TypeResourceTableIndex,
4001        resource_map: &mut ResourceMap,
4002    ) {
4003        self.ensure_resource_table(resource_table_ty_idx);
4004
4005        // Figure out whether the resource index we're dealing with is for an imported type
4006        let resource_table_ty = &self.types[resource_table_ty_idx];
4007        let resource_idx = resource_table_ty.unwrap_concrete_ty();
4008        let imported = self
4009            .component
4010            .defined_resource_index(resource_idx)
4011            .is_none();
4012
4013        // Retrieve the resource id for the type definition
4014        let resource_id = crate::dealias(self.resolve, t);
4015        let ty = &self.resolve.types[resource_id];
4016
4017        // If the resource is defined by this component (i.e. exported/used internally, *not* imported),
4018        // then determine the destructor that should be run based on the relevant resource
4019        let mut dtor_str = None;
4020        if let Some(resource_idx) = self.component.defined_resource_index(resource_idx) {
4021            assert!(!imported);
4022            let resource_def = self
4023                .component
4024                .initializers
4025                .iter()
4026                .find_map(|i| match i {
4027                    GlobalInitializer::Resource(r) if r.index == resource_idx => Some(r),
4028                    _ => None,
4029                })
4030                .unwrap();
4031
4032            if let Some(dtor) = &resource_def.dtor {
4033                dtor_str = Some(self.core_def(dtor));
4034            }
4035        }
4036
4037        // Look up the local import name
4038        let resource_name = ty.name.as_ref().unwrap().to_upper_camel_case();
4039
4040        let local_name = if imported {
4041            // Resolve the specific import that provides this resource table:
4042            // see [`Instantiator::find_import_providing_resource`].
4043            let imported_resource_entry = self.find_import_providing_resource(resource_idx);
4044
4045            let (world_key, iface_name) = match imported_resource_entry {
4046                // Resource provided by an imported instance: derive the
4047                // interface member name from the world key shape.
4048                Some((imp_name, _is_from_instance @ true)) => {
4049                    let key = self.imports[imp_name].clone();
4050                    let iface_name = match &key {
4051                        WorldKey::Name(name) => Some(name.clone()),
4052                        WorldKey::Interface(_) => {
4053                            match &self.resolve.worlds[self.world].imports[&key] {
4054                                WorldItem::Interface { id, .. } => {
4055                                    self.resolve.interfaces[*id].name.clone()
4056                                }
4057                                _ => None,
4058                            }
4059                        }
4060                    };
4061                    (key, iface_name)
4062                }
4063                // A world-level `import x: resource` style import
4064                Some((imp_name, _is_from_instance @ false)) => {
4065                    (self.imports[imp_name].clone(), None)
4066                }
4067                // Fall back to locating the import through the wit type's
4068                // owner; reachable only if the resource table doesn't appear
4069                // in the component's import types.
4070                None => match ty.owner {
4071                    wit_parser::TypeOwner::World(world) => (
4072                        self.resolve.worlds[world]
4073                            .imports
4074                            .iter()
4075                            .find(
4076                                |&(_, item)| matches!(item, WorldItem::Type { id, .. } if *id == t),
4077                            )
4078                            .unwrap()
4079                            .0
4080                            .clone(),
4081                        None,
4082                    ),
4083                    wit_parser::TypeOwner::Interface(iface) => {
4084                        let key = self.resolve.worlds[self.world]
4085                            .imports
4086                            .iter()
4087                            .find(|&(_, item)| match item {
4088                                WorldItem::Interface { id, .. } => *id == iface,
4089                                _ => false,
4090                            })
4091                            .map(|(key, _)| key)
4092                            .unwrap_or_else(|| {
4093                                panic!(
4094                                    "unable to find world import for interface [{}]",
4095                                    self.resolve.interfaces[iface]
4096                                        .name
4097                                        .as_deref()
4098                                        .unwrap_or("<unnamed>")
4099                                )
4100                            });
4101                        (
4102                            key.clone(),
4103                            match key {
4104                                WorldKey::Name(name) => Some(name.clone()),
4105                                WorldKey::Interface(_) => {
4106                                    self.resolve.interfaces[iface].name.clone()
4107                                }
4108                            },
4109                        )
4110                    }
4111                    wit_parser::TypeOwner::None => unimplemented!(),
4112                },
4113            };
4114            let iface_name = iface_name.as_deref();
4115
4116            let import_name = self.resolve.name_world_key(&world_key);
4117            let implements = self.resolve.worlds[self.world]
4118                .imports
4119                .get(&world_key)
4120                .and_then(|item| self.resolve.implements_value(&world_key, item));
4121            let (local_name, _) = self
4122                .bindgen
4123                .local_names
4124                .get_or_create(resource_idx, &resource_name);
4125
4126            let local_name_str = local_name.to_string();
4127
4128            // Nested interfaces only currently possible through mapping; must
4129            // resolve to the same specifier as the owning interface's
4130            // functions, including the `implements` mapping fallback.
4131            let (import_specifier, maybe_iface_member) = map_import_with_implements(
4132                &self.bindgen.opts.map,
4133                &import_name,
4134                implements.as_deref(),
4135            );
4136
4137            // Ensure that the import exists
4138            self.ensure_import(
4139                import_specifier,
4140                iface_name,
4141                maybe_iface_member.as_deref(),
4142                iface_name.map(|_| resource_name),
4143                local_name_str.to_string(),
4144            );
4145            local_name_str
4146        } else {
4147            let (local_name, _) = self
4148                .bindgen
4149                .local_names
4150                .get_or_create(resource_idx, &resource_name);
4151            local_name.to_string()
4152        };
4153
4154        // Add a resource table to track the host resource
4155        let entry = ResourceTable {
4156            imported,
4157            data: ResourceData::Host {
4158                tid: resource_table_ty_idx,
4159                rid: resource_idx,
4160                component_idx: resource_table_ty.unwrap_concrete_instance(),
4161                needs_task_context: self
4162                    .context_components
4163                    .borrow()
4164                    .contains(&resource_table_ty.unwrap_concrete_instance()),
4165                local_name,
4166                dtor_name: dtor_str,
4167            },
4168        };
4169
4170        // If the the resource already exists, then  ensure that it is exactly the same as the
4171        // value we're attempting to insert
4172        if let Some(existing) = resource_map.get(&resource_id) {
4173            // The same wit resource type may be imported more than once under
4174            // different labels (component model `implements` feature), giving
4175            // it one resource table per label. Shared type-keyed maps keep
4176            // the first table encountered; maps built per lowered function
4177            // only ever see the table of that function's own instance.
4178            if *existing != entry {
4179                assert!(
4180                    imported && existing.imported,
4181                    "conflicting resource tables for non-imported resource"
4182                );
4183            }
4184            return;
4185        }
4186
4187        // Insert the resource into the map,
4188        resource_map.insert(resource_id, entry);
4189    }
4190
4191    /// Connect resources that are defined at the type levels in `wit-parser`
4192    /// to their types as defined in `wasmtime-environ`
4193    ///
4194    /// The types that are connected here are stored in the `resource_map` for
4195    /// use later.
4196    ///
4197    /// # Arguments
4198    ///
4199    /// * `id` - The ID of the type if present (can be missing when dealing with `error-context`s, `future<_>`, etc)
4200    /// * `iface_ty` - The relevant interface type
4201    /// * `resource_map` - Resource map that we will update with pairings
4202    ///
4203    fn connect_resource_types(
4204        &mut self,
4205        id: TypeId,
4206        iface_ty: &InterfaceType,
4207        resource_map: &mut ResourceMap,
4208    ) {
4209        let kind = &self.resolve.types[id].kind;
4210        match (kind, iface_ty) {
4211            // For flags and enums we can do nothing -- they're simple values (string/number)
4212            (TypeDefKind::Flags(_), InterfaceType::Flags(_))
4213            | (TypeDefKind::Enum(_), InterfaceType::Enum(_)) => {}
4214
4215            // Connect records to records
4216            (TypeDefKind::Record(t1), InterfaceType::Record(t2)) => {
4217                let t2 = &self.types[*t2];
4218                for (f1, f2) in t1.fields.iter().zip(t2.fields.iter()) {
4219                    if let Type::Id(id) = f1.ty {
4220                        self.connect_resource_types(id, &f2.ty, resource_map);
4221                    }
4222                }
4223            }
4224
4225            // Handle connecting owned/borrowed handles to owned/borrowed handles
4226            (
4227                TypeDefKind::Handle(Handle::Own(t1) | Handle::Borrow(t1)),
4228                InterfaceType::Own(t2) | InterfaceType::Borrow(t2),
4229            ) => {
4230                self.connect_host_resource(*t1, *t2, resource_map);
4231            }
4232
4233            // Connect tuples to interface tuples
4234            (TypeDefKind::Tuple(t1), InterfaceType::Tuple(t2)) => {
4235                let t2 = &self.types[*t2];
4236                for (f1, f2) in t1.types.iter().zip(t2.types.iter()) {
4237                    if let Type::Id(id) = f1 {
4238                        self.connect_resource_types(*id, f2, resource_map);
4239                    }
4240                }
4241            }
4242
4243            // Connect inner types of variants to their interface types
4244            (TypeDefKind::Variant(t1), InterfaceType::Variant(t2)) => {
4245                let t2 = &self.types[*t2];
4246                for (f1, f2) in t1.cases.iter().zip(t2.cases.iter()) {
4247                    if let Some(Type::Id(id)) = &f1.ty {
4248                        self.connect_resource_types(*id, f2.1.as_ref().unwrap(), resource_map);
4249                    }
4250                }
4251            }
4252
4253            // Connect option<t> to option<t>
4254            (TypeDefKind::Option(t1), InterfaceType::Option(t2)) => {
4255                let t2 = &self.types[*t2];
4256                if let Type::Id(id) = t1 {
4257                    self.connect_resource_types(*id, &t2.ty, resource_map);
4258                }
4259            }
4260
4261            // Connect result<t> to result<t>
4262            (TypeDefKind::Result(t1), InterfaceType::Result(t2)) => {
4263                let t2 = &self.types[*t2];
4264                if let Some(Type::Id(id)) = &t1.ok {
4265                    self.connect_resource_types(*id, &t2.ok.unwrap(), resource_map);
4266                }
4267                if let Some(Type::Id(id)) = &t1.err {
4268                    self.connect_resource_types(*id, &t2.err.unwrap(), resource_map);
4269                }
4270            }
4271
4272            // Connect list<t> to list types
4273            (TypeDefKind::List(t1), InterfaceType::List(t2)) => {
4274                let t2 = &self.types[*t2];
4275                if let Type::Id(id) = t1 {
4276                    self.connect_resource_types(*id, &t2.element, resource_map);
4277                }
4278            }
4279
4280            // Connect map key and value types
4281            (TypeDefKind::Map(key, value), InterfaceType::Map(map)) => {
4282                let map = &self.types[*map];
4283                if let Type::Id(id) = key {
4284                    self.connect_resource_types(*id, &map.key, resource_map);
4285                }
4286                if let Type::Id(id) = value {
4287                    self.connect_resource_types(*id, &map.value, resource_map);
4288                }
4289            }
4290
4291            // Connect list<t, size> to list types
4292            (TypeDefKind::FixedLengthList(t1, _len), InterfaceType::FixedLengthList(t2)) => {
4293                let t2 = &self.types[*t2];
4294                if let Type::Id(id) = t1 {
4295                    self.connect_resource_types(*id, &t2.element, resource_map);
4296                }
4297            }
4298
4299            // Connect named types
4300            (TypeDefKind::Type(ty), _) => {
4301                if let Type::Id(id) = ty {
4302                    self.connect_resource_types(*id, iface_ty, resource_map);
4303                }
4304            }
4305
4306            // Connect futures & stream types
4307            (TypeDefKind::Future(maybe_elem_ty), container_iface_ty)
4308            | (TypeDefKind::Stream(maybe_elem_ty), container_iface_ty) => {
4309                match maybe_elem_ty {
4310                    // The case of an empty future is the propagation of a `null`-like value, usually a simple signal
4311                    // which we'll connect with the *normally invalid* type value 0 as an indicator
4312                    None => {
4313                        self.connect_p3_resources(&id, maybe_elem_ty, iface_ty, resource_map);
4314                    }
4315                    // For custom types we must recur to properly connect the inner type
4316                    Some(elem_ty @ Type::Id(elem_ty_id)) => {
4317                        // As the internal type could be a resource, and connecting p3 resources
4318                        // may generate lifting/lowering fns, we must connect the payload of the
4319                        // future/stream first, if necessary
4320                        //
4321                        let maybe_elem_iface_ty = match container_iface_ty {
4322                            InterfaceType::Future(future_table_ty_idx) => {
4323                                let future_table_ty = &self.types[*future_table_ty_idx];
4324                                let future = &self.types[future_table_ty.ty];
4325                                future.payload
4326                            }
4327                            InterfaceType::Stream(stream_table_ty_idx) => {
4328                                let stream_table_ty = &self.types[*stream_table_ty_idx];
4329                                let stream = &self.types[stream_table_ty.ty];
4330                                stream.payload
4331                            }
4332                            _ => unreachable!("unexpected iface type"),
4333                        };
4334                        if let Some(elem_iface_ty) = maybe_elem_iface_ty {
4335                            // TODO(refactor): the last arg of `connect_resource_types()` (`extra_resource_map`) is
4336                            // necessary because we are not building the imports/exports array directly.
4337                            //
4338                            // It's a hack that *should* be removable if we do more explicit and intentional
4339                            // building of import/export resource mappings (i.e. not building a partial map that we
4340                            // later `.extend()` onto the instantiator's maps, depending on whether we were working on
4341                            // imports or exports).
4342                            self.connect_resource_types(*elem_ty_id, &elem_iface_ty, resource_map);
4343                        }
4344
4345                        self.connect_p3_resources(&id, &Some(*elem_ty), iface_ty, resource_map);
4346                    }
4347                    // For basic types that are connected (non inner types) we can do a generic connect
4348                    Some(_) => {
4349                        self.connect_p3_resources(&id, maybe_elem_ty, iface_ty, resource_map);
4350                    }
4351                }
4352            }
4353
4354            // Connect the types in an ok/error variant of a Result to the future that they're being sent in
4355            (
4356                TypeDefKind::Result(Result_ { ok, err }),
4357                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4358            ) => {
4359                if let Some(Type::Id(ok_t)) = ok {
4360                    self.connect_resource_types(*ok_t, tk2, resource_map)
4361                }
4362                if let Some(Type::Id(err_t)) = err {
4363                    self.connect_resource_types(*err_t, tk2, resource_map)
4364                }
4365            }
4366
4367            // Connect the types in an option to the future that they're being sent in
4368            (
4369                TypeDefKind::Option(ty),
4370                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4371            ) => {
4372                if let Type::Id(some_t) = ty {
4373                    self.connect_resource_types(*some_t, tk2, resource_map)
4374                }
4375            }
4376
4377            // Connect resources to the future/stream that they're being sent in
4378            (
4379                TypeDefKind::Handle(Handle::Own(t1) | Handle::Borrow(t1)),
4380                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4381            ) => self.connect_resource_types(*t1, tk2, resource_map),
4382
4383            (TypeDefKind::Resource, InterfaceType::Future(_) | InterfaceType::Stream(_)) => {}
4384
4385            // Connect the inner types of variants to the future they're being sent in
4386            (
4387                TypeDefKind::Variant(variant),
4388                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4389            ) => {
4390                for f1 in variant.cases.iter() {
4391                    if let Some(Type::Id(id)) = &f1.ty {
4392                        self.connect_resource_types(*id, tk2, resource_map);
4393                    }
4394                }
4395            }
4396
4397            // Connect the inner types of variants to the future they're being sent in
4398            (
4399                TypeDefKind::Record(record),
4400                tk2 @ (InterfaceType::Future(_) | InterfaceType::Stream(_)),
4401            ) => {
4402                for f1 in record.fields.iter() {
4403                    if let Type::Id(id) = f1.ty {
4404                        self.connect_resource_types(id, tk2, resource_map);
4405                    }
4406                }
4407            }
4408
4409            // Simliar to the non-stream/future case, we don't have to do anything for
4410            // flags and plain enums as they are read directly
4411            (
4412                TypeDefKind::Enum(_) | TypeDefKind::Flags(_),
4413                InterfaceType::Future(_) | InterfaceType::Stream(_),
4414            ) => {}
4415
4416            (TypeDefKind::Resource, tk2) => {
4417                unreachable!(
4418                    "resource types do not need to be connected (in this case, to [{tk2:?}])"
4419                )
4420            }
4421
4422            (TypeDefKind::Unknown, tk2) => {
4423                unreachable!("unknown types cannot be connected (in this case to [{tk2:?}])")
4424            }
4425
4426            (tk1, tk2) => unreachable!("invalid typedef kind combination [{tk1:?}] [{tk2:?}]",),
4427        }
4428    }
4429
4430    fn bindgen(&mut self, args: JsFunctionBindgenArgs) {
4431        let JsFunctionBindgenArgs {
4432            nparams,
4433            call_type,
4434            iface_name,
4435            callee,
4436            opts,
4437            func,
4438            resource_map,
4439            abi,
4440            requires_async_porcelain,
4441            is_async,
4442            wrap_async_future_result,
4443            for_import,
4444        } = args;
4445
4446        let (memory, realloc) =
4447            if let CanonicalOptionsDataModel::LinearMemory(LinearMemoryOptions {
4448                memory,
4449                realloc,
4450            }) = opts.data_model
4451            {
4452                (
4453                    memory.map(|idx| format!("memory{}", idx.as_u32())),
4454                    realloc.map(|idx| {
4455                        format!(
4456                            "realloc{}{}",
4457                            idx.as_u32(),
4458                            if is_async {
4459                                "Async"
4460                            } else {
4461                                Default::default()
4462                            }
4463                        )
4464                    }),
4465                )
4466            } else {
4467                (None, None)
4468            };
4469
4470        let post_return = opts.post_return.map(|idx| {
4471            format!(
4472                "postReturn{}{}",
4473                idx.as_u32(),
4474                if is_async {
4475                    "Async"
4476                } else {
4477                    Default::default()
4478                }
4479            )
4480        });
4481
4482        let tracing_prefix = format!(
4483            "[iface=\"{}\", function=\"{}\"]",
4484            iface_name.unwrap_or("<no iface>"),
4485            func.name
4486        );
4487
4488        // Write the function argument list
4489        //
4490        // At this point, only the function preamble (e.g. 'function nameOfFunc()') has been written
4491        self.src.js("(");
4492        let mut params = Vec::new();
4493        let mut first = true;
4494        for i in 0..nparams {
4495            if i == 0
4496                && matches!(
4497                    call_type,
4498                    CallType::FirstArgIsThis | CallType::AsyncFirstArgIsThis
4499                )
4500            {
4501                params.push("this".into());
4502                continue;
4503            }
4504            if !first {
4505                self.src.js(", ");
4506            } else {
4507                first = false;
4508            }
4509            let param = format!("arg{i}");
4510            self.src.js(&param);
4511            params.push(param);
4512        }
4513        uwriteln!(self.src.js, ") {{");
4514        if wrap_async_future_result {
4515            let future_value = self.bindgen.intrinsic(Intrinsic::AsyncFuture(
4516                AsyncFutureIntrinsic::FutureValueClass,
4517            ));
4518            uwriteln!(
4519                self.src.js,
4520                "return new {future_value}(() => (async () => {{"
4521            );
4522        }
4523
4524        // If tracing is enabled, output a function entry tracing message
4525        if self.bindgen.opts.tracing {
4526            let event_fields = func
4527                .params
4528                .iter()
4529                .enumerate()
4530                .map(|(i, p)| format!("{}=${{arguments[{i}]}}", p.name))
4531                .collect::<Vec<String>>();
4532            uwriteln!(
4533                self.src.js,
4534                "console.error(`{tracing_prefix} call {}`);",
4535                event_fields.join(", ")
4536            );
4537        }
4538
4539        // If TLA compat was enabled, ensure that it was initialized
4540        if self.bindgen.opts.tla_compat
4541            && matches!(abi, AbiVariant::GuestExport)
4542            && self.bindgen.opts.instantiation_mode.is_none()
4543        {
4544            let throw_uninitialized = self.bindgen.intrinsic(Intrinsic::ThrowUninitialized);
4545            uwrite!(
4546                self.src.js,
4547                "\
4548                if (!_initialized) {throw_uninitialized}();
4549            "
4550            );
4551        }
4552
4553        // Generate function body
4554        let mut f = FunctionBindgen {
4555            resource_map,
4556            clear_resource_borrows: false,
4557            intrinsics: &mut self.bindgen.all_intrinsics,
4558            valid_lifting_optimization: self.bindgen.opts.valid_lifting_optimization,
4559            flags_as_bigint: self.bindgen.opts.flags_as_bigint,
4560            enum_values_screaming_snake_case: self.bindgen.opts.enum_values_screaming_snake_case,
4561            sizes: &self.sizes,
4562            err: if get_thrown_type(self.resolve, func.result).is_some() {
4563                match abi {
4564                    AbiVariant::GuestExport
4565                    | AbiVariant::GuestExportAsync
4566                    | AbiVariant::GuestExportAsyncStackful => ErrHandling::ThrowResultErr,
4567                    AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
4568                        ErrHandling::ResultCatchHandler
4569                    }
4570                }
4571            } else {
4572                ErrHandling::None
4573            },
4574            block_storage: Vec::new(),
4575            blocks: Vec::new(),
4576            callee,
4577            callee_resource_dynamic: matches!(
4578                call_type,
4579                CallType::CalleeResourceDispatch | CallType::AsyncCalleeResourceDispatch
4580            ),
4581            memory: memory.as_ref(),
4582            realloc: realloc.as_ref(),
4583            tmp: 0,
4584            params,
4585            post_return: post_return.as_ref(),
4586            tracing_prefix: &tracing_prefix,
4587            tracing_enabled: self.bindgen.opts.tracing,
4588            no_component_error_wrapping: self.bindgen.opts.no_component_error_wrapping,
4589            encoding: match opts.string_encoding {
4590                wasmtime_environ::component::StringEncoding::Utf8 => StringEncoding::UTF8,
4591                wasmtime_environ::component::StringEncoding::Utf16 => StringEncoding::UTF16,
4592                wasmtime_environ::component::StringEncoding::CompactUtf16 => {
4593                    StringEncoding::CompactUTF16
4594                }
4595            },
4596            src: source::Source::default(),
4597            resolve: self.resolve,
4598            requires_async_porcelain,
4599            is_async,
4600            wrap_async_future_result,
4601            iface_name,
4602            asmjs: self.bindgen.opts.asmjs,
4603            component_state: Some(FunctionBindgenComponentState {
4604                component_idx: opts.instance,
4605                realloc_fn_idx: if let CanonicalOptionsDataModel::LinearMemory(
4606                    LinearMemoryOptions { realloc, .. },
4607                ) = opts.data_model
4608                {
4609                    realloc
4610                } else {
4611                    None
4612                },
4613                memory_idx: opts.memory(),
4614                callback_fn_idx: opts.callback,
4615            }),
4616            for_import: Some(for_import),
4617        };
4618
4619        let is_guest_export = matches!(
4620            abi,
4621            AbiVariant::GuestExport
4622                | AbiVariant::GuestExportAsync
4623                | AbiVariant::GuestExportAsyncStackful
4624        );
4625        if is_guest_export {
4626            f.start_wasm_export_task();
4627            f.begin_wasm_export_body();
4628        }
4629
4630        // Emit (and visit, via the `FunctionBindgen` object) an abstract sequence of
4631        // instructions which represents the function being generated.
4632        abi::call(
4633            self.resolve,
4634            abi,
4635            match abi {
4636                AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
4637                    LiftLower::LiftArgsLowerResults
4638                }
4639                AbiVariant::GuestExport
4640                | AbiVariant::GuestExportAsync
4641                | AbiVariant::GuestExportAsyncStackful => LiftLower::LowerArgsLiftResults,
4642            },
4643            func,
4644            &mut f,
4645            is_async,
4646        );
4647
4648        if is_guest_export {
4649            f.end_wasm_export_body();
4650        }
4651
4652        // Once visiting has completed, write the contents the `FunctionBindgen` generated to output
4653        self.src.js(&f.src);
4654        if wrap_async_future_result {
4655            self.src.js("})());");
4656        }
4657
4658        // Close function body
4659        self.src.js("}");
4660    }
4661
4662    fn augmented_import_def(&mut self, def: &core::AugmentedImport<'_>) -> String {
4663        match def {
4664            core::AugmentedImport::CoreDef(def) => self.core_def(def),
4665            core::AugmentedImport::Memory { mem, op } => {
4666                let mem = self.core_def(mem);
4667                match op {
4668                    core::AugmentedOp::I32Load => {
4669                        format!(
4670                            "(ptr, off) => new DataView({mem}.buffer).getInt32(ptr + off, true)"
4671                        )
4672                    }
4673                    core::AugmentedOp::I32Load8U => {
4674                        format!(
4675                            "(ptr, off) => new DataView({mem}.buffer).getUint8(ptr + off, true)"
4676                        )
4677                    }
4678                    core::AugmentedOp::I32Load8S => {
4679                        format!("(ptr, off) => new DataView({mem}.buffer).getInt8(ptr + off, true)")
4680                    }
4681                    core::AugmentedOp::I32Load16U => {
4682                        format!(
4683                            "(ptr, off) => new DataView({mem}.buffer).getUint16(ptr + off, true)"
4684                        )
4685                    }
4686                    core::AugmentedOp::I32Load16S => {
4687                        format!(
4688                            "(ptr, off) => new DataView({mem}.buffer).getInt16(ptr + off, true)"
4689                        )
4690                    }
4691                    core::AugmentedOp::I64Load => {
4692                        format!(
4693                            "(ptr, off) => new DataView({mem}.buffer).getBigInt64(ptr + off, true)"
4694                        )
4695                    }
4696                    core::AugmentedOp::F32Load => {
4697                        format!(
4698                            "(ptr, off) => new DataView({mem}.buffer).getFloat32(ptr + off, true)"
4699                        )
4700                    }
4701                    core::AugmentedOp::F64Load => {
4702                        format!(
4703                            "(ptr, off) => new DataView({mem}.buffer).getFloat64(ptr + off, true)"
4704                        )
4705                    }
4706                    core::AugmentedOp::I32Store8 => {
4707                        format!(
4708                            "(ptr, val, offset) => {{
4709                                new DataView({mem}.buffer).setInt8(ptr + offset, val, true);
4710                            }}"
4711                        )
4712                    }
4713                    core::AugmentedOp::I32Store16 => {
4714                        format!(
4715                            "(ptr, val, offset) => {{
4716                                new DataView({mem}.buffer).setInt16(ptr + offset, val, true);
4717                            }}"
4718                        )
4719                    }
4720                    core::AugmentedOp::I32Store => {
4721                        format!(
4722                            "(ptr, val, offset) => {{
4723                                new DataView({mem}.buffer).setInt32(ptr + offset, val, true);
4724                            }}"
4725                        )
4726                    }
4727                    core::AugmentedOp::I64Store => {
4728                        format!(
4729                            "(ptr, val, offset) => {{
4730                                new DataView({mem}.buffer).setBigInt64(ptr + offset, val, true);
4731                            }}"
4732                        )
4733                    }
4734                    core::AugmentedOp::F32Store => {
4735                        format!(
4736                            "(ptr, val, offset) => {{
4737                                new DataView({mem}.buffer).setFloat32(ptr + offset, val, true);
4738                            }}"
4739                        )
4740                    }
4741                    core::AugmentedOp::F64Store => {
4742                        format!(
4743                            "(ptr, val, offset) => {{
4744                                new DataView({mem}.buffer).setFloat64(ptr + offset, val, true);
4745                            }}"
4746                        )
4747                    }
4748                    core::AugmentedOp::MemorySize => {
4749                        format!("ptr => {mem}.buffer.byteLength / 65536")
4750                    }
4751                }
4752            }
4753        }
4754    }
4755
4756    fn core_def(&mut self, def: &CoreDef) -> String {
4757        match def {
4758            CoreDef::Export(e) => self.core_export_var_name(e),
4759            CoreDef::TaskMayBlock => self
4760                .bindgen
4761                .intrinsic(AsyncTaskIntrinsic::CurrentTaskMayBlock.into()),
4762            CoreDef::Trampoline(i) => {
4763                let trampoline = &self.translation.trampolines[*i];
4764                let name = format!("trampoline{}", i.as_u32());
4765                let Some(instance) = self.trampoline_may_leave_instance(trampoline) else {
4766                    return name;
4767                };
4768
4769                self.used_instance_flags.borrow_mut().insert(instance);
4770                if Self::trampoline_checks_may_leave_internally(trampoline) {
4771                    name
4772                } else {
4773                    let guard_may_leave_fn = self
4774                        .bindgen
4775                        .intrinsic(Intrinsic::Component(ComponentIntrinsic::GuardMayLeave));
4776                    format!("{guard_may_leave_fn}({}, {name})", instance.as_u32())
4777                }
4778            }
4779            CoreDef::InstanceFlags(i) => {
4780                // SAFETY: short-lived borrow-mut.
4781                self.used_instance_flags.borrow_mut().insert(*i);
4782                format!("instanceFlags{}", i.as_u32())
4783            }
4784            CoreDef::UnsafeIntrinsic(ui) => match ui {
4785                wasmtime_environ::component::UnsafeIntrinsic::ContextGetI32_0 => {
4786                    let context_get_fn = self
4787                        .bindgen
4788                        .intrinsic(AsyncTaskIntrinsic::ContextGet.into());
4789                    let component_idx = self.init_current_module.expect("missing current module");
4790                    self.context_components.borrow_mut().insert(component_idx);
4791                    format!(
4792                        "{context_get_fn}.bind(null, {{ componentIdx: {}, slot: 0 }})",
4793                        component_idx.as_u32(),
4794                    )
4795                }
4796                wasmtime_environ::component::UnsafeIntrinsic::ContextSetI32_0 => {
4797                    let context_set_fn = self
4798                        .bindgen
4799                        .intrinsic(AsyncTaskIntrinsic::ContextSet.into());
4800                    let component_idx = self.init_current_module.expect("missing current module");
4801                    self.context_components.borrow_mut().insert(component_idx);
4802                    format!(
4803                        "{context_set_fn}.bind(null, {{ componentIdx: {}, slot: 0 }})",
4804                        component_idx.as_u32(),
4805                    )
4806                }
4807                wasmtime_environ::component::UnsafeIntrinsic::ContextGetI32_1 => {
4808                    let context_get_fn = self
4809                        .bindgen
4810                        .intrinsic(AsyncTaskIntrinsic::ContextGet.into());
4811                    let component_idx = self.init_current_module.expect("missing current module");
4812                    self.context_components.borrow_mut().insert(component_idx);
4813                    format!(
4814                        "{context_get_fn}.bind(null, {{ componentIdx: {}, slot: 1 }})",
4815                        component_idx.as_u32(),
4816                    )
4817                }
4818                wasmtime_environ::component::UnsafeIntrinsic::ContextSetI32_1 => {
4819                    let context_set_fn = self
4820                        .bindgen
4821                        .intrinsic(AsyncTaskIntrinsic::ContextSet.into());
4822                    let component_idx = self.init_current_module.expect("missing current module");
4823                    self.context_components.borrow_mut().insert(component_idx);
4824                    format!(
4825                        "{context_set_fn}.bind(null, {{ componentIdx: {}, slot: 1 }})",
4826                        component_idx.as_u32(),
4827                    )
4828                }
4829
4830                // All other intriniscs can be set generically
4831                ui => {
4832                    let idx = ui.index();
4833                    format!("unsafeIntrinsic{idx}")
4834                }
4835            },
4836        }
4837    }
4838
4839    fn core_export_var_name<T>(&self, export: &CoreExport<T>) -> String
4840    where
4841        T: Into<EntityIndex> + Copy,
4842    {
4843        let name = match &export.item {
4844            ExportItem::Index(idx) => {
4845                let module_idx = self
4846                    .instances
4847                    .get(export.instance)
4848                    .expect("unexpectedly missing export instance");
4849                let module = &self
4850                    .modules
4851                    .get(*module_idx)
4852                    .expect("unexpectedly missing module by idx");
4853                let idx = (*idx).into();
4854                module
4855                    .exports()
4856                    .iter()
4857                    .find_map(|(name, i)| if *i == idx { Some(name) } else { None })
4858                    .unwrap()
4859                    .to_string()
4860            }
4861            ExportItem::Name(s) => s.to_string(),
4862        };
4863        let i = export.instance.as_u32() as usize;
4864        let quoted = maybe_quote_member(&name);
4865        format!("exports{i}{quoted}")
4866    }
4867
4868    /// Process the component imports and build mappings
4869    fn process_imports(&mut self) {
4870        let mut import_resource_map = ResourceMap::new();
4871        for (_import_name, (import_idx, _import_path)) in self.component.imports.iter() {
4872            let (import_name, import_type_def) = &self.component.import_types[*import_idx];
4873            let import_world_key = &self
4874                .imports
4875                .get(import_name)
4876                .expect("missing import mapping");
4877            let import_world_item = &self
4878                .resolve
4879                .worlds
4880                .get(self.world)
4881                .expect("missing world")
4882                .imports
4883                .get(*import_world_key)
4884                .expect("missing import in world for import");
4885
4886            // Generate type information for types used in functions
4887            match import_world_item {
4888                WorldItem::Interface { id: iface_id, .. } => {
4889                    let iface = &self.resolve.interfaces[*iface_id];
4890
4891                    // Process functions imported by the iface, which will use (as arg or param)
4892                    // relevant resources
4893                    for (fn_name, iface_fn) in iface.functions.iter() {
4894                        match import_type_def {
4895                            ComponentExtern {
4896                                ty: TypeDef::ComponentInstance(instance_ty),
4897                                ..
4898                            } => {
4899                                if let Some(ComponentExtern {
4900                                    ty: TypeDef::ComponentFunc(type_func_index),
4901                                    ..
4902                                }) = &self.types[*instance_ty].exports.get(fn_name)
4903                                {
4904                                    self.create_resource_fn_map(
4905                                        iface_fn,
4906                                        *type_func_index,
4907                                        &mut import_resource_map,
4908                                    );
4909                                }
4910                            }
4911                            ComponentExtern {
4912                                ty: TypeDef::ComponentFunc(type_func_idx),
4913                                ..
4914                            } => {
4915                                self.create_resource_fn_map(
4916                                    iface_fn,
4917                                    *type_func_idx,
4918                                    &mut import_resource_map,
4919                                );
4920                            }
4921                            _ => {}
4922                        }
4923                    }
4924                }
4925
4926                // Process imported functions directly to build resource maps
4927                WorldItem::Function(func) => {
4928                    let TypeDef::ComponentFunc(func_ty_idx) = &import_type_def.ty else {
4929                        unreachable!("invalid fn export");
4930                    };
4931                    self.create_resource_fn_map(func, *func_ty_idx, &mut import_resource_map);
4932                }
4933                // Simply informational at this point
4934                WorldItem::Type { .. } => {}
4935            }
4936        }
4937
4938        self.resource_imports.extend(import_resource_map);
4939    }
4940
4941    /// Process component exports and build mappings
4942    fn process_exports(&mut self) {
4943        // Since imports may be referred to by exports, we include all imports in the exports array
4944        self.resource_exports.extend(self.resource_imports.clone());
4945
4946        // Process individual component exports
4947        for (export_name, (export_idx, _extern_data)) in self.component.exports.raw_iter() {
4948            let export_name = export_name.as_ref().to_string();
4949            let export = &self.component.export_items[*export_idx];
4950            let world_key = &self.exports[&export_name];
4951            let item = &self.resolve.worlds[self.world].exports[world_key];
4952            let mut export_resource_map = ResourceMap::new();
4953
4954            match export {
4955                Export::LiftedFunction {
4956                    func: def,
4957                    options,
4958                    ty: func_ty,
4959                } => {
4960                    let func = match item {
4961                        WorldItem::Function(f) => f,
4962                        WorldItem::Interface { .. } | WorldItem::Type { .. } => {
4963                            unreachable!("unexpectedly non-function lifted function export")
4964                        }
4965                    };
4966
4967                    self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);
4968
4969                    let local_name = String::from(match func.kind {
4970                        // For resources, we must take the type name (adding `.prototype.<fn name>` later)
4971                        FunctionKind::Constructor(resource_id)
4972                        | FunctionKind::Method(resource_id)
4973                        | FunctionKind::AsyncMethod(resource_id)
4974                        | FunctionKind::Static(resource_id)
4975                        | FunctionKind::AsyncStatic(resource_id) => Instantiator::resource_name(
4976                            self.resolve,
4977                            &mut self.bindgen.local_names,
4978                            resource_id,
4979                            &self.exports_resource_types,
4980                        ),
4981                        // Fore free standing functions we can use the exoprt name directly as a local name
4982                        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
4983                            self.bindgen.local_names.create_once(&export_name)
4984                        }
4985                    });
4986
4987                    let options = self
4988                        .component
4989                        .options
4990                        .get(*options)
4991                        .expect("failed to find options");
4992
4993                    self.export_bindgen(
4994                        &local_name,
4995                        def,
4996                        options,
4997                        func,
4998                        func_ty,
4999                        &export_name,
5000                        &export_resource_map,
5001                    );
5002
5003                    let js_binding_name = match func.kind {
5004                        // For resources, we must take the type name (adding `.prototype.<fn name>` later)
5005                        FunctionKind::Constructor(ty)
5006                        | FunctionKind::Method(ty)
5007                        | FunctionKind::AsyncMethod(ty)
5008                        | FunctionKind::Static(ty)
5009                        | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
5010                            .name
5011                            .as_ref()
5012                            .unwrap()
5013                            .to_upper_camel_case(),
5014                        // For free standing functions we can use the export name directly
5015                        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5016                            export_name.to_lower_camel_case()
5017                        }
5018                    };
5019
5020                    // Add the export binding
5021                    self.bindgen.esm_bindgen.add_export_binding(
5022                        None,
5023                        local_name,
5024                        js_binding_name,
5025                        func,
5026                    );
5027                }
5028
5029                Export::Instance { exports, .. } => {
5030                    let iface_id = match item {
5031                        WorldItem::Interface { id, .. } => *id,
5032                        WorldItem::Function(_) | WorldItem::Type { .. } => {
5033                            unreachable!("unexpectedly non-interface export instance")
5034                        }
5035                    };
5036
5037                    if self.bindgen.opts.flags_as_bigint || self.bindgen.opts.use_namespace_objects
5038                    {
5039                        let mut namespace_locals = BTreeMap::<TypeId, String>::new();
5040                        for (type_name, type_id) in &self.resolve.interfaces[iface_id].types {
5041                            let type_id = crate::dealias(self.resolve, *type_id);
5042                            let kind = &self.resolve.types[type_id].kind;
5043                            let generate = matches!(kind, TypeDefKind::Flags(_))
5044                                && self.bindgen.opts.flags_as_bigint
5045                                || matches!(kind, TypeDefKind::Enum(_) | TypeDefKind::Variant(_))
5046                                    && self.bindgen.opts.use_namespace_objects;
5047                            if !generate {
5048                                continue;
5049                            }
5050
5051                            let local_name = self
5052                                .bindgen
5053                                .local_names
5054                                .create_once(&type_name.to_upper_camel_case())
5055                                .to_string();
5056                            if let Some(existing) = namespace_locals.get(&type_id) {
5057                                uwriteln!(self.src.js, "const {local_name} = {existing};");
5058                            } else {
5059                                uwriteln!(self.src.js, "const {local_name} = Object.freeze({{");
5060                                match kind {
5061                                    TypeDefKind::Flags(flags) => {
5062                                        for (index, flag) in flags.flags.iter().enumerate() {
5063                                            uwriteln!(
5064                                                self.src.js,
5065                                                "{}: 1n << {index}n,",
5066                                                flag.name.to_upper_camel_case()
5067                                            );
5068                                        }
5069                                    }
5070                                    TypeDefKind::Enum(enum_) => {
5071                                        for case in &enum_.cases {
5072                                            let case_value = crate::enum_case_name(
5073                                                &case.name,
5074                                                self.bindgen.opts.enum_values_screaming_snake_case,
5075                                            );
5076                                            uwriteln!(
5077                                                self.src.js,
5078                                                "{}: '{}',",
5079                                                case.name.to_upper_camel_case(),
5080                                                case_value
5081                                            );
5082                                        }
5083                                    }
5084                                    TypeDefKind::Variant(variant) => {
5085                                        for case in &variant.cases {
5086                                            let case_name = case.name.to_upper_camel_case();
5087                                            if case.ty.is_some() {
5088                                                uwriteln!(
5089                                                    self.src.js,
5090                                                    "{case_name}: (val) => ({{ tag: '{}', val }}),",
5091                                                    case.name
5092                                                );
5093                                            } else {
5094                                                uwriteln!(
5095                                                    self.src.js,
5096                                                    "{case_name}: () => ({{ tag: '{}' }}),",
5097                                                    case.name
5098                                                );
5099                                            }
5100                                        }
5101                                    }
5102                                    _ => unreachable!(),
5103                                }
5104                                uwriteln!(self.src.js, "}});");
5105                                namespace_locals.insert(type_id, local_name.clone());
5106                            }
5107                            self.bindgen.esm_bindgen.add_export_constant(
5108                                &export_name,
5109                                local_name,
5110                                type_name.to_upper_camel_case(),
5111                            );
5112                        }
5113                    }
5114
5115                    // Process exported instances
5116                    for (func_name, (export_idx, _extern_data)) in exports.raw_iter() {
5117                        let func_name = func_name.as_ref().to_string();
5118                        let export = &self.component.export_items[*export_idx];
5119
5120                        // Gather function information for all lifted functions in the isntance export
5121                        let (def, options, func_ty) = match export {
5122                            Export::LiftedFunction { func, options, ty } => (func, options, ty),
5123                            Export::Type(_) => continue, // ignored
5124                            _ => unreachable!("unexpected non-lifted function export"),
5125                        };
5126
5127                        let func = &self.resolve.interfaces[iface_id].functions[&func_name];
5128
5129                        self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);
5130
5131                        let local_name = String::from(match func.kind {
5132                            // For resources, we must use the name of the type
5133                            FunctionKind::Constructor(resource_id)
5134                            | FunctionKind::Method(resource_id)
5135                            | FunctionKind::AsyncMethod(resource_id)
5136                            | FunctionKind::Static(resource_id)
5137                            | FunctionKind::AsyncStatic(resource_id) => {
5138                                Instantiator::resource_name(
5139                                    self.resolve,
5140                                    &mut self.bindgen.local_names,
5141                                    resource_id,
5142                                    &self.exports_resource_types,
5143                                )
5144                            }
5145                            // For free standing functions we can use the bare func name
5146                            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5147                                self.bindgen.local_names.create_once(&func_name)
5148                            }
5149                        });
5150
5151                        let options = self
5152                            .component
5153                            .options
5154                            .get(*options)
5155                            .expect("failed to find options");
5156
5157                        self.export_bindgen(
5158                            &local_name,
5159                            def,
5160                            options,
5161                            func,
5162                            func_ty,
5163                            &export_name,
5164                            &export_resource_map,
5165                        );
5166
5167                        // Determine the export func name (this can also be a class name)
5168                        let export_binding_name = match func.kind {
5169                            // For resources, we must use the type name (later adding `.prototype.<actual fn>`)
5170                            FunctionKind::Constructor(ty)
5171                            | FunctionKind::Method(ty)
5172                            | FunctionKind::AsyncMethod(ty)
5173                            | FunctionKind::Static(ty)
5174                            | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
5175                                .name
5176                                .as_ref()
5177                                .unwrap()
5178                                .to_upper_camel_case(),
5179                            // Free standing functions we can use the function name directly
5180                            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5181                                func_name.to_lower_camel_case()
5182                            }
5183                        };
5184
5185                        // Add the export binding
5186                        self.bindgen.esm_bindgen.add_export_binding(
5187                            Some(&export_name),
5188                            local_name,
5189                            export_binding_name,
5190                            func,
5191                        );
5192                    }
5193                }
5194
5195                // ignore type exports for now
5196                Export::Type(_) => {}
5197
5198                // This can't be tested at this time so leave it unimplemented
5199                Export::ModuleStatic { .. } | Export::ModuleImport { .. } => unimplemented!(),
5200            }
5201
5202            // Save information about exported resources for later
5203            self.resource_exports.extend(export_resource_map);
5204        }
5205
5206        self.bindgen.esm_bindgen.populate_export_aliases();
5207    }
5208
5209    #[allow(clippy::too_many_arguments)]
5210    fn export_bindgen(
5211        &mut self,
5212        local_name: &str,
5213        def: &CoreDef,
5214        options: &CanonicalOptions,
5215        func: &Function,
5216        _func_ty_idx: &TypeFuncIndex,
5217        export_name: &String,
5218        export_resource_map: &ResourceMap,
5219    ) {
5220        // Determine whether the function should be generated as async
5221        let requires_async_porcelain = requires_async_porcelain(
5222            FunctionIdentifier::Fn(func),
5223            export_name,
5224            &self.async_exports,
5225        );
5226        // If the function is *also* async lifted, it
5227        if options.async_ {
5228            assert!(
5229                options.post_return.is_none(),
5230                "async function {local_name} (export {export_name}) can't have post return"
5231            );
5232        }
5233
5234        let is_async = is_async_fn(func, options);
5235
5236        let wrap_async_future_result = (requires_async_porcelain || is_async)
5237            && matches!(
5238                func.result.as_ref(),
5239                Some(Type::Id(id))
5240                    if matches!(
5241                        self.resolve.types[crate::dealias(self.resolve, *id)].kind,
5242                        TypeDefKind::Future(_)
5243                    )
5244            );
5245
5246        let maybe_async = if (requires_async_porcelain || is_async) && !wrap_async_future_result {
5247            "async "
5248        } else {
5249            ""
5250        };
5251        let wrapped_function_target = wrap_async_future_result.then(|| match func.kind {
5252            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => local_name.to_string(),
5253            FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => format!(
5254                "{local_name}.prototype.{}",
5255                func.item_name().to_lower_camel_case()
5256            ),
5257            FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => {
5258                format!("{local_name}.{}", func.item_name().to_lower_camel_case())
5259            }
5260            FunctionKind::Constructor(_) => {
5261                unreachable!("constructors cannot return futures")
5262            }
5263        });
5264
5265        // Start building early variable declarations
5266        let core_export_fn = self.core_def(def);
5267        let callee = match self
5268            .bindgen
5269            .local_names
5270            .get_or_create(&core_export_fn, &core_export_fn)
5271        {
5272            (local_name, true) => local_name.to_string(),
5273            (local_name, false) => {
5274                let local_name = local_name.to_string();
5275                uwriteln!(self.src.js, "let {local_name};");
5276                self.bindgen
5277                    .all_core_exported_funcs
5278                    // TODO(breaking): remove requires_async_porcelain  once support
5279                    // for manual async import specification is removed, as p3 has
5280                    // built-in function async coloring
5281                    .push((core_export_fn.clone(), is_async | requires_async_porcelain));
5282                local_name
5283            }
5284        };
5285
5286        let iface_name = if export_name.is_empty() {
5287            None
5288        } else {
5289            Some(export_name)
5290        };
5291
5292        // Write function preamble (everything up to the `(` in `function (...`)
5293        match func.kind {
5294            FunctionKind::Freestanding => {
5295                uwrite!(self.src.js, "\n{maybe_async}function {local_name}")
5296            }
5297            FunctionKind::Method(_) => {
5298                self.ensure_local_resource_class(local_name.to_string());
5299                let method_name = func.item_name().to_lower_camel_case();
5300
5301                uwrite!(
5302                    self.src.js,
5303                    "\n{local_name}.prototype.{method_name} = {maybe_async}function {}",
5304                    if !is_js_reserved_word(&method_name) {
5305                        method_name.to_string()
5306                    } else {
5307                        format!("${method_name}")
5308                    }
5309                );
5310            }
5311            FunctionKind::Static(_) => {
5312                self.ensure_local_resource_class(local_name.to_string());
5313                let method_name = func.item_name().to_lower_camel_case();
5314                uwrite!(
5315                    self.src.js,
5316                    "\n{local_name}.{method_name} = function {}",
5317                    if !is_js_reserved_word(&method_name) {
5318                        method_name.to_string()
5319                    } else {
5320                        format!("${method_name}")
5321                    }
5322                );
5323            }
5324            FunctionKind::Constructor(_) => {
5325                if self.defined_resource_classes.contains(local_name) {
5326                    panic!(
5327                        "Internal error: Resource constructor must be defined before other methods and statics"
5328                    );
5329                }
5330                uwrite!(
5331                    self.src.js,
5332                    "
5333                    class {local_name} {{
5334                        constructor"
5335                );
5336                self.defined_resource_classes.insert(local_name.to_string());
5337            }
5338            FunctionKind::AsyncFreestanding => {
5339                uwrite!(self.src.js, "\n{maybe_async}function {local_name}")
5340            }
5341            FunctionKind::AsyncMethod(_) => {
5342                self.ensure_local_resource_class(local_name.to_string());
5343                let method_name = func.item_name().to_lower_camel_case();
5344                let fn_name = if !is_js_reserved_word(&method_name) {
5345                    method_name.to_string()
5346                } else {
5347                    format!("${method_name}")
5348                };
5349                uwrite!(
5350                    self.src.js,
5351                    "\n{local_name}.prototype.{method_name} = {maybe_async}function {fn_name}",
5352                );
5353            }
5354            FunctionKind::AsyncStatic(_) => {
5355                self.ensure_local_resource_class(local_name.to_string());
5356                let method_name = func.item_name().to_lower_camel_case();
5357                let fn_name = if !is_js_reserved_word(&method_name) {
5358                    method_name.to_string()
5359                } else {
5360                    format!("${method_name}")
5361                };
5362                uwrite!(
5363                    self.src.js,
5364                    "\n{local_name}.{method_name} = {maybe_async}function {fn_name}",
5365                );
5366            }
5367        };
5368
5369        // Perform bindgen
5370        self.bindgen(JsFunctionBindgenArgs {
5371            nparams: func.params.len(),
5372            call_type: match func.kind {
5373                FunctionKind::Method(_) => CallType::FirstArgIsThis,
5374                FunctionKind::AsyncMethod(_) => CallType::AsyncFirstArgIsThis,
5375                FunctionKind::Freestanding
5376                | FunctionKind::Static(_)
5377                | FunctionKind::Constructor(_) => CallType::Standard,
5378                FunctionKind::AsyncFreestanding | FunctionKind::AsyncStatic(_) => {
5379                    CallType::AsyncStandard
5380                }
5381            },
5382            iface_name: iface_name.map(|v| v.as_str()),
5383            callee: &callee,
5384            opts: options,
5385            func,
5386            resource_map: export_resource_map,
5387            abi: AbiVariant::GuestExport,
5388            requires_async_porcelain,
5389            is_async,
5390            wrap_async_future_result,
5391            for_import: false,
5392        });
5393        if let Some(target) = wrapped_function_target {
5394            let async_fn_ctor = self.bindgen.intrinsic(Intrinsic::AsyncFunctionCtor);
5395            uwriteln!(
5396                self.src.js,
5397                "\nObject.setPrototypeOf({target}, {async_fn_ctor}.prototype);"
5398            );
5399        }
5400
5401        // End the function
5402        match func.kind {
5403            FunctionKind::AsyncFreestanding | FunctionKind::Freestanding => self.src.js("\n"),
5404            FunctionKind::AsyncMethod(_)
5405            | FunctionKind::AsyncStatic(_)
5406            | FunctionKind::Method(_)
5407            | FunctionKind::Static(_) => self.src.js(";\n"),
5408            FunctionKind::Constructor(_) => self.src.js("\n}\n"),
5409        }
5410    }
5411}
5412
5413#[derive(Default)]
5414pub struct Source {
5415    pub js: source::Source,
5416    pub js_init: source::Source,
5417}
5418
5419impl Source {
5420    pub fn js(&mut self, s: &str) {
5421        self.js.push_str(s);
5422    }
5423    pub fn js_init(&mut self, s: &str) {
5424        self.js_init.push_str(s);
5425    }
5426}
5427
5428/// Compute the semver "compatibility track" for a version string.
5429/// Mirrors wasmtime's `alternate_lookup_key()` logic.
5430///
5431/// Returns the compat key and parsed `Version` on success.
5432///
5433/// Examples (showing just the key):
5434///   "1.2.3"  → Some(("1", ..))     — major > 0, compat within major
5435///   "0.2.10" → Some(("0.2", ..))   — minor > 0, compat within 0.minor
5436///   "0.0.1"  → None                — no semver compat
5437///   "1.0.0-rc.1" → None            — pre-release, no compat
5438fn semver_compat_key(version_str: &str) -> Option<(String, Version)> {
5439    let version = Version::parse(version_str).ok()?;
5440    if !version.pre.is_empty() {
5441        None
5442    } else if version.major != 0 {
5443        Some((format!("{}", version.major), version))
5444    } else if version.minor != 0 {
5445        Some((format!("0.{}", version.minor), version))
5446    } else {
5447        None
5448    }
5449}
5450
5451fn parse_mapping(mapping: &str) -> (String, Option<String>) {
5452    if mapping.len() > 1
5453        && let Some(hash_idx) = mapping[1..].find('#')
5454    {
5455        return (
5456            mapping[0..hash_idx + 1].to_string(),
5457            Some(mapping[hash_idx + 2..].into()),
5458        );
5459    }
5460    (mapping.into(), None)
5461}
5462
5463fn resolve_wildcard_mapping(key: &str, mapping: &str, impt: &str) -> Option<String> {
5464    let idx = key.find('*')?;
5465    let lhs = &key[..idx];
5466    let rhs = &key[idx + 1..];
5467
5468    if !impt.starts_with(lhs) || !impt.ends_with(rhs) {
5469        return None;
5470    }
5471
5472    let matched_len = impt.len() - lhs.len() - rhs.len();
5473    let matched = &impt[lhs.len()..lhs.len() + matched_len];
5474    Some(mapping.replace('*', matched))
5475}
5476
5477/// Same as [`map_import`], except that when `impt` itself has no mapping and
5478/// the import is a labeled import of a named interface (the component model
5479/// `implements` feature 🏷️), a mapping for the implemented interface id is
5480/// consulted as a fallback.
5481fn map_import_with_implements(
5482    map: &Option<HashMap<String, String>>,
5483    impt: &str,
5484    implements: Option<&str>,
5485) -> (String, Option<String>) {
5486    let (specifier, iface_member) = map_import(map, impt);
5487    if specifier == impt
5488        && iface_member.is_none()
5489        && let Some(target) = implements
5490    {
5491        let (mapped, member) = map_import(map, target);
5492        // An unmapped name is returned with just its version stripped
5493        let target_sans_version = match target.find('@') {
5494            Some(version_idx) => &target[0..version_idx],
5495            None => target,
5496        };
5497        if mapped != target_sans_version || member.is_some() {
5498            return (mapped, member);
5499        }
5500    }
5501    (specifier, iface_member)
5502}
5503
5504fn map_import(map: &Option<HashMap<String, String>>, impt: &str) -> (String, Option<String>) {
5505    let impt_sans_version = match impt.find('@') {
5506        Some(version_idx) => &impt[0..version_idx],
5507        None => impt,
5508    };
5509    if let Some(map) = map.as_ref() {
5510        // 1. Exact match (including version)
5511        if let Some(mapping) = map.get(impt) {
5512            return parse_mapping(mapping);
5513        }
5514
5515        // 2. Exact match without version
5516        if let Some(mapping) = map.get(impt_sans_version) {
5517            return parse_mapping(mapping);
5518        }
5519
5520        // Prefer versioned wildcards over unversioned fallbacks.
5521        for (key, mapping) in map {
5522            if !key.contains('@') {
5523                continue;
5524            }
5525            if let Some(mapping) = resolve_wildcard_mapping(key, mapping, impt) {
5526                return parse_mapping(&mapping);
5527            }
5528        }
5529
5530        // Then apply unversioned wildcards to the version-stripped import.
5531        for (key, mapping) in map {
5532            if key.contains('@') {
5533                continue;
5534            }
5535            if let Some(mapping) = resolve_wildcard_mapping(key, mapping, impt_sans_version) {
5536                return parse_mapping(&mapping);
5537            }
5538        }
5539
5540        // If the import has a parseable version and earlier steps didn't match,
5541        // try matching against map entries with compatible versions.
5542        if let Some(at) = impt.find('@') {
5543            let impt_ver_str = &impt[at + 1..];
5544            if let Some((impt_compat, _)) = semver_compat_key(impt_ver_str) {
5545                let mut best_match: Option<(String, Version)> = None;
5546
5547                for (key, mapping) in map {
5548                    let key_at = match key.find('@') {
5549                        Some(at) => at,
5550                        None => continue,
5551                    };
5552                    let key_base = &key[..key_at];
5553                    let key_ver_str = &key[key_at + 1..];
5554
5555                    let (key_compat, key_ver) = match semver_compat_key(key_ver_str) {
5556                        Some(k) => k,
5557                        None => continue,
5558                    };
5559                    if impt_compat != key_compat {
5560                        continue;
5561                    }
5562
5563                    let resolved = if let Some(mapping) =
5564                        resolve_wildcard_mapping(key_base, mapping, impt_sans_version)
5565                    {
5566                        Some(mapping)
5567                    } else if key_base == impt_sans_version {
5568                        Some(mapping.clone())
5569                    } else {
5570                        None
5571                    };
5572
5573                    if let Some(resolved_mapping) = resolved {
5574                        match &best_match {
5575                            Some((_, prev_ver)) if key_ver <= *prev_ver => {}
5576                            _ => {
5577                                best_match = Some((resolved_mapping, key_ver));
5578                            }
5579                        }
5580                    }
5581                }
5582
5583                if let Some((mapping, _)) = best_match {
5584                    return parse_mapping(&mapping);
5585                }
5586            }
5587        }
5588    }
5589    (impt_sans_version.to_string(), None)
5590}
5591
5592pub fn parse_world_key(name: &str) -> Option<(&str, &str, &str)> {
5593    let registry_idx = name.find(':')?;
5594    let ns = &name[0..registry_idx];
5595    match name.rfind('/') {
5596        Some(sep_idx) => {
5597            let end = if let Some(version_idx) = name.rfind('@') {
5598                version_idx
5599            } else {
5600                name.len()
5601            };
5602            Some((
5603                ns,
5604                &name[registry_idx + 1..sep_idx],
5605                &name[sep_idx + 1..end],
5606            ))
5607        }
5608        // interface is a namespace, function is a default export
5609        None => Some((ns, &name[registry_idx + 1..], "")),
5610    }
5611}
5612
5613fn core_file_name(name: &str, idx: u32) -> String {
5614    let i_str = if idx == 0 {
5615        String::from("")
5616    } else {
5617        (idx + 1).to_string()
5618    };
5619    format!("{name}.core{i_str}.wasm")
5620}
5621
5622/// Encode a [`StringEncoding`] as a string that can be used in Javascript
5623fn string_encoding_js_literal(val: &wasmtime_environ::component::StringEncoding) -> &'static str {
5624    match val {
5625        wasmtime_environ::component::StringEncoding::Utf8 => "'utf8'",
5626        wasmtime_environ::component::StringEncoding::Utf16 => "'utf16'",
5627        wasmtime_environ::component::StringEncoding::CompactUtf16 => "'compact-utf16'",
5628    }
5629}
5630
5631/// Generate the javascript that corresponds to a list of lifting functions for a given list of types
5632///
5633/// # Arguments
5634///
5635/// * `instantiator`
5636/// * `types` - Types for which to generate lift functions
5637/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
5638///
5639pub fn gen_flat_lift_fn_list_js_expr(
5640    instantiator: &mut Instantiator,
5641    types: &[InterfaceType],
5642    extra_resource_map: &Option<&mut ResourceMap>,
5643) -> String {
5644    let mut lift_fns: Vec<String> = Vec::with_capacity(types.len());
5645    for ty in types.iter() {
5646        lift_fns.push(gen_flat_lift_fn_js_expr(
5647            instantiator,
5648            ty,
5649            extra_resource_map,
5650        ));
5651    }
5652    format!("[{}]", lift_fns.join(","))
5653}
5654
5655fn flat_count_js_expr(flat_count: &Option<u8>) -> String {
5656    flat_count
5657        .map(|count| count.to_string())
5658        .unwrap_or_else(|| "null".into())
5659}
5660
5661/// The Canonical ABI `join` operation over flat core types, used when
5662/// computing the flat representation of variant payloads.
5663fn join_flat_core_types(a: &'static str, b: &'static str) -> &'static str {
5664    if a == b {
5665        a
5666    } else if (a == "i32" && b == "f32") || (a == "f32" && b == "i32") {
5667        "i32"
5668    } else {
5669        "i64"
5670    }
5671}
5672
5673/// Compute the flat core types of a type per the Canonical ABI's
5674/// `flatten_type` (32-bit memories), for use in lift/lower metadata.
5675///
5676/// Returns `None` when the type has no flat representation of at most
5677/// [`MAX_FLAT_PARAMS`] core values (such types are passed via memory).
5678fn flat_core_types(
5679    component_types: &ComponentTypes,
5680    ty: &InterfaceType,
5681) -> Option<Vec<&'static str>> {
5682    component_types
5683        .canonical_abi(ty)
5684        .flat_count(MAX_FLAT_PARAMS)?;
5685    let mut flat = Vec::new();
5686    push_flat_core_types(component_types, ty, &mut flat);
5687    Some(flat)
5688}
5689
5690/// Compute the join of the flat core types of a group of variant case
5691/// payloads, per the Canonical ABI's `flatten_variant` (excluding the
5692/// discriminant).
5693fn flat_core_types_variant_payload_join<'a>(
5694    component_types: &ComponentTypes,
5695    cases: impl Iterator<Item = Option<&'a InterfaceType>>,
5696) -> Vec<&'static str> {
5697    let mut joined: Vec<&'static str> = Vec::new();
5698    for maybe_ty in cases {
5699        let Some(ty) = maybe_ty else { continue };
5700        let mut case_flat = Vec::new();
5701        push_flat_core_types(component_types, ty, &mut case_flat);
5702        for (idx, flat_ty) in case_flat.into_iter().enumerate() {
5703            match joined.get_mut(idx) {
5704                Some(existing) => {
5705                    *existing = join_flat_core_types(existing, flat_ty);
5706                }
5707                None => joined.push(flat_ty),
5708            }
5709        }
5710    }
5711    joined
5712}
5713
5714fn push_flat_core_types(
5715    component_types: &ComponentTypes,
5716    ty: &InterfaceType,
5717    flat: &mut Vec<&'static str>,
5718) {
5719    match ty {
5720        InterfaceType::Bool
5721        | InterfaceType::S8
5722        | InterfaceType::U8
5723        | InterfaceType::S16
5724        | InterfaceType::U16
5725        | InterfaceType::S32
5726        | InterfaceType::U32
5727        | InterfaceType::Char
5728        | InterfaceType::Flags(_)
5729        | InterfaceType::Enum(_)
5730        | InterfaceType::Own(_)
5731        | InterfaceType::Borrow(_)
5732        | InterfaceType::Future(_)
5733        | InterfaceType::Stream(_)
5734        | InterfaceType::ErrorContext(_) => flat.push("i32"),
5735
5736        InterfaceType::S64 | InterfaceType::U64 => flat.push("i64"),
5737
5738        InterfaceType::Float32 => flat.push("f32"),
5739        InterfaceType::Float64 => flat.push("f64"),
5740
5741        InterfaceType::String | InterfaceType::List(_) | InterfaceType::Map(_) => {
5742            flat.push("i32");
5743            flat.push("i32");
5744        }
5745
5746        InterfaceType::Record(ty_idx) => {
5747            for field in &component_types[*ty_idx].fields {
5748                push_flat_core_types(component_types, &field.ty, flat);
5749            }
5750        }
5751
5752        InterfaceType::Tuple(ty_idx) => {
5753            for ty in &component_types[*ty_idx].types {
5754                push_flat_core_types(component_types, ty, flat);
5755            }
5756        }
5757
5758        InterfaceType::FixedLengthList(ty_idx) => {
5759            let list_ty = &component_types[*ty_idx];
5760            for _ in 0..list_ty.size {
5761                push_flat_core_types(component_types, &list_ty.element, flat);
5762            }
5763        }
5764
5765        InterfaceType::Variant(ty_idx) => {
5766            let variant_ty = &component_types[*ty_idx];
5767            flat.push("i32");
5768            flat.extend(flat_core_types_variant_payload_join(
5769                component_types,
5770                variant_ty.cases.iter().map(|(_, ty)| ty.as_ref()),
5771            ));
5772        }
5773
5774        InterfaceType::Option(ty_idx) => {
5775            let option_ty = &component_types[*ty_idx];
5776            flat.push("i32");
5777            flat.extend(flat_core_types_variant_payload_join(
5778                component_types,
5779                [None, Some(&option_ty.ty)].into_iter(),
5780            ));
5781        }
5782
5783        InterfaceType::Result(ty_idx) => {
5784            let result_ty = &component_types[*ty_idx];
5785            flat.push("i32");
5786            flat.extend(flat_core_types_variant_payload_join(
5787                component_types,
5788                [result_ty.ok.as_ref(), result_ty.err.as_ref()].into_iter(),
5789            ));
5790        }
5791    }
5792}
5793
5794/// Render a (possibly missing) flat core type list as a JS expression
5795fn flat_core_types_js_expr(flat: &Option<Vec<&'static str>>) -> String {
5796    match flat {
5797        Some(flat) => format!(
5798            "[{}]",
5799            flat.iter()
5800                .map(|t| format!("'{t}'"))
5801                .collect::<Vec<_>>()
5802                .join(",")
5803        ),
5804        None => "null".into(),
5805    }
5806}
5807
5808/// Generate the javascript lifting function for a given type
5809///
5810/// This function will a function object that can be executed with the right
5811/// context in order to perform the lift. For example, running this for bool
5812/// will produce the following:
5813///
5814/// ```js
5815/// _liftFlatBool
5816/// ```
5817///
5818/// This is becasue all it takes to lift a flat boolean is to run the _liftFlatBool function intrinsic.
5819///
5820/// The intrinsic it guaranteed to be in scope once execution time because it wlil be used in the relevant branch.
5821///
5822/// # Arguments
5823///
5824/// * `instantiator`
5825/// * `ty` - The type for which to generate a lift function
5826/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
5827///
5828pub fn gen_flat_lift_fn_js_expr(
5829    instantiator: &mut Instantiator,
5830    ty: &InterfaceType,
5831    extra_resource_map: &Option<&mut ResourceMap>,
5832) -> String {
5833    let component_types = instantiator.types;
5834
5835    match ty {
5836        InterfaceType::Bool => {
5837            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBool));
5838            Intrinsic::Lift(LiftIntrinsic::LiftFlatBool).name().into()
5839        }
5840
5841        InterfaceType::S8 => {
5842            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS8));
5843            Intrinsic::Lift(LiftIntrinsic::LiftFlatS8).name().into()
5844        }
5845
5846        InterfaceType::U8 => {
5847            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU8));
5848            Intrinsic::Lift(LiftIntrinsic::LiftFlatU8).name().into()
5849        }
5850
5851        InterfaceType::S16 => {
5852            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS16));
5853            Intrinsic::Lift(LiftIntrinsic::LiftFlatS16).name().into()
5854        }
5855
5856        InterfaceType::U16 => {
5857            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU16));
5858            Intrinsic::Lift(LiftIntrinsic::LiftFlatU16).name().into()
5859        }
5860
5861        InterfaceType::S32 => {
5862            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS32));
5863            Intrinsic::Lift(LiftIntrinsic::LiftFlatS32).name().into()
5864        }
5865
5866        InterfaceType::U32 => {
5867            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU32));
5868            Intrinsic::Lift(LiftIntrinsic::LiftFlatU32).name().into()
5869        }
5870
5871        InterfaceType::S64 => {
5872            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS64));
5873            Intrinsic::Lift(LiftIntrinsic::LiftFlatS64).name().into()
5874        }
5875
5876        InterfaceType::U64 => {
5877            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU64));
5878            Intrinsic::Lift(LiftIntrinsic::LiftFlatU64).name().into()
5879        }
5880
5881        InterfaceType::Float32 => {
5882            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32));
5883            Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32)
5884                .name()
5885                .into()
5886        }
5887
5888        InterfaceType::Float64 => {
5889            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64));
5890            Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64)
5891                .name()
5892                .into()
5893        }
5894
5895        InterfaceType::Char => {
5896            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatChar));
5897            Intrinsic::Lift(LiftIntrinsic::LiftFlatChar).name().into()
5898        }
5899
5900        InterfaceType::String => {
5901            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny));
5902            Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny)
5903                .name()
5904                .into()
5905        }
5906
5907        InterfaceType::Record(ty_idx) => {
5908            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord));
5909            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord).name();
5910            let record_ty = &component_types[*ty_idx];
5911            let size32 = record_ty.abi.size32;
5912            let align32 = record_ty.abi.align32;
5913            let mut keys_and_lifts_expr = String::from("[");
5914            // For each field we build a list of [name, liftFn, 32bit alignment]
5915            // so that the record lifting function (which is a higher level function)
5916            // can properly generate a function that lifts the fields.
5917            for f in &record_ty.fields {
5918                let field_abi = component_types.canonical_abi(&f.ty);
5919                let field_size32 = field_abi.size32;
5920                let field_align32 = field_abi.align32;
5921                keys_and_lifts_expr.push_str(&format!(
5922                    "['{}', {}, {}, {}],",
5923                    f.name.to_lower_camel_case(),
5924                    gen_flat_lift_fn_js_expr(instantiator, &f.ty, extra_resource_map),
5925                    field_size32,
5926                    field_align32,
5927                ));
5928            }
5929            keys_and_lifts_expr.push(']');
5930            format!(
5931                "{lift_fn}({{ fieldMetas: {keys_and_lifts_expr}, size32: {size32}, align32: {align32} }})"
5932            )
5933        }
5934
5935        InterfaceType::Variant(ty_idx) => {
5936            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant));
5937            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant).name();
5938            let variant_ty = &component_types[*ty_idx];
5939            let variant_flat_count = flat_count_js_expr(&variant_ty.abi.flat_count);
5940            let variant_size32 = variant_ty.abi.size32;
5941            let variant_align32 = variant_ty.abi.align32;
5942            let variant_payload_offset32 = variant_ty.info.payload_offset32;
5943            let variant_payload_flat_types = flat_core_types_js_expr(
5944                &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
5945            );
5946
5947            let mut lift_metas_expr = String::from("[");
5948            for (name, maybe_ty) in &variant_ty.cases {
5949                let (lift_fn_js, case_size32, case_align32, case_flat_count, case_flat_types) =
5950                    match maybe_ty {
5951                        Some(ty) => {
5952                            let cabi_info = component_types.canonical_abi(ty);
5953                            (
5954                                gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map),
5955                                cabi_info.size32.to_string(),
5956                                cabi_info.align32.to_string(),
5957                                cabi_info
5958                                    .flat_count(MAX_FLAT_PARAMS)
5959                                    .map(|v| v.to_string())
5960                                    .unwrap_or_else(|| "null".into()),
5961                                flat_core_types_js_expr(&flat_core_types(component_types, ty)),
5962                            )
5963                        }
5964                        None => (
5965                            "null".into(),
5966                            "0".into(),
5967                            "0".into(),
5968                            "0".into(),
5969                            "[]".into(),
5970                        ),
5971                    };
5972
5973                lift_metas_expr.push_str(&format!(
5974                    "['{name}', {lift_fn_js}, {case_size32}, {case_align32}, {case_flat_count}, {case_flat_types}],",
5975                ));
5976            }
5977            lift_metas_expr.push(']');
5978
5979            format!(
5980                "{lift_fn}({{
5981                     caseMetas: {lift_metas_expr},
5982                     variantSize32: {variant_size32},
5983                     variantAlign32: {variant_align32},
5984                     variantPayloadOffset32: {variant_payload_offset32},
5985                     variantFlatCount: {variant_flat_count},
5986                     variantPayloadFlatTypes: {variant_payload_flat_types},
5987                 }} )"
5988            )
5989        }
5990
5991        InterfaceType::List(ty_idx) => {
5992            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
5993            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
5994            let list_ty = &component_types[*ty_idx];
5995            let lift_fn_expr =
5996                gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
5997            let elem_cabi = component_types.canonical_abi(&list_ty.element);
5998            let elem_align32 = elem_cabi.align32;
5999            let elem_size32 = elem_cabi.size32;
6000            let typed_array = js_typed_array_ctor(&list_ty.element).unwrap_or("undefined");
6001            format!(
6002                "{f}({{
6003                     elemLiftFn: {lift_fn_expr},
6004                     elemAlign32: {elem_align32},
6005                     elemSize32: {elem_size32},
6006                     typedArray: {typed_array},
6007                  }})"
6008            )
6009        }
6010
6011        InterfaceType::FixedLengthList(ty_idx) => {
6012            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
6013            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
6014            let list_ty = &component_types[*ty_idx];
6015            let list_size32 = list_ty.abi.size32;
6016            let list_align32 = list_ty.abi.align32;
6017            let lift_fn_expr =
6018                gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6019            let list_len = list_ty.size;
6020            let elem_cabi = component_types.canonical_abi(&list_ty.element);
6021            let elem_align32 = elem_cabi.align32;
6022            let elem_size32 = elem_cabi.size32;
6023            format!(
6024                "{f}({{
6025                     elemLiftFn: {lift_fn_expr},
6026                     elemAlign32: {elem_align32},
6027                     elemSize32: {elem_size32},
6028                     listSize32: {list_size32},
6029                     listAlign32: {list_align32},
6030                     knownLen: {list_len},
6031                 }})"
6032            )
6033        }
6034
6035        InterfaceType::Tuple(ty_idx) => {
6036            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple));
6037            let tuple_ty = &component_types[*ty_idx];
6038            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple).name();
6039            let size_u32 = tuple_ty.abi.size32;
6040            let align_u32 = tuple_ty.abi.align32;
6041
6042            let mut elem_lifts_expr = String::from("[");
6043            for ty in &tuple_ty.types {
6044                let lift_fn_js = gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map);
6045                let elem_abi = component_types.canonical_abi(ty);
6046                let elem_size32 = elem_abi.size32;
6047                let elem_align32 = elem_abi.align32;
6048                elem_lifts_expr
6049                    .push_str(&format!("[{lift_fn_js}, {elem_size32}, {elem_align32}],"));
6050            }
6051            elem_lifts_expr.push(']');
6052
6053            format!(
6054                "{f}({{ elemLiftFns: {elem_lifts_expr}, size32: {size_u32}, align32: {align_u32} }})"
6055            )
6056        }
6057
6058        InterfaceType::Flags(ty_idx) => {
6059            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags));
6060            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags).name();
6061            let flags_ty = &component_types[*ty_idx];
6062            let size_u32 = flags_ty.abi.size32;
6063            let align_u32 = flags_ty.abi.align32;
6064            let names_expr = format!(
6065                "[{}]",
6066                flags_ty
6067                    .names
6068                    .iter()
6069                    .map(|s| format!("'{}'", s.to_lower_camel_case()))
6070                    .collect::<Vec<_>>()
6071                    .join(",")
6072            );
6073            let num_flags = flags_ty.names.len();
6074            let elem_size = if num_flags <= 8 {
6075                1
6076            } else if num_flags <= 16 {
6077                2
6078            } else {
6079                4
6080            };
6081
6082            format!(
6083                "{f}({{ names: {names_expr}, size32: {size_u32}, align32: {align_u32}, intSizeBytes: {elem_size} }})"
6084            )
6085        }
6086
6087        InterfaceType::Enum(ty_idx) => {
6088            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum));
6089            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum).name();
6090            let enum_ty = &component_types[*ty_idx];
6091            let enum_size32 = enum_ty.abi.size32;
6092            let enum_align32 = enum_ty.abi.align32;
6093            let enum_payload_offset32 = enum_ty.info.payload_offset32;
6094            let enum_flat_count = flat_count_js_expr(&enum_ty.abi.flat_count);
6095
6096            let mut elem_lifts_expr = String::from("[");
6097            for name in &enum_ty.names {
6098                let name = crate::enum_case_name(
6099                    name,
6100                    instantiator.bindgen.opts.enum_values_screaming_snake_case,
6101                );
6102                elem_lifts_expr.push_str(&format!(
6103                    "['{name}', null, {enum_size32}, {enum_align32}, {enum_payload_offset32}],"
6104                ));
6105            }
6106            elem_lifts_expr.push(']');
6107
6108            format!(
6109                r#"
6110                  {f}({{
6111                      caseMetas: {elem_lifts_expr},
6112                      variantSize32: {enum_size32},
6113                      variantAlign32: {enum_align32},
6114                      variantPayloadOffset32: {enum_payload_offset32},
6115                      variantFlatCount: {enum_flat_count},
6116                  }})
6117               "#
6118            )
6119        }
6120
6121        InterfaceType::Option(ty_idx) => {
6122            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOption));
6123            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOption).name();
6124            let option_ty = &component_types[*ty_idx];
6125            let option_payload_offset32 = option_ty.info.payload_offset32;
6126            let option_align32 = option_ty.abi.align32;
6127            let option_size32 = option_ty.abi.size32;
6128            let option_flat_count = flat_count_js_expr(&option_ty.abi.flat_count);
6129            let option_payload_flat_types = flat_core_types_js_expr(
6130                &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
6131            );
6132
6133            let some_ty_abi = component_types.canonical_abi(&option_ty.ty);
6134            let some_ty_flat_count = flat_count_js_expr(&some_ty_abi.flat_count);
6135            let some_ty_size32 = some_ty_abi.size32;
6136            let some_ty_align32 = some_ty_abi.align32;
6137            let some_ty_flat_types =
6138                flat_core_types_js_expr(&flat_core_types(component_types, &option_ty.ty));
6139            let some_ty_lift_fn_js =
6140                gen_flat_lift_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);
6141
6142            format!(
6143                r#"
6144                {f}({{
6145                    caseMetas: [
6146                        ['none', null, 0, 0, 0, [] ],
6147                        ['some', {some_ty_lift_fn_js}, {some_ty_size32}, {some_ty_align32}, {some_ty_flat_count}, {some_ty_flat_types} ],
6148                    ],
6149                    variantSize32: {option_size32},
6150                    variantAlign32: {option_align32},
6151                    variantPayloadOffset32: {option_payload_offset32},
6152                    variantFlatCount: {option_flat_count},
6153                    variantPayloadFlatTypes: {option_payload_flat_types},
6154                }})
6155                "#
6156            )
6157        }
6158
6159        InterfaceType::Result(ty_idx) => {
6160            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatResult));
6161            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatResult).name();
6162            let result_ty = &component_types[*ty_idx];
6163            let result_size32 = result_ty.abi.size32;
6164            let result_align32 = result_ty.abi.align32;
6165            let result_payload_offset32 = result_ty.info.payload_offset32;
6166            let result_flat_count = flat_count_js_expr(&result_ty.abi.flat_count);
6167            let result_payload_flat_types = flat_core_types_js_expr(
6168                &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
6169            );
6170
6171            let mut cases_and_lifts_expr = String::from("[");
6172            if let Some(ok_ty) = result_ty.ok {
6173                let ok_ty_abi = component_types.canonical_abi(&ok_ty);
6174                let ok_ty_size32 = ok_ty_abi.size32;
6175                let ok_ty_align32 = ok_ty_abi.align32;
6176                let ok_flat_count = flat_count_js_expr(&ok_ty_abi.flat_count);
6177                let ok_ty_flat_types =
6178                    flat_core_types_js_expr(&flat_core_types(component_types, &ok_ty));
6179                let ok_ty_lift_fn =
6180                    gen_flat_lift_fn_js_expr(instantiator, &ok_ty, extra_resource_map);
6181                cases_and_lifts_expr.push_str(&format!(
6182                    "['ok', {ok_ty_lift_fn}, {ok_ty_size32}, {ok_ty_align32}, {ok_flat_count}, {ok_ty_flat_types}],",
6183                ))
6184            } else {
6185                cases_and_lifts_expr.push_str("['ok', null, 0, 0, 0, []],");
6186            }
6187
6188            if let Some(err_ty) = &result_ty.err {
6189                let err_ty_abi = component_types.canonical_abi(err_ty);
6190                let err_ty_size32 = err_ty_abi.size32;
6191                let err_ty_align32 = err_ty_abi.align32;
6192                let err_ty_flat_count = flat_count_js_expr(&err_ty_abi.flat_count);
6193                let err_ty_flat_types =
6194                    flat_core_types_js_expr(&flat_core_types(component_types, err_ty));
6195                let err_ty_lift_fn =
6196                    gen_flat_lift_fn_js_expr(instantiator, err_ty, extra_resource_map);
6197                cases_and_lifts_expr.push_str(&format!(
6198                    "['err', {err_ty_lift_fn}, {err_ty_size32}, {err_ty_align32}, {err_ty_flat_count}, {err_ty_flat_types}],",
6199                ))
6200            } else {
6201                cases_and_lifts_expr.push_str("['err', null, 0, 0, 0, []],");
6202            }
6203            cases_and_lifts_expr.push(']');
6204
6205            format!(
6206                r#"
6207                  {lift_fn}({{
6208                      caseMetas: {cases_and_lifts_expr},
6209                      variantSize32: {result_size32},
6210                      variantAlign32: {result_align32},
6211                      variantPayloadOffset32: {result_payload_offset32},
6212                      variantFlatCount: {result_flat_count},
6213                      variantPayloadFlatTypes: {result_payload_flat_types},
6214                  }})
6215                "#
6216            )
6217        }
6218
6219        InterfaceType::Own(ty_idx) => {
6220            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn));
6221            instantiator.add_intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
6222            instantiator.add_intrinsic(Intrinsic::SymbolResourceHandle);
6223            instantiator.add_intrinsic(Intrinsic::SymbolResourceRep);
6224            instantiator.add_intrinsic(Intrinsic::SymbolDispose);
6225            instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
6226            instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
6227            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn).name();
6228            let table_ty = &component_types[*ty_idx];
6229            let resource_component_idx = table_ty.unwrap_concrete_instance();
6230            let component_idx = resource_component_idx.as_u32();
6231            if instantiator
6232                .context_components
6233                .borrow()
6234                .contains(&resource_component_idx)
6235            {
6236                instantiator.add_intrinsic(Intrinsic::Resource(
6237                    ResourceIntrinsic::ResourceDestructorCall,
6238                ));
6239            }
6240            let resource_idx = table_ty.unwrap_concrete_ty();
6241
6242            // Attempt to find information about the owned resource
6243            match instantiator.exports_resource_index_types.get(&resource_idx) {
6244                // Type information not found for this resource index
6245                None => format!(
6246                    r#"{f}({{
6247                       componentIdx: {component_idx},
6248                       classNameFn: () => null,
6249                       createResourceFn: () => {{ throw new Error('invalid/missing resource type data'); }},
6250                    }})
6251                "#,
6252                ),
6253
6254                // If we have a resource type def, find more information about it to generate
6255                // the resource creation function
6256                Some(resource_typedef) => {
6257                    // Look in both the resource exports and the provided extra resource map for the resource
6258                    let (resource_class_name, create_resource_fn_js) = match (
6259                        instantiator.resource_exports.get(resource_typedef),
6260                        extra_resource_map
6261                            .as_ref()
6262                            .and_then(|v| v.get(resource_typedef)),
6263                    ) {
6264                        // Resource type information wasn't found
6265                        (None, None) => (
6266                            "null".into(),
6267                            "() => {{ throw new Error('missing resource information'); }}".into(),
6268                        ),
6269
6270                        // Resource type was found in either resource_exports or extra provided resource map
6271                        (Some(ResourceTable { imported, data }), _)
6272                        | (_, Some(ResourceTable { imported, data })) => match data {
6273                            ResourceData::Guest { .. } => {
6274                                unimplemented!(
6275                                    "owned resources created by guests should must have host-side data"
6276                                )
6277                            }
6278                            ResourceData::Host {
6279                                tid,
6280                                rid,
6281                                component_idx,
6282                                needs_task_context,
6283                                local_name,
6284                                dtor_name,
6285                            } => {
6286                                let empty_func = JsHelperIntrinsic::EmptyFunc.name();
6287                                let symbol_resource_handle = Intrinsic::SymbolResourceHandle.name();
6288                                let symbol_dispose = Intrinsic::SymbolDispose.name();
6289                                let rsc_table_remove =
6290                                    ResourceIntrinsic::ResourceTableRemove.name();
6291                                let tid = tid.as_u32();
6292                                let rsc_flag = ResourceIntrinsic::ResourceTableFlag.name();
6293                                let component_idx = component_idx.as_u32();
6294
6295                                // Mirrors `Instruction::HandleLift` in `function_bindgen.rs`:
6296                                let create_resource_fn_js = if *imported {
6297                                    let symbol_resource_rep = Intrinsic::SymbolResourceRep.name();
6298                                    let rid = rid.as_u32();
6299                                    format!(
6300                                        r#"
6301                                      (handle) => {{
6302                                          const rep = handleTable{tid}[(handle << 1) + 1] & ~{rsc_flag};
6303                                          let resourceObj = captureTable{rid}.get(rep);
6304                                          if (!resourceObj) {{
6305                                              resourceObj = Object.create({local_name}.prototype);
6306                                              Object.defineProperty(resourceObj, {symbol_resource_handle}, {{ writable: true, value: handle }});
6307                                              Object.defineProperty(resourceObj, {symbol_resource_rep}, {{ writable: true, value: rep }});
6308                                          }} else {{
6309                                              captureTable{rid}.delete(rep);
6310                                          }}
6311                                          {rsc_table_remove}(handleTable{tid}, handle);
6312                                          return resourceObj;
6313                                      }}
6314                                     "#
6315                                    )
6316                                } else {
6317                                    let dtor_setup_js = dtor_name
6318                                        .as_ref()
6319                                        .map(|dtor| {
6320                                            let dtor_call = if *needs_task_context {
6321                                                let call_resource_destructor =
6322                                                    ResourceIntrinsic::ResourceDestructorCall.name();
6323                                                format!(
6324                                                    "{call_resource_destructor}({{ componentIdx: {component_idx}, dtor: {dtor}, rep: handleEntry.rep }});"
6325                                                )
6326                                            } else {
6327                                                format!("{dtor}(handleEntry.rep);")
6328                                            };
6329                                            format!(
6330                                             r#"
6331                                               Object.defineProperty(
6332                                                   resourceObj,
6333                                                   {symbol_dispose},
6334                                                   {{
6335                                                       writable: true,
6336                                                       value: function() {{
6337                                                           finalizationRegistry{tid}.unregister(resourceObj);
6338                                                           const handleEntry = {rsc_table_remove}(handleTable{tid}, handle);
6339                                                           resourceObj[{symbol_dispose}] = {empty_func};
6340                                                           resourceObj[{symbol_resource_handle}] = undefined;
6341                                                           {dtor_call}
6342                                                       }}
6343                                                  }}
6344                                              );
6345                                        "#
6346                                            )
6347                                        })
6348                                        .unwrap_or_default();
6349
6350                                    format!(
6351                                        r#"
6352                                      (handle) => {{
6353                                          const resourceObj = Object.create({local_name}.prototype);
6354                                          Object.defineProperty(resourceObj, {symbol_resource_handle}, {{
6355                                              writable: true,
6356                                              value: handle,
6357                                          }});
6358                                          finalizationRegistry{tid}.register(resourceObj, handle, resourceObj);
6359                                          {dtor_setup_js}
6360                                          return resourceObj;
6361                                      }}
6362                                     "#
6363                                    )
6364                                };
6365
6366                                (local_name.to_string(), create_resource_fn_js)
6367                            }
6368                        },
6369                    };
6370
6371                    format!(
6372                        r#"{f}({{
6373                       componentIdx: {component_idx},
6374                       classNameFn: () => {resource_class_name},
6375                       createResourceFn: {create_resource_fn_js},
6376                    }})
6377                "#,
6378                    )
6379                }
6380            }
6381        }
6382
6383        InterfaceType::Borrow(ty_idx) => {
6384            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow));
6385            let table_idx = ty_idx.as_u32();
6386            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow).name();
6387            format!("{f}.bind(null, {table_idx})")
6388        }
6389
6390        InterfaceType::Future(ty_idx) => {
6391            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture));
6392            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture).name();
6393            let table_idx = ty_idx.as_u32();
6394            let table_ty = &component_types[*ty_idx];
6395            let component_idx = table_ty.instance.as_u32();
6396            format!("{f}({{ futureTableIdx: {table_idx}, componentIdx: {component_idx} }})")
6397        }
6398
6399        InterfaceType::Stream(ty_idx) => {
6400            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStream));
6401            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatStream).name();
6402            let table_idx = ty_idx.as_u32();
6403            let table_ty = &component_types[*ty_idx];
6404            let component_idx = table_ty.instance.as_u32();
6405            format!("{f}({{ streamTableIdx: {table_idx}, componentIdx: {component_idx} }})")
6406        }
6407
6408        InterfaceType::ErrorContext(ty_idx) => {
6409            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext));
6410            let table_idx = ty_idx.as_u32();
6411            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext).name();
6412            format!("{f}.bind(null, {table_idx})")
6413        }
6414
6415        InterfaceType::Map(ty_idx) => {
6416            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatMap));
6417            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatMap).name();
6418            let map_ty = &component_types[*ty_idx];
6419            let key_lift = gen_flat_lift_fn_js_expr(instantiator, &map_ty.key, extra_resource_map);
6420            let value_lift =
6421                gen_flat_lift_fn_js_expr(instantiator, &map_ty.value, extra_resource_map);
6422            let entry_size32 = map_ty.entry_abi.size32;
6423            let entry_align32 = map_ty.entry_abi.align32;
6424            let value_offset32 = map_ty.value_offset32;
6425            format!(
6426                "{f}({{
6427                     keyLiftFn: {key_lift},
6428                     valueLiftFn: {value_lift},
6429                     entrySize32: {entry_size32},
6430                     entryAlign32: {entry_align32},
6431                     valueOffset32: {value_offset32},
6432                 }})"
6433            )
6434        }
6435    }
6436}
6437
6438fn js_typed_array_ctor(ty: &InterfaceType) -> Option<&'static str> {
6439    match ty {
6440        InterfaceType::U8 => Some("Uint8Array"),
6441        InterfaceType::S8 => Some("Int8Array"),
6442        InterfaceType::U16 => Some("Uint16Array"),
6443        InterfaceType::S16 => Some("Int16Array"),
6444        InterfaceType::U32 => Some("Uint32Array"),
6445        InterfaceType::S32 => Some("Int32Array"),
6446        InterfaceType::U64 => Some("BigUint64Array"),
6447        InterfaceType::S64 => Some("BigInt64Array"),
6448        InterfaceType::Float32 => Some("Float32Array"),
6449        InterfaceType::Float64 => Some("Float64Array"),
6450        _ => None,
6451    }
6452}
6453
6454/// Generate the javascript that corresponds to a list of lowering functions for a given list of types
6455///
6456/// # Arguments
6457///
6458/// * `instantiator`
6459/// * `types` - Types for which to generate lift functions
6460/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
6461///
6462pub fn gen_flat_lower_fn_list_js_expr(
6463    instantiator: &mut Instantiator,
6464    types: &[InterfaceType],
6465    extra_import_map: &Option<&mut ResourceMap>,
6466) -> String {
6467    let mut lower_fns: Vec<String> = Vec::with_capacity(types.len());
6468    for ty in types.iter() {
6469        lower_fns.push(gen_flat_lower_fn_js_expr(
6470            instantiator,
6471            ty,
6472            extra_import_map,
6473        ));
6474    }
6475    format!("[{}]", lower_fns.join(","))
6476}
6477
6478/// Generate the javascript lowering function for a given type
6479///
6480/// This function will a function object that can be executed with the right
6481/// context in order to perform the lower. For example, running this for bool
6482/// will produce the following:
6483///
6484/// ```js
6485/// _lowerFlatBool
6486/// ```
6487///
6488/// This is becasue all it takes to lower a flat boolean is to run the _lowerFlatBool function intrinsic.
6489///
6490/// The intrinsic it guaranteed to be in scope once execution time because it wlil be used in the relevant branch.
6491///
6492/// # Arguments
6493///
6494/// * `instantiator`
6495/// * `ty` - type for which to generate a lower function
6496/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
6497///
6498pub fn gen_flat_lower_fn_js_expr(
6499    instantiator: &mut Instantiator,
6500    ty: &InterfaceType,
6501    extra_resource_map: &Option<&mut ResourceMap>,
6502) -> String {
6503    let component_types = instantiator.types;
6504    match ty {
6505        InterfaceType::Bool => {
6506            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBool));
6507            Intrinsic::Lower(LowerIntrinsic::LowerFlatBool)
6508                .name()
6509                .into()
6510        }
6511
6512        InterfaceType::S8 => {
6513            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS8));
6514            Intrinsic::Lower(LowerIntrinsic::LowerFlatS8).name().into()
6515        }
6516
6517        InterfaceType::U8 => {
6518            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU8));
6519            Intrinsic::Lower(LowerIntrinsic::LowerFlatU8).name().into()
6520        }
6521
6522        InterfaceType::S16 => {
6523            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS16));
6524            Intrinsic::Lower(LowerIntrinsic::LowerFlatS16).name().into()
6525        }
6526
6527        InterfaceType::U16 => {
6528            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU16));
6529            Intrinsic::Lower(LowerIntrinsic::LowerFlatU16).name().into()
6530        }
6531
6532        InterfaceType::S32 => {
6533            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS32));
6534            Intrinsic::Lower(LowerIntrinsic::LowerFlatS32).name().into()
6535        }
6536
6537        InterfaceType::U32 => {
6538            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU32));
6539            Intrinsic::Lower(LowerIntrinsic::LowerFlatU32).name().into()
6540        }
6541
6542        InterfaceType::S64 => {
6543            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS64));
6544            Intrinsic::Lower(LowerIntrinsic::LowerFlatS64).name().into()
6545        }
6546
6547        InterfaceType::U64 => {
6548            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU64));
6549            Intrinsic::Lower(LowerIntrinsic::LowerFlatU64).name().into()
6550        }
6551
6552        InterfaceType::Float32 => {
6553            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32));
6554            Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32)
6555                .name()
6556                .into()
6557        }
6558
6559        InterfaceType::Float64 => {
6560            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64));
6561            Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64)
6562                .name()
6563                .into()
6564        }
6565
6566        InterfaceType::Char => {
6567            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatChar));
6568            Intrinsic::Lower(LowerIntrinsic::LowerFlatChar)
6569                .name()
6570                .into()
6571        }
6572
6573        InterfaceType::String => {
6574            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny));
6575            Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny)
6576                .name()
6577                .into()
6578        }
6579
6580        InterfaceType::Record(ty_idx) => {
6581            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord));
6582            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord).name();
6583            let record_ty = &component_types[*ty_idx];
6584            let size32 = record_ty.abi.size32;
6585            let align32 = record_ty.abi.align32;
6586            let mut keys_and_lowers_expr = String::from("[");
6587            for f in &record_ty.fields {
6588                // For each field we build a list of [name, lowerFn, 32bit alignment]
6589                // so that the record lowering function (which is a higher level function)
6590                // can properly generate a function that lowers the fields.
6591                let field_abi = component_types.canonical_abi(&f.ty);
6592                let field_size32 = field_abi.size32;
6593                let field_align32 = field_abi.align32;
6594                keys_and_lowers_expr.push_str(&format!(
6595                    "['{}', {}, {}, {} ],",
6596                    f.name.to_lower_camel_case(),
6597                    gen_flat_lower_fn_js_expr(instantiator, &f.ty, &None),
6598                    field_size32,
6599                    field_align32,
6600                ));
6601            }
6602            keys_and_lowers_expr.push(']');
6603            format!(
6604                "{lower_fn}({{ fieldMetas: {keys_and_lowers_expr}, size32: {size32}, align32: {align32} }})"
6605            )
6606        }
6607
6608        InterfaceType::Variant(ty_idx) => {
6609            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant));
6610            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant).name();
6611            let variant_ty = &component_types[*ty_idx];
6612            let variant_flat_count = flat_count_js_expr(&variant_ty.abi.flat_count);
6613            let size32 = variant_ty.abi.size32;
6614            let align32 = variant_ty.abi.align32;
6615            let payload_offset32 = variant_ty.info.payload_offset32;
6616
6617            let mut lower_metas_expr = String::from("[");
6618            for (name, maybe_ty) in variant_ty.cases.iter() {
6619                let (case_size32, case_align32, case_flat_count) = if let Some(iface_ty) = maybe_ty
6620                {
6621                    let cabi_info = component_types.canonical_abi(iface_ty);
6622                    (
6623                        cabi_info.size32.to_string(),
6624                        cabi_info.align32.to_string(),
6625                        cabi_info
6626                            .flat_count(MAX_FLAT_PARAMS)
6627                            .map(|v| v.to_string())
6628                            .unwrap_or_else(|| "null".into()),
6629                    )
6630                } else {
6631                    ("0".into(), "0".into(), "0".into())
6632                };
6633
6634                lower_metas_expr.push_str(&format!(
6635                    "[ '{name}', {}, {case_size32}, {case_align32}, {case_flat_count} ],",
6636                    maybe_ty
6637                        .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, &None))
6638                        .unwrap_or_else(|| "null".into()),
6639                ));
6640            }
6641            lower_metas_expr.push(']');
6642
6643            format!(
6644                "{lower_fn}({{
6645                     caseMetas: {lower_metas_expr},
6646                     variantSize32: {size32},
6647                     variantAlign32: {align32},
6648                     variantPayloadOffset32: {payload_offset32},
6649                     variantFlatCount: {variant_flat_count},
6650                 }} )"
6651            )
6652        }
6653
6654        InterfaceType::List(ty_idx) => {
6655            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
6656            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
6657            let list_ty = &component_types[*ty_idx];
6658            let elem_ty_lower_expr =
6659                gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6660            let elem_cabi = component_types.canonical_abi(&list_ty.element);
6661            let elem_align32 = elem_cabi.align32;
6662            let elem_size32 = elem_cabi.size32;
6663
6664            format!(
6665                "{f}({{
6666                elemLowerFn: {elem_ty_lower_expr},
6667                elemSize32: {elem_size32},
6668                elemAlign32: {elem_align32},
6669            }})"
6670            )
6671        }
6672
6673        InterfaceType::FixedLengthList(ty_idx) => {
6674            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
6675            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
6676            let list_ty = &component_types[*ty_idx];
6677            let elem_ty_lower_expr =
6678                gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6679            let list_len = list_ty.size;
6680            let list_align32 = list_ty.abi.size32;
6681            let list_size32 = list_ty.abi.size32;
6682            let elem_cabi = component_types.canonical_abi(&list_ty.element);
6683            let elem_align32 = elem_cabi.align32;
6684            let elem_size32 = elem_cabi.size32;
6685
6686            format!(
6687                r#"{f}({{
6688                       elemLowerFn: {elem_ty_lower_expr},
6689                       elemAlign32: {elem_align32},
6690                       elemSize32: {elem_size32},
6691                       align32: {list_align32},
6692                       size32: {list_size32},
6693                       knownLen: {list_len},
6694                   }})"#
6695            )
6696        }
6697
6698        InterfaceType::Tuple(ty_idx) => {
6699            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple));
6700            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple).name();
6701            let tuple_ty = &component_types[*ty_idx];
6702            let size_u32 = tuple_ty.abi.size32;
6703            let align_u32 = tuple_ty.abi.align32;
6704
6705            let mut elem_lowers_expr = String::from("[");
6706            for ty in &tuple_ty.types {
6707                let lower_fn_js = gen_flat_lower_fn_js_expr(instantiator, ty, extra_resource_map);
6708                let elem_abi = component_types.canonical_abi(ty);
6709                let elem_size32 = elem_abi.size32;
6710                let elem_align32 = elem_abi.align32;
6711                elem_lowers_expr
6712                    .push_str(&format!("[{lower_fn_js}, {elem_size32}, {elem_align32}],"));
6713            }
6714            elem_lowers_expr.push(']');
6715
6716            format!(
6717                "{f}({{ elemLowerMetas: {elem_lowers_expr}, size32: {size_u32}, align32: {align_u32} }})"
6718            )
6719        }
6720
6721        InterfaceType::Flags(ty_idx) => {
6722            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags));
6723            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags).name();
6724            let flags_ty = &component_types[*ty_idx];
6725            let size32 = flags_ty.abi.size32;
6726            let align32 = flags_ty.abi.align32;
6727            let names_list_js = format!(
6728                "[{}]",
6729                flags_ty
6730                    .names
6731                    .iter()
6732                    .map(|s| format!("'{}'", s.to_lower_camel_case()))
6733                    .collect::<Vec<_>>()
6734                    .join(",")
6735            );
6736            let num_flags = flags_ty.names.len();
6737            let elem_size = if num_flags <= 8 {
6738                1
6739            } else if num_flags <= 16 {
6740                2
6741            } else {
6742                4
6743            };
6744
6745            format!(
6746                "{f}({{ names: {names_list_js}, size32: {size32}, align32: {align32}, intSizeBytes: {elem_size} }})"
6747            )
6748        }
6749
6750        InterfaceType::Enum(ty_idx) => {
6751            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum));
6752            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum).name();
6753            let enum_ty = &component_types[*ty_idx];
6754            let enum_size32 = enum_ty.abi.size32;
6755            let enum_align32 = enum_ty.abi.align32;
6756            let enum_flat_count = flat_count_js_expr(&enum_ty.abi.flat_count);
6757            let enum_payload_offset32 = enum_ty.info.payload_offset32;
6758
6759            let mut elem_lowers_expr = String::from("[");
6760            for name in &enum_ty.names {
6761                let name = crate::enum_case_name(
6762                    name,
6763                    instantiator.bindgen.opts.enum_values_screaming_snake_case,
6764                );
6765                elem_lowers_expr.push_str(&format!(
6766                    "['{name}', null, {enum_size32}, {enum_align32}, {enum_payload_offset32}],"
6767                ));
6768            }
6769            elem_lowers_expr.push(']');
6770
6771            format!(
6772                r#"
6773                  {f}({{
6774                       caseMetas: {elem_lowers_expr},
6775                       variantSize32: {enum_size32},
6776                       variantAlign32: {enum_align32},
6777                       variantPayloadOffset32: {enum_payload_offset32},
6778                       variantFlatCount: {enum_flat_count},
6779                  }})
6780                "#
6781            )
6782        }
6783
6784        InterfaceType::Option(ty_idx) => {
6785            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOption));
6786            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOption).name();
6787            let option_ty = &component_types[*ty_idx];
6788            let option_size32 = option_ty.abi.size32;
6789            let option_align32 = option_ty.abi.align32;
6790            let option_payload_offset32 = option_ty.info.payload_offset32;
6791            let option_flat_count = flat_count_js_expr(&option_ty.abi.flat_count);
6792
6793            let some_ty_abi = component_types.canonical_abi(&option_ty.ty);
6794            let some_ty_flat_count = flat_count_js_expr(&some_ty_abi.flat_count);
6795            let some_ty_size32 = some_ty_abi.size32;
6796            let some_ty_align32 = some_ty_abi.align32;
6797            let some_ty_lower_fn_js =
6798                gen_flat_lower_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);
6799
6800            format!(
6801                r#"
6802                  {f}({{
6803                       caseMetas: [
6804                           [ 'none', null, 0, 0, 0 ],
6805                           [ 'some', {some_ty_lower_fn_js}, {some_ty_size32}, {some_ty_align32}, {some_ty_flat_count}],
6806                       ],
6807                       variantSize32: {option_size32},
6808                       variantAlign32: {option_align32},
6809                       variantPayloadOffset32: {option_payload_offset32},
6810                       variantFlatCount: {option_flat_count},
6811                   }})
6812                "#
6813            )
6814        }
6815
6816        InterfaceType::Result(ty_idx) => {
6817            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatResult));
6818            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatResult).name();
6819            let result_ty = &component_types[*ty_idx];
6820            let result_size32 = result_ty.abi.size32;
6821            let result_align32 = result_ty.abi.align32;
6822            let result_payload_offset32 = result_ty.info.payload_offset32;
6823            let result_flat_count = flat_count_js_expr(&result_ty.abi.flat_count);
6824
6825            let ok_lower_fn_js = result_ty
6826                .ok
6827                .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
6828                .unwrap_or_else(|| "null".into());
6829            let err_lower_fn_js = result_ty
6830                .err
6831                .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
6832                .unwrap_or_else(|| "null".into());
6833
6834            format!(
6835                r#"
6836                   {lower_fn}({{
6837                       caseMetas: [
6838                           [ 'ok', {ok_lower_fn_js}, {result_size32}, {result_align32}, {result_payload_offset32} ],
6839                           [ 'err', {err_lower_fn_js}, {result_size32}, {result_align32}, {result_payload_offset32} ],
6840                       ],
6841                       variantSize32: {result_size32},
6842                       variantAlign32: {result_align32},
6843                       variantPayloadOffset32: {result_payload_offset32},
6844                       variantFlatCount: {result_flat_count},
6845                   }})
6846                "#
6847            )
6848        }
6849
6850        InterfaceType::Own(ty_idx) => {
6851            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn));
6852            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn).name();
6853            let resource_table_ty = &component_types[*ty_idx];
6854            let component_idx = resource_table_ty.unwrap_concrete_instance().as_u32();
6855            let resource_idx = resource_table_ty.unwrap_concrete_ty();
6856
6857            // Retrieve resource information for the given resource, looking
6858            // in both the extra resource map and the instantiator's dedicated resource-to-imports/
6859            // exports maps.
6860            let (_, ResourceTable { imported, data }) = match (
6861                instantiator.imports_resource_index_types.get(&resource_idx),
6862                instantiator.exports_resource_index_types.get(&resource_idx),
6863            ) {
6864                (Some(import_ty_id), _) => {
6865                    let ty = crate::dealias(instantiator.resolve, *import_ty_id);
6866                    let maybe_resource_table =
6867                        instantiator.resource_imports.get(&ty).or(extra_resource_map
6868                            .as_ref()
6869                            .and_then(|m| m.get(import_ty_id)));
6870                    (
6871                        ty,
6872                        maybe_resource_table.expect("missing imported resource table information"),
6873                    )
6874                }
6875                (_, Some(export_ty_id)) => {
6876                    let ty = crate::dealias(instantiator.resolve, *export_ty_id);
6877                    let maybe_resource_table =
6878                        instantiator.resource_exports.get(&ty).or(extra_resource_map
6879                            .as_ref()
6880                            .and_then(|m| m.get(export_ty_id)));
6881                    (
6882                        ty,
6883                        maybe_resource_table.expect("missing exported resource table information"),
6884                    )
6885                }
6886
6887                // If resource was not found in the index type map at all, we're missing resource metadata.
6888                (None, None) => {
6889                    return format!(
6890                        "{f}({{
6891                             componentIdx: {component_idx},
6892                             lowerFn: () => {{ throw new Error('missing/invalid resource metadata'); }}
6893                         }})"
6894                    );
6895                }
6896            };
6897
6898            // Build the function to create the resource, depending on how it was provided
6899            let lower_fn_js = match data {
6900                // If the resource was provided by the host, build the function to create it.
6901                ResourceData::Host {
6902                    tid,
6903                    rid,
6904                    local_name,
6905                    ..
6906                } => {
6907                    let tid = tid.as_u32();
6908                    let rid = rid.as_u32();
6909                    let symbol_resource_rep =
6910                        instantiator.bindgen.intrinsic(Intrinsic::SymbolResourceRep);
6911                    let symbol_resource_handle = instantiator
6912                        .bindgen
6913                        .intrinsic(Intrinsic::SymbolResourceHandle);
6914                    let symbol_dispose = instantiator.bindgen.intrinsic(Intrinsic::SymbolDispose);
6915
6916                    if *imported {
6917                        // If imported (and from the host), we must ensure that the incoming object is of the right
6918                        // instance, then add it to the capture table w/ the right resource ID,
6919                        let create_own_fn = instantiator.bindgen.intrinsic(Intrinsic::Resource(
6920                            ResourceIntrinsic::ResourceTableCreateOwn,
6921                        ));
6922                        format!(
6923                            r#"
6924                              function lowerImportedOwnedHost_{local_name}(obj) {{
6925                                  if (!(obj instanceof {local_name})) {{
6926                                      throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
6927                                  }}
6928                                  let handle = obj[{symbol_resource_handle}];
6929                                  if (!handle) {{
6930                                    const rep = obj[{symbol_resource_rep}] || ++captureCnt{rid};
6931                                    captureTable{rid}.set(rep, obj);
6932                                    handle = {create_own_fn}(handleTable{tid}, rep);
6933                                  }}
6934                                  return handle;
6935                              }}
6936                            "#
6937                        )
6938                    } else {
6939                        // If the resource was not imported (and came from the host), it comes from the component receiving it,
6940                        // and the object should already have a handle associated inside of it (the component must have created it).
6941                        //
6942                        // We disconnect the external connections for dispose and remove the external
6943                        // facing resource handle that was added when lifted out.
6944                        let empty_func = instantiator
6945                            .bindgen
6946                            .intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
6947                        format!(
6948                            r#"
6949                               function lowerExportedOwnedHost_{local_name}(obj) {{
6950                                   let handle = obj[{symbol_resource_handle}];
6951                                   if (!handle) {{
6952                                       throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
6953                                   }}
6954                                   finalizationRegistry{tid}.unregister(obj);
6955                                   obj[{symbol_dispose}] = {empty_func};
6956                                   obj[{symbol_resource_handle}] = undefined;
6957                                   return handle;
6958                               }}
6959                        "#
6960                        )
6961                    }
6962                }
6963
6964                // If the resource was provided by the guest, build the function to create it.
6965                ResourceData::Guest {
6966                    resource_name,
6967                    prefix,
6968                    extra,
6969                } => {
6970                    assert!(
6971                        extra.is_none(),
6972                        "plain resource handles do not carry extra data"
6973                    );
6974
6975                    let upper_camel = resource_name.to_upper_camel_case();
6976                    let lower_camel = resource_name.to_lower_camel_case();
6977                    let prefix = prefix.as_deref().unwrap_or("");
6978
6979                    if *imported {
6980                        // If we get a resource that is provided by the host, then
6981                        // it should already have an external-facing resource handle on it.
6982                        let symbol_resource_handle = instantiator
6983                            .bindgen
6984                            .intrinsic(Intrinsic::SymbolResourceHandle);
6985                        format!(
6986                            r#"
6987                              function lowerImportedOwnedGuest_{upper_camel}(obj) {{
6988                                  const handle = obj[{symbol_resource_handle}];
6989                                  finalizationRegistry_import${prefix}{lower_camel}.unregister(obj);
6990                                  return handle;
6991                              }}
6992                            "#
6993                        )
6994                    } else {
6995                        // If we get a resource that was exported by the guest and is being lowered in,
6996                        // we can check that the object is of the right kidn of instance, and
6997                        // create rep for it if one does not already exist.
6998                        let symbol_resource_handle = instantiator
6999                            .bindgen
7000                            .intrinsic(Intrinsic::SymbolResourceHandle);
7001                        format!(
7002                            r#"
7003                              function lowerExportedOwnedGuest_{upper_camel}(obj) {{
7004                                  if (!(obj instanceof {upper_camel})) {{
7005                                    throw new TypeError('Resource error: Not a valid \"{upper_camel}\" resource.');
7006                                  }}
7007                                  let handle = obj[{symbol_resource_handle}];
7008                                  if (handle === undefined) {{
7009                                      const localRep = repCnt++;
7010                                      repTable.set(localRep, {{ rep: obj, own: true }});
7011                                      handle = $resource_{prefix}new${lower_camel}(localRep);
7012                                      obj[{symbol_resource_handle}] = handle;
7013                                      finalizationRegistry_export${prefix}{lower_camel}.register(obj, handle, obj);
7014                                  }}
7015                                  return handle;
7016                              }}
7017                            "#
7018                        )
7019                    }
7020                }
7021            };
7022
7023            format!(
7024                "{f}({{
7025                     componentIdx: {component_idx},
7026                     lowerFn: {lower_fn_js},
7027                 }})"
7028            )
7029        }
7030
7031        InterfaceType::Borrow(ty_idx) => {
7032            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow));
7033            let table_idx = ty_idx.as_u32();
7034            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow).name();
7035            format!("{f}.bind(null, {table_idx})")
7036        }
7037
7038        InterfaceType::Future(ty_idx) => {
7039            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture));
7040            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture).name();
7041            let table_idx = ty_idx.as_u32();
7042            let table_ty = &component_types[*ty_idx];
7043            let component_idx = table_ty.instance.as_u32();
7044            let future_ty_idx = table_ty.ty;
7045            let future_ty = &component_types[future_ty_idx];
7046            let payload = future_ty.payload;
7047            let payload_ty_name_js = future_ty
7048                .payload
7049                .map(|iface_ty| format!("'{iface_ty:?}'"))
7050                .unwrap_or_else(|| "null".into());
7051
7052            // Gather element metadata
7053            let (
7054                payload_size32,
7055                payload_align32,
7056                payload_flat_count_js,
7057                payload_lift_fn_js,
7058                payload_lower_fn_js,
7059                is_borrowed,
7060                is_none_type,
7061                is_numeric_type,
7062                is_async_value,
7063            ) = match payload {
7064                None => (
7065                    0,
7066                    0,
7067                    "0".into(),
7068                    "() => {{ throw new Error('empty future payload'); }}".into(),
7069                    "() => {{ throw new Error('empty future payload'); }}".into(),
7070                    false,
7071                    true,
7072                    false,
7073                    false,
7074                ),
7075                Some(payload_ty) => {
7076                    let cabi = instantiator.types.canonical_abi(&payload_ty);
7077                    (
7078                        cabi.size32,
7079                        cabi.align32,
7080                        cabi.flat_count
7081                            .map(|v| format!("{v}"))
7082                            .unwrap_or_else(|| "null".into()),
7083                        gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7084                        gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7085                        matches!(payload_ty, InterfaceType::Borrow(_)),
7086                        false,
7087                        matches!(
7088                            payload_ty,
7089                            InterfaceType::U8
7090                                | InterfaceType::U16
7091                                | InterfaceType::U32
7092                                | InterfaceType::U64
7093                                | InterfaceType::S8
7094                                | InterfaceType::S16
7095                                | InterfaceType::S32
7096                                | InterfaceType::S64
7097                                | InterfaceType::Float32
7098                                | InterfaceType::Float64
7099                        ),
7100                        matches!(
7101                            payload_ty,
7102                            InterfaceType::Stream(_) | InterfaceType::Future(_)
7103                        ),
7104                    )
7105                }
7106            };
7107
7108            // Determine the level of future nesting
7109            let mut future_nesting_level = 0;
7110            let mut payload_ty = future_ty.payload;
7111            while let Some(InterfaceType::Future(inner_ty)) = payload_ty {
7112                future_nesting_level += 1;
7113                payload_ty = component_types[component_types[inner_ty].ty].payload;
7114            }
7115
7116            format!(
7117                r#"{f}({{
7118                       futureTableIdx: {table_idx},
7119                       futureNestingLevel: {future_nesting_level},
7120                       componentIdx: {component_idx},
7121                       elemMeta: {{
7122                           liftFn: {payload_lift_fn_js},
7123                           lowerFn: {payload_lower_fn_js},
7124                           payloadTypeName: {payload_ty_name_js},
7125                           isNone: {is_none_type},
7126                           isNumeric: {is_numeric_type},
7127                           isBorrowed: {is_borrowed},
7128                           isAsyncValue: {is_async_value},
7129                           flatCount: {payload_flat_count_js},
7130                           align32: {payload_align32},
7131                           size32: {payload_size32},
7132                       }},
7133                   }})
7134                "#
7135            )
7136        }
7137
7138        InterfaceType::Stream(ty_idx) => {
7139            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStream));
7140            let table_idx = ty_idx.as_u32();
7141            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatStream).name();
7142            let table_ty = &component_types[*ty_idx];
7143            let component_idx = table_ty.instance.as_u32();
7144            let stream_ty_idx = table_ty.ty;
7145            let stream_ty = &component_types[stream_ty_idx];
7146            let payload = stream_ty.payload;
7147            let payload_ty_name_js = stream_ty
7148                .payload
7149                .map(|iface_ty| format!("'{iface_ty:?}'"))
7150                .unwrap_or_else(|| "null".into());
7151
7152            // TODO(fix): payload u8 should be special cased here
7153
7154            let (
7155                payload_size32,
7156                payload_align32,
7157                payload_flat_count_js,
7158                payload_lift_fn_js,
7159                payload_lower_fn_js,
7160                is_borrowed,
7161                is_none_type,
7162                is_numeric_type,
7163                is_async_value,
7164                typed_array_js,
7165            ) = match payload {
7166                None => (
7167                    0,
7168                    0,
7169                    "0".into(),
7170                    "() => {{ throw new Error('empty stream payload'); }}".into(),
7171                    "() => {{ throw new Error('empty stream payload'); }}".into(),
7172                    false,
7173                    true,
7174                    false,
7175                    false,
7176                    "undefined",
7177                ),
7178                Some(payload_ty) => {
7179                    let cabi = instantiator.types.canonical_abi(&payload_ty);
7180                    (
7181                        cabi.size32,
7182                        cabi.align32,
7183                        cabi.flat_count
7184                            .map(|v| format!("{v}"))
7185                            .unwrap_or_else(|| "null".into()),
7186                        gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7187                        gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7188                        matches!(payload_ty, InterfaceType::Borrow(_)),
7189                        false,
7190                        matches!(
7191                            payload_ty,
7192                            InterfaceType::U8
7193                                | InterfaceType::U16
7194                                | InterfaceType::U32
7195                                | InterfaceType::U64
7196                                | InterfaceType::S8
7197                                | InterfaceType::S16
7198                                | InterfaceType::S32
7199                                | InterfaceType::S64
7200                                | InterfaceType::Float32
7201                                | InterfaceType::Float64
7202                        ),
7203                        matches!(
7204                            payload_ty,
7205                            InterfaceType::Stream(_) | InterfaceType::Future(_)
7206                        ),
7207                        js_typed_array_ctor(&payload_ty).unwrap_or("undefined"),
7208                    )
7209                }
7210            };
7211
7212            format!(
7213                r#"{f}({{
7214                       streamTableIdx: {table_idx},
7215                       componentIdx: {component_idx},
7216                       elemMeta: {{
7217                           liftFn: {payload_lift_fn_js},
7218                           lowerFn: {payload_lower_fn_js},
7219                           payloadTypeName: {payload_ty_name_js},
7220                           isNone: {is_none_type},
7221                           isNumeric: {is_numeric_type},
7222                           isBorrowed: {is_borrowed},
7223                           isAsyncValue: {is_async_value},
7224                           typedArray: {typed_array_js},
7225                           flatCount: {payload_flat_count_js},
7226                           align32: {payload_align32},
7227                           size32: {payload_size32},
7228                       }},
7229                   }})
7230                "#
7231            )
7232        }
7233
7234        InterfaceType::ErrorContext(ty_idx) => {
7235            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext));
7236            let table_idx = ty_idx.as_u32();
7237            let lower_flat_err_ctx_fn =
7238                Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext).name();
7239            format!("{lower_flat_err_ctx_fn}.bind(null, {table_idx})")
7240        }
7241
7242        InterfaceType::Map(ty_idx) => {
7243            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatMap));
7244            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatMap).name();
7245            let map_ty = &component_types[*ty_idx];
7246            let key_lower =
7247                gen_flat_lower_fn_js_expr(instantiator, &map_ty.key, extra_resource_map);
7248            let value_lower =
7249                gen_flat_lower_fn_js_expr(instantiator, &map_ty.value, extra_resource_map);
7250            let entry_size32 = map_ty.entry_abi.size32;
7251            let entry_align32 = map_ty.entry_abi.align32;
7252            let value_offset32 = map_ty.value_offset32;
7253            format!(
7254                "{f}({{
7255                     keyLowerFn: {key_lower},
7256                     valueLowerFn: {value_lower},
7257                     entrySize32: {entry_size32},
7258                     entryAlign32: {entry_align32},
7259                     valueOffset32: {value_offset32},
7260                 }})"
7261            )
7262        }
7263    }
7264}
7265
7266#[cfg(test)]
7267mod tests {
7268    use super::*;
7269
7270    /// Helper to extract just the compat key string for cleaner test assertions.
7271    fn compat_key(version_str: &str) -> Option<String> {
7272        semver_compat_key(version_str).map(|(key, _)| key)
7273    }
7274
7275    #[test]
7276    fn test_semver_compat_key() {
7277        assert_eq!(compat_key("1.0.0"), Some("1".into()));
7278        assert_eq!(compat_key("1.2.3"), Some("1".into()));
7279        assert_eq!(compat_key("2.0.0"), Some("2".into()));
7280        assert_eq!(compat_key("0.2.0"), Some("0.2".into()));
7281        assert_eq!(compat_key("0.2.10"), Some("0.2".into()));
7282        assert_eq!(compat_key("0.1.0"), Some("0.1".into()));
7283        assert_eq!(compat_key("0.0.1"), None);
7284        assert_eq!(compat_key("1.0.0-rc.1"), None);
7285        assert_eq!(compat_key("0.2.0-pre"), None);
7286        assert_eq!(compat_key("not-a-version"), None);
7287    }
7288
7289    #[test]
7290    fn test_semver_compat_key_returns_parsed_version() {
7291        let (key, ver) = semver_compat_key("1.2.3").unwrap();
7292        assert_eq!(key, "1");
7293        assert_eq!(ver, Version::new(1, 2, 3));
7294    }
7295
7296    #[test]
7297    fn test_map_import_exact_match() {
7298        let mut map = HashMap::new();
7299        map.insert("wasi:http/types@0.2.0".into(), "./http.js#types".into());
7300        let map = Some(map);
7301        assert_eq!(
7302            map_import(&map, "wasi:http/types@0.2.0"),
7303            ("./http.js".into(), Some("types".into()))
7304        );
7305    }
7306
7307    #[test]
7308    fn test_map_import_sans_version_match() {
7309        let mut map = HashMap::new();
7310        map.insert("wasi:http/types".into(), "./http.js".into());
7311        let map = Some(map);
7312        assert_eq!(
7313            map_import(&map, "wasi:http/types@0.2.10"),
7314            ("./http.js".into(), None)
7315        );
7316    }
7317
7318    #[test]
7319    fn test_map_import_wildcard_sans_version() {
7320        // Unversioned wildcard key matches via version-stripped path (pre-existing logic)
7321        let mut map = HashMap::new();
7322        map.insert("wasi:http/*".into(), "./http.js#*".into());
7323        let map = Some(map);
7324        assert_eq!(
7325            map_import(&map, "wasi:http/types@0.2.10"),
7326            ("./http.js".into(), Some("types".into()))
7327        );
7328    }
7329
7330    #[test]
7331    fn test_map_import_semver_exact_key() {
7332        // Map has @0.2.0, import is @0.2.10 — should match via semver
7333        let mut map = HashMap::new();
7334        map.insert("wasi:http/types@0.2.0".into(), "./http.js".into());
7335        let map = Some(map);
7336        assert_eq!(
7337            map_import(&map, "wasi:http/types@0.2.10"),
7338            ("./http.js".into(), None)
7339        );
7340    }
7341
7342    #[test]
7343    fn test_map_import_semver_wildcard_key() {
7344        // Map has wasi:http/*@0.2.0, import is @0.2.10 — should match via semver
7345        let mut map = HashMap::new();
7346        map.insert("wasi:http/*@0.2.1".into(), "./http.js#*".into());
7347        let map = Some(map);
7348        assert_eq!(
7349            map_import(&map, "wasi:http/types@0.2.10"),
7350            ("./http.js".into(), Some("types".into()))
7351        );
7352    }
7353
7354    #[test]
7355    fn test_map_import_semver_lower_import_version() {
7356        // Import version (0.2.1) is lower than map entry (0.2.10) — same compat track
7357        let mut map = HashMap::new();
7358        map.insert("wasi:http/types@0.2.10".into(), "./http.js".into());
7359        let map = Some(map);
7360        assert_eq!(
7361            map_import(&map, "wasi:http/types@0.2.1"),
7362            ("./http.js".into(), None)
7363        );
7364    }
7365
7366    #[test]
7367    fn test_map_import_semver_no_cross_minor() {
7368        // 0.2.x should NOT match 0.3.x
7369        let mut map = HashMap::new();
7370        map.insert("wasi:http/types@0.3.0".into(), "./http.js".into());
7371        let map = Some(map);
7372        assert_eq!(
7373            map_import(&map, "wasi:http/types@0.2.10"),
7374            ("wasi:http/types".into(), None)
7375        );
7376    }
7377
7378    #[test]
7379    fn test_map_import_semver_prefers_highest() {
7380        // Multiple compatible versions — should prefer highest
7381        let mut map = HashMap::new();
7382        map.insert("wasi:http/types@0.2.1".into(), "./http-old.js".into());
7383        map.insert("wasi:http/types@0.2.5".into(), "./http-new.js".into());
7384        let map = Some(map);
7385        assert_eq!(
7386            map_import(&map, "wasi:http/types@0.2.10"),
7387            ("./http-new.js".into(), None)
7388        );
7389    }
7390
7391    #[test]
7392    fn test_map_import_no_match_prerelease() {
7393        let mut map = HashMap::new();
7394        map.insert("wasi:http/types@0.2.0-rc.1".into(), "./http.js".into());
7395        let map = Some(map);
7396        assert_eq!(
7397            map_import(&map, "wasi:http/types@0.2.0"),
7398            ("wasi:http/types".into(), None)
7399        );
7400    }
7401
7402    #[test]
7403    fn test_map_import_prerelease_versioned_wildcard_wins_over_unversioned_wildcard() {
7404        // p3 imports (pre-release version) must route to the
7405        // version-pinned wildcard, not the unversioned p2 fallback.
7406        let mut map = HashMap::new();
7407        map.insert(
7408            "wasi:cli/*".into(),
7409            "@bytecodealliance/preview2-shim/cli#*".into(),
7410        );
7411        map.insert(
7412            "wasi:cli/*@0.3.0".into(),
7413            "@bytecodealliance/preview3-shim/cli#*".into(),
7414        );
7415        let map = Some(map);
7416        assert_eq!(
7417            map_import(&map, "wasi:cli/stdout@0.3.0"),
7418            (
7419                "@bytecodealliance/preview3-shim/cli".into(),
7420                Some("stdout".into())
7421            )
7422        );
7423        // Same map, p2 import should still resolve to preview2-shim.
7424        assert_eq!(
7425            map_import(&map, "wasi:cli/stdout@0.2.6"),
7426            (
7427                "@bytecodealliance/preview2-shim/cli".into(),
7428                Some("stdout".into())
7429            )
7430        );
7431        // Unversioned import should also flow to p2.
7432        assert_eq!(
7433            map_import(&map, "wasi:cli/stdout"),
7434            (
7435                "@bytecodealliance/preview2-shim/cli".into(),
7436                Some("stdout".into())
7437            )
7438        );
7439    }
7440
7441    #[test]
7442    fn test_map_import_no_match_zero_zero() {
7443        let mut map = HashMap::new();
7444        map.insert("wasi:http/types@0.0.1".into(), "./http.js".into());
7445        let map = Some(map);
7446        assert_eq!(
7447            map_import(&map, "wasi:http/types@0.0.2"),
7448            ("wasi:http/types".into(), None)
7449        );
7450    }
7451
7452    #[test]
7453    fn test_map_import_semver_major_version() {
7454        // Major version compat: 1.0.0 and 1.2.3 share compat key "1"
7455        let mut map = HashMap::new();
7456        map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
7457        let map = Some(map);
7458        assert_eq!(
7459            map_import(&map, "wasi:http/types@1.2.3"),
7460            ("./http.js".into(), None)
7461        );
7462    }
7463
7464    #[test]
7465    fn test_map_import_semver_no_cross_major() {
7466        // 1.x.y should NOT match 2.x.y
7467        let mut map = HashMap::new();
7468        map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
7469        let map = Some(map);
7470        assert_eq!(
7471            map_import(&map, "wasi:http/types@2.0.0"),
7472            ("wasi:http/types".into(), None)
7473        );
7474    }
7475
7476    #[test]
7477    fn test_map_import_no_map() {
7478        // No map provided — returns import sans version
7479        assert_eq!(
7480            map_import(&None, "wasi:http/types@0.2.0"),
7481            ("wasi:http/types".into(), None)
7482        );
7483    }
7484
7485    #[test]
7486    fn test_map_import_no_map_unversioned() {
7487        // No map, no version — returns import as-is
7488        assert_eq!(
7489            map_import(&None, "wasi:http/types"),
7490            ("wasi:http/types".into(), None)
7491        );
7492    }
7493
7494    #[test]
7495    fn test_parse_mapping_with_hash() {
7496        assert_eq!(
7497            parse_mapping("./http.js#types"),
7498            ("./http.js".into(), Some("types".into()))
7499        );
7500    }
7501
7502    #[test]
7503    fn test_parse_mapping_without_hash() {
7504        assert_eq!(parse_mapping("./http.js"), ("./http.js".into(), None));
7505    }
7506
7507    #[test]
7508    fn test_parse_mapping_leading_hash() {
7509        // Leading '#' should not be treated as a separator
7510        assert_eq!(parse_mapping("#foo"), ("#foo".into(), None));
7511    }
7512
7513    #[test]
7514    fn test_parse_mapping_empty() {
7515        assert_eq!(parse_mapping(""), ("".into(), None));
7516    }
7517}