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