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