Skip to main content

js_component_bindgen/
transpile_bindgen.rs

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