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