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