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