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            skip_fn_call_task_management: false,
4904            clear_resource_borrows: false,
4905            intrinsics: &mut self.bindgen.all_intrinsics,
4906            valid_lifting_optimization: self.bindgen.opts.valid_lifting_optimization,
4907            flags_as_bigint: self.bindgen.opts.flags_as_bigint,
4908            enum_values_screaming_snake_case: self.bindgen.opts.enum_values_screaming_snake_case,
4909            sizes: &self.sizes,
4910            err: if get_thrown_type(self.resolve, func.result).is_some() {
4911                match abi {
4912                    AbiVariant::GuestExport
4913                    | AbiVariant::GuestExportAsync
4914                    | AbiVariant::GuestExportAsyncStackful => ErrHandling::ThrowResultErr,
4915                    AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
4916                        ErrHandling::ResultCatchHandler
4917                    }
4918                }
4919            } else {
4920                ErrHandling::None
4921            },
4922            block_storage: Vec::new(),
4923            blocks: Vec::new(),
4924            callee,
4925            callee_resource_dynamic: matches!(
4926                call_type,
4927                CallType::CalleeResourceDispatch | CallType::AsyncCalleeResourceDispatch
4928            ),
4929            memory: memory.as_ref(),
4930            realloc: realloc.as_ref(),
4931            dealloc: None,
4932            tmp: 0,
4933            params,
4934            post_return: post_return.as_ref(),
4935            tracing_prefix: &tracing_prefix,
4936            tracing_enabled: self.bindgen.opts.tracing,
4937            no_component_error_wrapping: self.bindgen.opts.no_component_error_wrapping,
4938            encoding: match opts.string_encoding {
4939                wasmtime_environ::component::StringEncoding::Utf8 => StringEncoding::UTF8,
4940                wasmtime_environ::component::StringEncoding::Utf16 => StringEncoding::UTF16,
4941                wasmtime_environ::component::StringEncoding::CompactUtf16 => {
4942                    StringEncoding::CompactUTF16
4943                }
4944            },
4945            src: source::Source::default(),
4946            resolve: self.resolve,
4947            requires_async_porcelain,
4948            is_async,
4949            canonical_abi_async: opts.async_,
4950            wrap_async_future_result,
4951            result_ty: func.result.as_ref(),
4952            iface_name,
4953            asmjs: self.bindgen.opts.asmjs,
4954            component_state: Some(FunctionBindgenComponentState {
4955                component_idx: opts.instance,
4956                realloc_fn_idx: if let CanonicalOptionsDataModel::LinearMemory(
4957                    LinearMemoryOptions { realloc, .. },
4958                ) = opts.data_model
4959                {
4960                    realloc
4961                } else {
4962                    None
4963                },
4964                memory_idx: opts.memory(),
4965                callback_fn_idx: opts.callback,
4966            }),
4967            for_import: Some(for_import),
4968        };
4969
4970        let is_guest_export = matches!(
4971            abi,
4972            AbiVariant::GuestExport
4973                | AbiVariant::GuestExportAsync
4974                | AbiVariant::GuestExportAsyncStackful
4975        );
4976        if is_guest_export {
4977            f.start_wasm_export_task();
4978            f.begin_wasm_export_body();
4979        }
4980
4981        // Emit (and visit, via the `FunctionBindgen` object) an abstract sequence of
4982        // instructions which represents the function being generated.
4983        abi::call(
4984            self.resolve,
4985            abi,
4986            match abi {
4987                AbiVariant::GuestImport | AbiVariant::GuestImportAsync => {
4988                    LiftLower::LiftArgsLowerResults
4989                }
4990                AbiVariant::GuestExport
4991                | AbiVariant::GuestExportAsync
4992                | AbiVariant::GuestExportAsyncStackful => LiftLower::LowerArgsLiftResults,
4993            },
4994            func,
4995            &mut f,
4996            if for_import { is_async } else { opts.async_ },
4997        );
4998
4999        if is_guest_export {
5000            f.end_wasm_export_body();
5001        }
5002
5003        // Once visiting has completed, write the contents the `FunctionBindgen` generated to output
5004        self.src.js(&f.src);
5005        if wrap_async_future_result {
5006            self.src.js("})());");
5007        }
5008
5009        // Close function body
5010        self.src.js("}");
5011    }
5012
5013    fn augmented_import_def(&mut self, def: &core::AugmentedImport<'_>) -> String {
5014        match def {
5015            core::AugmentedImport::CoreDef(def) => {
5016                let is_non_suspending_function =
5017                    self.core_def_is_function(def) && !self.core_def_may_suspend(def);
5018                let value = self.core_def(def);
5019                if is_non_suspending_function {
5020                    format!("Object.assign({value}, {{ _jcoMaySuspend: false }})")
5021                } else {
5022                    value
5023                }
5024            }
5025            core::AugmentedImport::Memory { mem, op } => {
5026                let mem = self.core_def(mem);
5027                match op {
5028                    core::AugmentedOp::I32Load => {
5029                        format!(
5030                            "(ptr, off) => new DataView({mem}.buffer).getInt32(ptr + off, true)"
5031                        )
5032                    }
5033                    core::AugmentedOp::I32Load8U => {
5034                        format!(
5035                            "(ptr, off) => new DataView({mem}.buffer).getUint8(ptr + off, true)"
5036                        )
5037                    }
5038                    core::AugmentedOp::I32Load8S => {
5039                        format!("(ptr, off) => new DataView({mem}.buffer).getInt8(ptr + off, true)")
5040                    }
5041                    core::AugmentedOp::I32Load16U => {
5042                        format!(
5043                            "(ptr, off) => new DataView({mem}.buffer).getUint16(ptr + off, true)"
5044                        )
5045                    }
5046                    core::AugmentedOp::I32Load16S => {
5047                        format!(
5048                            "(ptr, off) => new DataView({mem}.buffer).getInt16(ptr + off, true)"
5049                        )
5050                    }
5051                    core::AugmentedOp::I64Load => {
5052                        format!(
5053                            "(ptr, off) => new DataView({mem}.buffer).getBigInt64(ptr + off, true)"
5054                        )
5055                    }
5056                    core::AugmentedOp::F32Load => {
5057                        format!(
5058                            "(ptr, off) => new DataView({mem}.buffer).getFloat32(ptr + off, true)"
5059                        )
5060                    }
5061                    core::AugmentedOp::F64Load => {
5062                        format!(
5063                            "(ptr, off) => new DataView({mem}.buffer).getFloat64(ptr + off, true)"
5064                        )
5065                    }
5066                    core::AugmentedOp::I32Store8 => {
5067                        format!(
5068                            "(ptr, val, offset) => {{
5069                                new DataView({mem}.buffer).setInt8(ptr + offset, val, true);
5070                            }}"
5071                        )
5072                    }
5073                    core::AugmentedOp::I32Store16 => {
5074                        format!(
5075                            "(ptr, val, offset) => {{
5076                                new DataView({mem}.buffer).setInt16(ptr + offset, val, true);
5077                            }}"
5078                        )
5079                    }
5080                    core::AugmentedOp::I32Store => {
5081                        format!(
5082                            "(ptr, val, offset) => {{
5083                                new DataView({mem}.buffer).setInt32(ptr + offset, val, true);
5084                            }}"
5085                        )
5086                    }
5087                    core::AugmentedOp::I64Store => {
5088                        format!(
5089                            "(ptr, val, offset) => {{
5090                                new DataView({mem}.buffer).setBigInt64(ptr + offset, val, true);
5091                            }}"
5092                        )
5093                    }
5094                    core::AugmentedOp::F32Store => {
5095                        format!(
5096                            "(ptr, val, offset) => {{
5097                                new DataView({mem}.buffer).setFloat32(ptr + offset, val, true);
5098                            }}"
5099                        )
5100                    }
5101                    core::AugmentedOp::F64Store => {
5102                        format!(
5103                            "(ptr, val, offset) => {{
5104                                new DataView({mem}.buffer).setFloat64(ptr + offset, val, true);
5105                            }}"
5106                        )
5107                    }
5108                    core::AugmentedOp::MemorySize => {
5109                        format!("ptr => {mem}.buffer.byteLength / 65536")
5110                    }
5111                }
5112            }
5113        }
5114    }
5115
5116    fn core_def(&mut self, def: &CoreDef) -> String {
5117        match def {
5118            CoreDef::Export(e) => self.core_export_var_name(e),
5119            CoreDef::TaskMayBlock => self
5120                .bindgen
5121                .intrinsic(AsyncTaskIntrinsic::CurrentTaskMayBlock.into()),
5122            CoreDef::Trampoline(i) => {
5123                let trampoline = &self.translation.trampolines[*i];
5124                let name = format!("trampoline{}", i.as_u32());
5125                let Some(instance) = self.trampoline_may_leave_instance(trampoline) else {
5126                    return name;
5127                };
5128
5129                self.used_instance_flags.borrow_mut().insert(instance);
5130                if Self::trampoline_checks_may_leave_internally(trampoline) {
5131                    name
5132                } else {
5133                    let guard_may_leave_fn = self
5134                        .bindgen
5135                        .intrinsic(Intrinsic::Component(ComponentIntrinsic::GuardMayLeave));
5136                    format!("{guard_may_leave_fn}({}, {name})", instance.as_u32())
5137                }
5138            }
5139            CoreDef::InstanceFlags(i) => {
5140                // SAFETY: short-lived borrow-mut.
5141                self.used_instance_flags.borrow_mut().insert(*i);
5142                format!("instanceFlags{}", i.as_u32())
5143            }
5144            CoreDef::UnsafeIntrinsic(ui) => {
5145                use wasmtime_environ::component::UnsafeIntrinsic;
5146                let (intrinsic, slot) = match ui {
5147                    UnsafeIntrinsic::ContextGetI32_0 => (AsyncTaskIntrinsic::ContextGet, 0),
5148                    UnsafeIntrinsic::ContextSetI32_0 => (AsyncTaskIntrinsic::ContextSet, 0),
5149                    UnsafeIntrinsic::ContextGetI32_1 => (AsyncTaskIntrinsic::ContextGet, 1),
5150                    UnsafeIntrinsic::ContextSetI32_1 => (AsyncTaskIntrinsic::ContextSet, 1),
5151                    ui => return format!("unsafeIntrinsic{}", ui.index()),
5152                };
5153                let context_fn = self.bindgen.intrinsic(intrinsic.into());
5154                // FACT adapters have no owning component: their context operations
5155                // follow the executing task as enter/exit-sync-call switches it.
5156                let component = if let Some(component_idx) = self.init_current_module {
5157                    self.context_components.borrow_mut().insert(component_idx);
5158                    format!("componentIdx: {}, ", component_idx.as_u32())
5159                } else {
5160                    String::new()
5161                };
5162                format!("{context_fn}.bind(null, {{ {component}slot: {slot} }})")
5163            }
5164        }
5165    }
5166
5167    fn core_export_var_name<T>(&self, export: &CoreExport<T>) -> String
5168    where
5169        T: Into<EntityIndex> + Copy,
5170    {
5171        let name = match &export.item {
5172            ExportItem::Index(idx) => {
5173                let module_idx = self
5174                    .instances
5175                    .get(export.instance)
5176                    .expect("unexpectedly missing export instance");
5177                let module = &self
5178                    .modules
5179                    .get(*module_idx)
5180                    .expect("unexpectedly missing module by idx");
5181                let idx = (*idx).into();
5182                module
5183                    .exports()
5184                    .iter()
5185                    .find_map(|(name, i)| if *i == idx { Some(name) } else { None })
5186                    .unwrap()
5187                    .to_string()
5188            }
5189            ExportItem::Name(s) => s.to_string(),
5190        };
5191        let i = export.instance.as_u32() as usize;
5192        let quoted = maybe_quote_member(&name);
5193        format!("exports{i}{quoted}")
5194    }
5195
5196    /// Process the component imports and build mappings
5197    fn process_imports(&mut self) {
5198        let mut import_resource_map = ResourceMap::new();
5199        for (_import_name, (import_idx, _import_path)) in self.component.imports.iter() {
5200            let (import_name, import_type_def) = &self.component.import_types[*import_idx];
5201            let import_world_key = &self
5202                .imports
5203                .get(import_name)
5204                .expect("missing import mapping");
5205            let import_world_item = &self
5206                .resolve
5207                .worlds
5208                .get(self.world)
5209                .expect("missing world")
5210                .imports
5211                .get(*import_world_key)
5212                .expect("missing import in world for import");
5213
5214            // Generate type information for types used in functions
5215            match import_world_item {
5216                WorldItem::Interface { id: iface_id, .. } => {
5217                    let iface = &self.resolve.interfaces[*iface_id];
5218
5219                    // Process functions imported by the iface, which will use (as arg or param)
5220                    // relevant resources
5221                    for (fn_name, iface_fn) in iface.functions.iter() {
5222                        match import_type_def {
5223                            ComponentExtern {
5224                                ty: TypeDef::ComponentInstance(instance_ty),
5225                                ..
5226                            } => {
5227                                if let Some(ComponentExtern {
5228                                    ty: TypeDef::ComponentFunc(type_func_index),
5229                                    ..
5230                                }) = &self.types[*instance_ty].exports.get(fn_name)
5231                                {
5232                                    self.create_resource_fn_map(
5233                                        iface_fn,
5234                                        *type_func_index,
5235                                        &mut import_resource_map,
5236                                    );
5237                                }
5238                            }
5239                            ComponentExtern {
5240                                ty: TypeDef::ComponentFunc(type_func_idx),
5241                                ..
5242                            } => {
5243                                self.create_resource_fn_map(
5244                                    iface_fn,
5245                                    *type_func_idx,
5246                                    &mut import_resource_map,
5247                                );
5248                            }
5249                            _ => {}
5250                        }
5251                    }
5252                }
5253
5254                // Process imported functions directly to build resource maps
5255                WorldItem::Function(func) => {
5256                    let TypeDef::ComponentFunc(func_ty_idx) = &import_type_def.ty else {
5257                        unreachable!("invalid fn export");
5258                    };
5259                    self.create_resource_fn_map(func, *func_ty_idx, &mut import_resource_map);
5260                }
5261                // Simply informational at this point
5262                WorldItem::Type { .. } => {}
5263            }
5264        }
5265
5266        self.resource_imports.extend(import_resource_map);
5267    }
5268
5269    /// Process component exports and build mappings
5270    fn process_exports(&mut self) {
5271        // Since imports may be referred to by exports, we include all imports in the exports array
5272        self.resource_exports.extend(self.resource_imports.clone());
5273
5274        // Process individual component exports
5275        for (export_name, (export_idx, _extern_data)) in self.component.exports.raw_iter() {
5276            let export_name = export_name.as_ref().to_string();
5277            let export = &self.component.export_items[*export_idx];
5278            let world_key = &self.exports[&export_name];
5279            let item = &self.resolve.worlds[self.world].exports[world_key];
5280            let mut export_resource_map = ResourceMap::new();
5281
5282            match export {
5283                Export::LiftedFunction {
5284                    func: def,
5285                    options,
5286                    ty: func_ty,
5287                } => {
5288                    let func = match item {
5289                        WorldItem::Function(f) => f,
5290                        WorldItem::Interface { .. } | WorldItem::Type { .. } => {
5291                            unreachable!("unexpectedly non-function lifted function export")
5292                        }
5293                    };
5294
5295                    self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);
5296
5297                    let local_name = String::from(match func.kind {
5298                        // For resources, we must take the type name (adding `.prototype.<fn name>` later)
5299                        FunctionKind::Constructor(resource_id)
5300                        | FunctionKind::Method(resource_id)
5301                        | FunctionKind::AsyncMethod(resource_id)
5302                        | FunctionKind::Static(resource_id)
5303                        | FunctionKind::AsyncStatic(resource_id) => Instantiator::resource_name(
5304                            self.resolve,
5305                            &mut self.bindgen.local_names,
5306                            resource_id,
5307                            &self.exports_resource_types,
5308                        ),
5309                        // Fore free standing functions we can use the exoprt name directly as a local name
5310                        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5311                            self.bindgen.local_names.create_once(&export_name)
5312                        }
5313                    });
5314
5315                    let options = self
5316                        .component
5317                        .options
5318                        .get(*options)
5319                        .expect("failed to find options");
5320
5321                    self.export_bindgen(
5322                        &local_name,
5323                        def,
5324                        options,
5325                        func,
5326                        func_ty,
5327                        &export_name,
5328                        &export_resource_map,
5329                    );
5330
5331                    let js_binding_name = match func.kind {
5332                        // For resources, we must take the type name (adding `.prototype.<fn name>` later)
5333                        FunctionKind::Constructor(ty)
5334                        | FunctionKind::Method(ty)
5335                        | FunctionKind::AsyncMethod(ty)
5336                        | FunctionKind::Static(ty)
5337                        | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
5338                            .name
5339                            .as_ref()
5340                            .unwrap()
5341                            .to_upper_camel_case(),
5342                        // For free standing functions we can use the export name directly
5343                        FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5344                            export_name.to_lower_camel_case()
5345                        }
5346                    };
5347
5348                    // Add the export binding
5349                    self.bindgen.esm_bindgen.add_export_binding(
5350                        None,
5351                        local_name,
5352                        js_binding_name,
5353                        func,
5354                    );
5355                }
5356
5357                Export::Instance { exports, .. } => {
5358                    let iface_id = match item {
5359                        WorldItem::Interface { id, .. } => *id,
5360                        WorldItem::Function(_) | WorldItem::Type { .. } => {
5361                            unreachable!("unexpectedly non-interface export instance")
5362                        }
5363                    };
5364
5365                    if self.bindgen.opts.flags_as_bigint || self.bindgen.opts.use_namespace_objects
5366                    {
5367                        let mut namespace_locals = BTreeMap::<TypeId, String>::new();
5368                        for (type_name, type_id) in &self.resolve.interfaces[iface_id].types {
5369                            let type_id = crate::dealias(self.resolve, *type_id);
5370                            let kind = &self.resolve.types[type_id].kind;
5371                            let generate = matches!(kind, TypeDefKind::Flags(_))
5372                                && self.bindgen.opts.flags_as_bigint
5373                                || matches!(kind, TypeDefKind::Enum(_) | TypeDefKind::Variant(_))
5374                                    && self.bindgen.opts.use_namespace_objects;
5375                            if !generate {
5376                                continue;
5377                            }
5378
5379                            let local_name = self
5380                                .bindgen
5381                                .local_names
5382                                .create_once(&type_name.to_upper_camel_case())
5383                                .to_string();
5384                            if let Some(existing) = namespace_locals.get(&type_id) {
5385                                uwriteln!(self.src.js, "const {local_name} = {existing};");
5386                            } else {
5387                                uwriteln!(self.src.js, "const {local_name} = Object.freeze({{");
5388                                match kind {
5389                                    TypeDefKind::Flags(flags) => {
5390                                        for (index, flag) in flags.flags.iter().enumerate() {
5391                                            uwriteln!(
5392                                                self.src.js,
5393                                                "{}: 1n << {index}n,",
5394                                                flag.name.to_upper_camel_case()
5395                                            );
5396                                        }
5397                                    }
5398                                    TypeDefKind::Enum(enum_) => {
5399                                        for case in &enum_.cases {
5400                                            let case_value = crate::enum_case_name(
5401                                                &case.name,
5402                                                self.bindgen.opts.enum_values_screaming_snake_case,
5403                                            );
5404                                            uwriteln!(
5405                                                self.src.js,
5406                                                "{}: '{}',",
5407                                                case.name.to_upper_camel_case(),
5408                                                case_value
5409                                            );
5410                                        }
5411                                    }
5412                                    TypeDefKind::Variant(variant) => {
5413                                        for case in &variant.cases {
5414                                            let case_name = case.name.to_upper_camel_case();
5415                                            if case.ty.is_some() {
5416                                                uwriteln!(
5417                                                    self.src.js,
5418                                                    "{case_name}: (val) => ({{ tag: '{}', val }}),",
5419                                                    case.name
5420                                                );
5421                                            } else {
5422                                                uwriteln!(
5423                                                    self.src.js,
5424                                                    "{case_name}: () => ({{ tag: '{}' }}),",
5425                                                    case.name
5426                                                );
5427                                            }
5428                                        }
5429                                    }
5430                                    _ => unreachable!(),
5431                                }
5432                                uwriteln!(self.src.js, "}});");
5433                                namespace_locals.insert(type_id, local_name.clone());
5434                            }
5435                            self.bindgen.esm_bindgen.add_export_constant(
5436                                &export_name,
5437                                local_name,
5438                                type_name.to_upper_camel_case(),
5439                            );
5440                        }
5441                    }
5442
5443                    // Process exported instances
5444                    for (func_name, (export_idx, _extern_data)) in exports.raw_iter() {
5445                        let func_name = func_name.as_ref().to_string();
5446                        let export = &self.component.export_items[*export_idx];
5447
5448                        // Gather function information for all lifted functions in the isntance export
5449                        let (def, options, func_ty) = match export {
5450                            Export::LiftedFunction { func, options, ty } => (func, options, ty),
5451                            Export::Type(_) => continue, // ignored
5452                            _ => unreachable!("unexpected non-lifted function export"),
5453                        };
5454
5455                        let func = &self.resolve.interfaces[iface_id].functions[&func_name];
5456
5457                        self.create_resource_fn_map(func, *func_ty, &mut export_resource_map);
5458
5459                        let local_name = String::from(match func.kind {
5460                            // For resources, we must use the name of the type
5461                            FunctionKind::Constructor(resource_id)
5462                            | FunctionKind::Method(resource_id)
5463                            | FunctionKind::AsyncMethod(resource_id)
5464                            | FunctionKind::Static(resource_id)
5465                            | FunctionKind::AsyncStatic(resource_id) => {
5466                                Instantiator::resource_name(
5467                                    self.resolve,
5468                                    &mut self.bindgen.local_names,
5469                                    resource_id,
5470                                    &self.exports_resource_types,
5471                                )
5472                            }
5473                            // For free standing functions we can use the bare func name
5474                            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5475                                self.bindgen.local_names.create_once(&func_name)
5476                            }
5477                        });
5478
5479                        let options = self
5480                            .component
5481                            .options
5482                            .get(*options)
5483                            .expect("failed to find options");
5484
5485                        self.export_bindgen(
5486                            &local_name,
5487                            def,
5488                            options,
5489                            func,
5490                            func_ty,
5491                            &export_name,
5492                            &export_resource_map,
5493                        );
5494
5495                        // Determine the export func name (this can also be a class name)
5496                        let export_binding_name = match func.kind {
5497                            // For resources, we must use the type name (later adding `.prototype.<actual fn>`)
5498                            FunctionKind::Constructor(ty)
5499                            | FunctionKind::Method(ty)
5500                            | FunctionKind::AsyncMethod(ty)
5501                            | FunctionKind::Static(ty)
5502                            | FunctionKind::AsyncStatic(ty) => self.resolve.types[ty]
5503                                .name
5504                                .as_ref()
5505                                .unwrap()
5506                                .to_upper_camel_case(),
5507                            // Free standing functions we can use the function name directly
5508                            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => {
5509                                func_name.to_lower_camel_case()
5510                            }
5511                        };
5512
5513                        // Add the export binding
5514                        self.bindgen.esm_bindgen.add_export_binding(
5515                            Some(&export_name),
5516                            local_name,
5517                            export_binding_name,
5518                            func,
5519                        );
5520                    }
5521                }
5522
5523                // ignore type exports for now
5524                Export::Type(_) => {}
5525
5526                // This can't be tested at this time so leave it unimplemented
5527                Export::ModuleStatic { .. } | Export::ModuleImport { .. } => unimplemented!(),
5528            }
5529
5530            // Save information about exported resources for later
5531            self.resource_exports.extend(export_resource_map);
5532        }
5533
5534        self.bindgen.esm_bindgen.populate_export_aliases();
5535    }
5536
5537    #[allow(clippy::too_many_arguments)]
5538    fn export_bindgen(
5539        &mut self,
5540        local_name: &str,
5541        def: &CoreDef,
5542        options: &CanonicalOptions,
5543        func: &Function,
5544        _func_ty_idx: &TypeFuncIndex,
5545        export_name: &String,
5546        export_resource_map: &ResourceMap,
5547    ) {
5548        // Determine whether the function should be generated as async
5549        let inferred_async = self.core_def_requires_async_export(def, false);
5550        if inferred_async {
5551            let func_name = func.name.as_str();
5552            self.async_analysis
5553                .inferred_exports
5554                .insert(if export_name == func_name {
5555                    func_name.to_string()
5556                } else {
5557                    format!("{export_name}#{func_name}")
5558                });
5559        }
5560        let requires_async_porcelain = inferred_async
5561            || requires_async_porcelain(
5562                FunctionIdentifier::Fn(func),
5563                export_name,
5564                &self.async_exports,
5565            );
5566        // If the function is *also* async lifted, it
5567        if options.async_ {
5568            assert!(
5569                options.post_return.is_none(),
5570                "async function {local_name} (export {export_name}) can't have post return"
5571            );
5572        }
5573
5574        let is_async = is_async_fn(func, options);
5575
5576        let wrap_async_future_result = (requires_async_porcelain || is_async)
5577            && matches!(
5578                func.result.as_ref(),
5579                Some(Type::Id(id))
5580                    if matches!(
5581                        self.resolve.types[crate::dealias(self.resolve, *id)].kind,
5582                        TypeDefKind::Future(_)
5583                    )
5584            );
5585
5586        let maybe_async = if (requires_async_porcelain || is_async) && !wrap_async_future_result {
5587            "async "
5588        } else {
5589            ""
5590        };
5591        let wrapped_function_target = wrap_async_future_result.then(|| match func.kind {
5592            FunctionKind::Freestanding | FunctionKind::AsyncFreestanding => local_name.to_string(),
5593            FunctionKind::Method(_) | FunctionKind::AsyncMethod(_) => format!(
5594                "{local_name}.prototype.{}",
5595                func.item_name().to_lower_camel_case()
5596            ),
5597            FunctionKind::Static(_) | FunctionKind::AsyncStatic(_) => {
5598                format!("{local_name}.{}", func.item_name().to_lower_camel_case())
5599            }
5600            FunctionKind::Constructor(_) => {
5601                unreachable!("constructors cannot return futures")
5602            }
5603        });
5604
5605        // Start building early variable declarations
5606        let core_export_fn = self.core_def(def);
5607        let callee = match self
5608            .bindgen
5609            .local_names
5610            .get_or_create(&core_export_fn, &core_export_fn)
5611        {
5612            (local_name, true) => local_name.to_string(),
5613            (local_name, false) => {
5614                let local_name = local_name.to_string();
5615                uwriteln!(self.src.js, "let {local_name};");
5616                self.bindgen
5617                    .all_core_exported_funcs
5618                    // TODO(breaking): remove requires_async_porcelain  once support
5619                    // for manual async import specification is removed, as p3 has
5620                    // built-in function async coloring
5621                    .push((core_export_fn.clone(), is_async | requires_async_porcelain));
5622                local_name
5623            }
5624        };
5625
5626        let iface_name = if export_name.is_empty() {
5627            None
5628        } else {
5629            Some(export_name)
5630        };
5631
5632        // Write function preamble (everything up to the `(` in `function (...`)
5633        match func.kind {
5634            FunctionKind::Freestanding => {
5635                uwrite!(self.src.js, "\n{maybe_async}function {local_name}")
5636            }
5637            FunctionKind::Method(_) => {
5638                self.ensure_local_resource_class(local_name.to_string());
5639                let method_name = func.item_name().to_lower_camel_case();
5640
5641                uwrite!(
5642                    self.src.js,
5643                    "\n{local_name}.prototype.{method_name} = {maybe_async}function {}",
5644                    if !is_js_reserved_word(&method_name) {
5645                        method_name.to_string()
5646                    } else {
5647                        format!("${method_name}")
5648                    }
5649                );
5650            }
5651            FunctionKind::Static(_) => {
5652                self.ensure_local_resource_class(local_name.to_string());
5653                let method_name = func.item_name().to_lower_camel_case();
5654                uwrite!(
5655                    self.src.js,
5656                    "\n{local_name}.{method_name} = function {}",
5657                    if !is_js_reserved_word(&method_name) {
5658                        method_name.to_string()
5659                    } else {
5660                        format!("${method_name}")
5661                    }
5662                );
5663            }
5664            FunctionKind::Constructor(_) => {
5665                if self.defined_resource_classes.contains(local_name) {
5666                    panic!(
5667                        "Internal error: Resource constructor must be defined before other methods and statics"
5668                    );
5669                }
5670                uwrite!(
5671                    self.src.js,
5672                    "
5673                    class {local_name} {{
5674                        constructor"
5675                );
5676                self.defined_resource_classes.insert(local_name.to_string());
5677            }
5678            FunctionKind::AsyncFreestanding => {
5679                uwrite!(self.src.js, "\n{maybe_async}function {local_name}")
5680            }
5681            FunctionKind::AsyncMethod(_) => {
5682                self.ensure_local_resource_class(local_name.to_string());
5683                let method_name = func.item_name().to_lower_camel_case();
5684                let fn_name = if !is_js_reserved_word(&method_name) {
5685                    method_name.to_string()
5686                } else {
5687                    format!("${method_name}")
5688                };
5689                uwrite!(
5690                    self.src.js,
5691                    "\n{local_name}.prototype.{method_name} = {maybe_async}function {fn_name}",
5692                );
5693            }
5694            FunctionKind::AsyncStatic(_) => {
5695                self.ensure_local_resource_class(local_name.to_string());
5696                let method_name = func.item_name().to_lower_camel_case();
5697                let fn_name = if !is_js_reserved_word(&method_name) {
5698                    method_name.to_string()
5699                } else {
5700                    format!("${method_name}")
5701                };
5702                uwrite!(
5703                    self.src.js,
5704                    "\n{local_name}.{method_name} = {maybe_async}function {fn_name}",
5705                );
5706            }
5707        };
5708
5709        // Perform bindgen
5710        self.bindgen(JsFunctionBindgenArgs {
5711            nparams: func.params.len(),
5712            call_type: match func.kind {
5713                FunctionKind::Method(_) => CallType::FirstArgIsThis,
5714                FunctionKind::AsyncMethod(_) => CallType::AsyncFirstArgIsThis,
5715                FunctionKind::Freestanding
5716                | FunctionKind::Static(_)
5717                | FunctionKind::Constructor(_) => CallType::Standard,
5718                FunctionKind::AsyncFreestanding | FunctionKind::AsyncStatic(_) => {
5719                    CallType::AsyncStandard
5720                }
5721            },
5722            iface_name: iface_name.map(|v| v.as_str()),
5723            callee: &callee,
5724            opts: options,
5725            func,
5726            resource_map: export_resource_map,
5727            abi: AbiVariant::GuestExport,
5728            requires_async_porcelain,
5729            is_async,
5730            wrap_async_future_result,
5731            for_import: false,
5732        });
5733        if let Some(target) = wrapped_function_target {
5734            let async_fn_ctor = self.bindgen.intrinsic(Intrinsic::AsyncFunctionCtor);
5735            uwriteln!(
5736                self.src.js,
5737                "\nObject.setPrototypeOf({target}, {async_fn_ctor}.prototype);"
5738            );
5739        }
5740
5741        // End the function
5742        match func.kind {
5743            FunctionKind::AsyncFreestanding | FunctionKind::Freestanding => self.src.js("\n"),
5744            FunctionKind::AsyncMethod(_)
5745            | FunctionKind::AsyncStatic(_)
5746            | FunctionKind::Method(_)
5747            | FunctionKind::Static(_) => self.src.js(";\n"),
5748            FunctionKind::Constructor(_) => self.src.js("\n}\n"),
5749        }
5750    }
5751}
5752
5753#[derive(Default)]
5754pub struct Source {
5755    pub js: source::Source,
5756    pub js_init: source::Source,
5757}
5758
5759impl Source {
5760    pub fn js(&mut self, s: &str) {
5761        self.js.push_str(s);
5762    }
5763    pub fn js_init(&mut self, s: &str) {
5764        self.js_init.push_str(s);
5765    }
5766}
5767
5768/// Compute the semver "compatibility track" for a version string.
5769/// Mirrors wasmtime's `alternate_lookup_key()` logic.
5770///
5771/// Returns the compat key and parsed `Version` on success.
5772///
5773/// Examples (showing just the key):
5774///   "1.2.3"  → Some(("1", ..))     — major > 0, compat within major
5775///   "0.2.10" → Some(("0.2", ..))   — minor > 0, compat within 0.minor
5776///   "0.0.1"  → None                — no semver compat
5777///   "1.0.0-rc.1" → None            — pre-release, no compat
5778fn semver_compat_key(version_str: &str) -> Option<(String, Version)> {
5779    let version = Version::parse(version_str).ok()?;
5780    if !version.pre.is_empty() {
5781        None
5782    } else if version.major != 0 {
5783        Some((format!("{}", version.major), version))
5784    } else if version.minor != 0 {
5785        Some((format!("0.{}", version.minor), version))
5786    } else {
5787        None
5788    }
5789}
5790
5791fn parse_mapping(mapping: &str) -> (String, Option<String>) {
5792    if mapping.len() > 1
5793        && let Some(hash_idx) = mapping[1..].find('#')
5794    {
5795        return (
5796            mapping[0..hash_idx + 1].to_string(),
5797            Some(mapping[hash_idx + 2..].into()),
5798        );
5799    }
5800    (mapping.into(), None)
5801}
5802
5803fn resolve_wildcard_mapping(key: &str, mapping: &str, impt: &str) -> Option<String> {
5804    let idx = key.find('*')?;
5805    let lhs = &key[..idx];
5806    let rhs = &key[idx + 1..];
5807
5808    if !impt.starts_with(lhs) || !impt.ends_with(rhs) {
5809        return None;
5810    }
5811
5812    let matched_len = impt.len() - lhs.len() - rhs.len();
5813    let matched = &impt[lhs.len()..lhs.len() + matched_len];
5814    Some(mapping.replace('*', matched))
5815}
5816
5817/// Same as [`map_import`], except that when `impt` itself has no mapping and
5818/// the import is a labeled import of a named interface (the component model
5819/// `implements` feature 🏷️), a mapping for the implemented interface id is
5820/// consulted as a fallback.
5821fn map_import_with_implements(
5822    map: &Option<HashMap<String, String>>,
5823    impt: &str,
5824    implements: Option<&str>,
5825) -> (String, Option<String>) {
5826    let (specifier, iface_member) = map_import(map, impt);
5827    if specifier == impt
5828        && iface_member.is_none()
5829        && let Some(target) = implements
5830    {
5831        let (mapped, member) = map_import(map, target);
5832        // An unmapped name is returned with just its version stripped
5833        let target_sans_version = match target.find('@') {
5834            Some(version_idx) => &target[0..version_idx],
5835            None => target,
5836        };
5837        if mapped != target_sans_version || member.is_some() {
5838            return (mapped, member);
5839        }
5840    }
5841    (specifier, iface_member)
5842}
5843
5844fn map_import(map: &Option<HashMap<String, String>>, impt: &str) -> (String, Option<String>) {
5845    let impt_sans_version = match impt.find('@') {
5846        Some(version_idx) => &impt[0..version_idx],
5847        None => impt,
5848    };
5849    if let Some(map) = map.as_ref() {
5850        // 1. Exact match (including version)
5851        if let Some(mapping) = map.get(impt) {
5852            return parse_mapping(mapping);
5853        }
5854
5855        // 2. Exact match without version
5856        if let Some(mapping) = map.get(impt_sans_version) {
5857            return parse_mapping(mapping);
5858        }
5859
5860        // Prefer versioned wildcards over unversioned fallbacks.
5861        for (key, mapping) in map {
5862            if !key.contains('@') {
5863                continue;
5864            }
5865            if let Some(mapping) = resolve_wildcard_mapping(key, mapping, impt) {
5866                return parse_mapping(&mapping);
5867            }
5868        }
5869
5870        // Then apply unversioned wildcards to the version-stripped import.
5871        for (key, mapping) in map {
5872            if key.contains('@') {
5873                continue;
5874            }
5875            if let Some(mapping) = resolve_wildcard_mapping(key, mapping, impt_sans_version) {
5876                return parse_mapping(&mapping);
5877            }
5878        }
5879
5880        // If the import has a parseable version and earlier steps didn't match,
5881        // try matching against map entries with compatible versions.
5882        if let Some(at) = impt.find('@') {
5883            let impt_ver_str = &impt[at + 1..];
5884            if let Some((impt_compat, _)) = semver_compat_key(impt_ver_str) {
5885                let mut best_match: Option<(String, Version)> = None;
5886
5887                for (key, mapping) in map {
5888                    let key_at = match key.find('@') {
5889                        Some(at) => at,
5890                        None => continue,
5891                    };
5892                    let key_base = &key[..key_at];
5893                    let key_ver_str = &key[key_at + 1..];
5894
5895                    let (key_compat, key_ver) = match semver_compat_key(key_ver_str) {
5896                        Some(k) => k,
5897                        None => continue,
5898                    };
5899                    if impt_compat != key_compat {
5900                        continue;
5901                    }
5902
5903                    let resolved = if let Some(mapping) =
5904                        resolve_wildcard_mapping(key_base, mapping, impt_sans_version)
5905                    {
5906                        Some(mapping)
5907                    } else if key_base == impt_sans_version {
5908                        Some(mapping.clone())
5909                    } else {
5910                        None
5911                    };
5912
5913                    if let Some(resolved_mapping) = resolved {
5914                        match &best_match {
5915                            Some((_, prev_ver)) if key_ver <= *prev_ver => {}
5916                            _ => {
5917                                best_match = Some((resolved_mapping, key_ver));
5918                            }
5919                        }
5920                    }
5921                }
5922
5923                if let Some((mapping, _)) = best_match {
5924                    return parse_mapping(&mapping);
5925                }
5926            }
5927        }
5928    }
5929    (impt_sans_version.to_string(), None)
5930}
5931
5932pub fn parse_world_key(name: &str) -> Option<(&str, &str, &str)> {
5933    let registry_idx = name.find(':')?;
5934    let ns = &name[0..registry_idx];
5935    match name.rfind('/') {
5936        Some(sep_idx) => {
5937            let end = if let Some(version_idx) = name.rfind('@') {
5938                version_idx
5939            } else {
5940                name.len()
5941            };
5942            Some((
5943                ns,
5944                &name[registry_idx + 1..sep_idx],
5945                &name[sep_idx + 1..end],
5946            ))
5947        }
5948        // interface is a namespace, function is a default export
5949        None => Some((ns, &name[registry_idx + 1..], "")),
5950    }
5951}
5952
5953fn core_file_name(name: &str, idx: u32) -> String {
5954    let i_str = if idx == 0 {
5955        String::from("")
5956    } else {
5957        (idx + 1).to_string()
5958    };
5959    format!("{name}.core{i_str}.wasm")
5960}
5961
5962/// Encode a [`StringEncoding`] as a string that can be used in Javascript
5963fn string_encoding_js_literal(val: &wasmtime_environ::component::StringEncoding) -> &'static str {
5964    match val {
5965        wasmtime_environ::component::StringEncoding::Utf8 => "'utf8'",
5966        wasmtime_environ::component::StringEncoding::Utf16 => "'utf16'",
5967        wasmtime_environ::component::StringEncoding::CompactUtf16 => "'compact-utf16'",
5968    }
5969}
5970
5971/// Generate the javascript that corresponds to a list of lifting functions for a given list of types
5972///
5973/// # Arguments
5974///
5975/// * `instantiator`
5976/// * `types` - Types for which to generate lift functions
5977/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
5978///
5979pub fn gen_flat_lift_fn_list_js_expr(
5980    instantiator: &mut Instantiator,
5981    types: &[InterfaceType],
5982    extra_resource_map: &Option<&mut ResourceMap>,
5983) -> String {
5984    let mut lift_fns: Vec<String> = Vec::with_capacity(types.len());
5985    for ty in types.iter() {
5986        lift_fns.push(gen_flat_lift_fn_js_expr(
5987            instantiator,
5988            ty,
5989            extra_resource_map,
5990        ));
5991    }
5992    format!("[{}]", lift_fns.join(","))
5993}
5994
5995fn flat_count_js_expr(flat_count: &Option<u8>) -> String {
5996    flat_count
5997        .map(|count| count.to_string())
5998        .unwrap_or_else(|| "null".into())
5999}
6000
6001fn interface_type_maybe_null(component_types: &ComponentTypes, ty: &InterfaceType) -> bool {
6002    match ty {
6003        InterfaceType::Option(idx) => {
6004            !interface_type_maybe_null(component_types, &component_types[*idx].ty)
6005        }
6006        _ => false,
6007    }
6008}
6009
6010/// The Canonical ABI `join` operation over flat core types, used when
6011/// computing the flat representation of variant payloads.
6012fn join_flat_core_types(a: &'static str, b: &'static str) -> &'static str {
6013    if a == b {
6014        a
6015    } else if (a == "i32" && b == "f32") || (a == "f32" && b == "i32") {
6016        "i32"
6017    } else {
6018        "i64"
6019    }
6020}
6021
6022/// Compute the flat core types of a type per the Canonical ABI's
6023/// `flatten_type` (32-bit memories), for use in lift/lower metadata.
6024///
6025/// Returns `None` when the type has no flat representation of at most
6026/// [`MAX_FLAT_PARAMS`] core values (such types are passed via memory).
6027fn flat_core_types(
6028    component_types: &ComponentTypes,
6029    ty: &InterfaceType,
6030) -> Option<Vec<&'static str>> {
6031    component_types
6032        .canonical_abi(ty)
6033        .flat_count(MAX_FLAT_PARAMS)?;
6034    let mut flat = Vec::new();
6035    push_flat_core_types(component_types, ty, &mut flat);
6036    Some(flat)
6037}
6038
6039/// Compute the join of the flat core types of a group of variant case
6040/// payloads, per the Canonical ABI's `flatten_variant` (excluding the
6041/// discriminant).
6042fn flat_core_types_variant_payload_join<'a>(
6043    component_types: &ComponentTypes,
6044    cases: impl Iterator<Item = Option<&'a InterfaceType>>,
6045) -> Vec<&'static str> {
6046    let mut joined: Vec<&'static str> = Vec::new();
6047    for maybe_ty in cases {
6048        let Some(ty) = maybe_ty else { continue };
6049        let mut case_flat = Vec::new();
6050        push_flat_core_types(component_types, ty, &mut case_flat);
6051        for (idx, flat_ty) in case_flat.into_iter().enumerate() {
6052            match joined.get_mut(idx) {
6053                Some(existing) => {
6054                    *existing = join_flat_core_types(existing, flat_ty);
6055                }
6056                None => joined.push(flat_ty),
6057            }
6058        }
6059    }
6060    joined
6061}
6062
6063fn push_flat_core_types(
6064    component_types: &ComponentTypes,
6065    ty: &InterfaceType,
6066    flat: &mut Vec<&'static str>,
6067) {
6068    match ty {
6069        InterfaceType::Bool
6070        | InterfaceType::S8
6071        | InterfaceType::U8
6072        | InterfaceType::S16
6073        | InterfaceType::U16
6074        | InterfaceType::S32
6075        | InterfaceType::U32
6076        | InterfaceType::Char
6077        | InterfaceType::Flags(_)
6078        | InterfaceType::Enum(_)
6079        | InterfaceType::Own(_)
6080        | InterfaceType::Borrow(_)
6081        | InterfaceType::Future(_)
6082        | InterfaceType::Stream(_)
6083        | InterfaceType::ErrorContext(_) => flat.push("i32"),
6084
6085        InterfaceType::S64 | InterfaceType::U64 => flat.push("i64"),
6086
6087        InterfaceType::Float32 => flat.push("f32"),
6088        InterfaceType::Float64 => flat.push("f64"),
6089
6090        InterfaceType::String | InterfaceType::List(_) | InterfaceType::Map(_) => {
6091            flat.push("i32");
6092            flat.push("i32");
6093        }
6094
6095        InterfaceType::Record(ty_idx) => {
6096            for field in &component_types[*ty_idx].fields {
6097                push_flat_core_types(component_types, &field.ty, flat);
6098            }
6099        }
6100
6101        InterfaceType::Tuple(ty_idx) => {
6102            for ty in &component_types[*ty_idx].types {
6103                push_flat_core_types(component_types, ty, flat);
6104            }
6105        }
6106
6107        InterfaceType::FixedLengthList(ty_idx) => {
6108            let list_ty = &component_types[*ty_idx];
6109            for _ in 0..list_ty.size {
6110                push_flat_core_types(component_types, &list_ty.element, flat);
6111            }
6112        }
6113
6114        InterfaceType::Variant(ty_idx) => {
6115            let variant_ty = &component_types[*ty_idx];
6116            flat.push("i32");
6117            flat.extend(flat_core_types_variant_payload_join(
6118                component_types,
6119                variant_ty.cases.iter().map(|(_, ty)| ty.as_ref()),
6120            ));
6121        }
6122
6123        InterfaceType::Option(ty_idx) => {
6124            let option_ty = &component_types[*ty_idx];
6125            flat.push("i32");
6126            flat.extend(flat_core_types_variant_payload_join(
6127                component_types,
6128                [None, Some(&option_ty.ty)].into_iter(),
6129            ));
6130        }
6131
6132        InterfaceType::Result(ty_idx) => {
6133            let result_ty = &component_types[*ty_idx];
6134            flat.push("i32");
6135            flat.extend(flat_core_types_variant_payload_join(
6136                component_types,
6137                [result_ty.ok.as_ref(), result_ty.err.as_ref()].into_iter(),
6138            ));
6139        }
6140    }
6141}
6142
6143/// Render a (possibly missing) flat core type list as a JS expression
6144fn flat_core_types_js_expr(flat: &Option<Vec<&'static str>>) -> String {
6145    match flat {
6146        Some(flat) => format!(
6147            "[{}]",
6148            flat.iter()
6149                .map(|t| format!("'{t}'"))
6150                .collect::<Vec<_>>()
6151                .join(",")
6152        ),
6153        None => "null".into(),
6154    }
6155}
6156
6157/// Generate the javascript lifting function for a given type
6158///
6159/// This function will a function object that can be executed with the right
6160/// context in order to perform the lift. For example, running this for bool
6161/// will produce the following:
6162///
6163/// ```js
6164/// _liftFlatBool
6165/// ```
6166///
6167/// This is becasue all it takes to lift a flat boolean is to run the _liftFlatBool function intrinsic.
6168///
6169/// The intrinsic it guaranteed to be in scope once execution time because it wlil be used in the relevant branch.
6170///
6171/// # Arguments
6172///
6173/// * `instantiator`
6174/// * `ty` - The type for which to generate a lift function
6175/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
6176///
6177pub fn gen_flat_lift_fn_js_expr(
6178    instantiator: &mut Instantiator,
6179    ty: &InterfaceType,
6180    extra_resource_map: &Option<&mut ResourceMap>,
6181) -> String {
6182    let component_types = instantiator.types;
6183
6184    match ty {
6185        InterfaceType::Bool => {
6186            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBool));
6187            Intrinsic::Lift(LiftIntrinsic::LiftFlatBool).name().into()
6188        }
6189
6190        InterfaceType::S8 => {
6191            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS8));
6192            Intrinsic::Lift(LiftIntrinsic::LiftFlatS8).name().into()
6193        }
6194
6195        InterfaceType::U8 => {
6196            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU8));
6197            Intrinsic::Lift(LiftIntrinsic::LiftFlatU8).name().into()
6198        }
6199
6200        InterfaceType::S16 => {
6201            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS16));
6202            Intrinsic::Lift(LiftIntrinsic::LiftFlatS16).name().into()
6203        }
6204
6205        InterfaceType::U16 => {
6206            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU16));
6207            Intrinsic::Lift(LiftIntrinsic::LiftFlatU16).name().into()
6208        }
6209
6210        InterfaceType::S32 => {
6211            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS32));
6212            Intrinsic::Lift(LiftIntrinsic::LiftFlatS32).name().into()
6213        }
6214
6215        InterfaceType::U32 => {
6216            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU32));
6217            Intrinsic::Lift(LiftIntrinsic::LiftFlatU32).name().into()
6218        }
6219
6220        InterfaceType::S64 => {
6221            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatS64));
6222            Intrinsic::Lift(LiftIntrinsic::LiftFlatS64).name().into()
6223        }
6224
6225        InterfaceType::U64 => {
6226            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatU64));
6227            Intrinsic::Lift(LiftIntrinsic::LiftFlatU64).name().into()
6228        }
6229
6230        InterfaceType::Float32 => {
6231            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32));
6232            Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat32)
6233                .name()
6234                .into()
6235        }
6236
6237        InterfaceType::Float64 => {
6238            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64));
6239            Intrinsic::Lift(LiftIntrinsic::LiftFlatFloat64)
6240                .name()
6241                .into()
6242        }
6243
6244        InterfaceType::Char => {
6245            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatChar));
6246            Intrinsic::Lift(LiftIntrinsic::LiftFlatChar).name().into()
6247        }
6248
6249        InterfaceType::String => {
6250            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny));
6251            Intrinsic::Lift(LiftIntrinsic::LiftFlatStringAny)
6252                .name()
6253                .into()
6254        }
6255
6256        InterfaceType::Record(ty_idx) => {
6257            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord));
6258            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatRecord).name();
6259            let record_ty = &component_types[*ty_idx];
6260            let size32 = record_ty.abi.size32;
6261            let align32 = record_ty.abi.align32;
6262            let mut keys_and_lifts_expr = String::from("[");
6263            // For each field we build a list of [name, liftFn, 32bit alignment]
6264            // so that the record lifting function (which is a higher level function)
6265            // can properly generate a function that lifts the fields.
6266            for f in &record_ty.fields {
6267                let field_abi = component_types.canonical_abi(&f.ty);
6268                let field_size32 = field_abi.size32;
6269                let field_align32 = field_abi.align32;
6270                keys_and_lifts_expr.push_str(&format!(
6271                    "['{}', {}, {}, {}],",
6272                    f.name.to_lower_camel_case(),
6273                    gen_flat_lift_fn_js_expr(instantiator, &f.ty, extra_resource_map),
6274                    field_size32,
6275                    field_align32,
6276                ));
6277            }
6278            keys_and_lifts_expr.push(']');
6279            format!(
6280                "{lift_fn}({{ fieldMetas: {keys_and_lifts_expr}, size32: {size32}, align32: {align32} }})"
6281            )
6282        }
6283
6284        InterfaceType::Variant(ty_idx) => {
6285            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant));
6286            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatVariant).name();
6287            let variant_ty = &component_types[*ty_idx];
6288            let variant_flat_count = flat_count_js_expr(&variant_ty.abi.flat_count);
6289            let variant_size32 = variant_ty.abi.size32;
6290            let variant_align32 = variant_ty.abi.align32;
6291            let variant_payload_offset32 = variant_ty.info.payload_offset32;
6292            let variant_payload_flat_types = flat_core_types_js_expr(
6293                &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
6294            );
6295
6296            let mut lift_metas_expr = String::from("[");
6297            for (name, maybe_ty) in &variant_ty.cases {
6298                let (lift_fn_js, case_size32, case_align32, case_flat_count, case_flat_types) =
6299                    match maybe_ty {
6300                        Some(ty) => {
6301                            let cabi_info = component_types.canonical_abi(ty);
6302                            (
6303                                gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map),
6304                                cabi_info.size32.to_string(),
6305                                cabi_info.align32.to_string(),
6306                                cabi_info
6307                                    .flat_count(MAX_FLAT_PARAMS)
6308                                    .map(|v| v.to_string())
6309                                    .unwrap_or_else(|| "null".into()),
6310                                flat_core_types_js_expr(&flat_core_types(component_types, ty)),
6311                            )
6312                        }
6313                        None => (
6314                            "null".into(),
6315                            "0".into(),
6316                            "0".into(),
6317                            "0".into(),
6318                            "[]".into(),
6319                        ),
6320                    };
6321
6322                lift_metas_expr.push_str(&format!(
6323                    "['{name}', {lift_fn_js}, {case_size32}, {case_align32}, {case_flat_count}, {case_flat_types}],",
6324                ));
6325            }
6326            lift_metas_expr.push(']');
6327
6328            format!(
6329                "{lift_fn}({{
6330                     caseMetas: {lift_metas_expr},
6331                     variantSize32: {variant_size32},
6332                     variantAlign32: {variant_align32},
6333                     variantPayloadOffset32: {variant_payload_offset32},
6334                     variantFlatCount: {variant_flat_count},
6335                     variantPayloadFlatTypes: {variant_payload_flat_types},
6336                 }} )"
6337            )
6338        }
6339
6340        InterfaceType::List(ty_idx) => {
6341            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
6342            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
6343            let list_ty = &component_types[*ty_idx];
6344            let lift_fn_expr =
6345                gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6346            let elem_cabi = component_types.canonical_abi(&list_ty.element);
6347            let elem_align32 = elem_cabi.align32;
6348            let elem_size32 = elem_cabi.size32;
6349            let typed_array = js_typed_array_ctor(&list_ty.element).unwrap_or("undefined");
6350            format!(
6351                "{f}({{
6352                     elemLiftFn: {lift_fn_expr},
6353                     elemAlign32: {elem_align32},
6354                     elemSize32: {elem_size32},
6355                     typedArray: {typed_array},
6356                  }})"
6357            )
6358        }
6359
6360        InterfaceType::FixedLengthList(ty_idx) => {
6361            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatList));
6362            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatList).name();
6363            let list_ty = &component_types[*ty_idx];
6364            let list_size32 = list_ty.abi.size32;
6365            let list_align32 = list_ty.abi.align32;
6366            let lift_fn_expr =
6367                gen_flat_lift_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
6368            let list_len = list_ty.size;
6369            let elem_cabi = component_types.canonical_abi(&list_ty.element);
6370            let elem_align32 = elem_cabi.align32;
6371            let elem_size32 = elem_cabi.size32;
6372            format!(
6373                "{f}({{
6374                     elemLiftFn: {lift_fn_expr},
6375                     elemAlign32: {elem_align32},
6376                     elemSize32: {elem_size32},
6377                     listSize32: {list_size32},
6378                     listAlign32: {list_align32},
6379                     knownLen: {list_len},
6380                 }})"
6381            )
6382        }
6383
6384        InterfaceType::Tuple(ty_idx) => {
6385            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple));
6386            let tuple_ty = &component_types[*ty_idx];
6387            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatTuple).name();
6388            let size_u32 = tuple_ty.abi.size32;
6389            let align_u32 = tuple_ty.abi.align32;
6390
6391            let mut elem_lifts_expr = String::from("[");
6392            for ty in &tuple_ty.types {
6393                let lift_fn_js = gen_flat_lift_fn_js_expr(instantiator, ty, extra_resource_map);
6394                let elem_abi = component_types.canonical_abi(ty);
6395                let elem_size32 = elem_abi.size32;
6396                let elem_align32 = elem_abi.align32;
6397                elem_lifts_expr
6398                    .push_str(&format!("[{lift_fn_js}, {elem_size32}, {elem_align32}],"));
6399            }
6400            elem_lifts_expr.push(']');
6401
6402            format!(
6403                "{f}({{ elemLiftFns: {elem_lifts_expr}, size32: {size_u32}, align32: {align_u32} }})"
6404            )
6405        }
6406
6407        InterfaceType::Flags(ty_idx) => {
6408            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags));
6409            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFlags).name();
6410            let flags_ty = &component_types[*ty_idx];
6411            let size_u32 = flags_ty.abi.size32;
6412            let align_u32 = flags_ty.abi.align32;
6413            let names_expr = format!(
6414                "[{}]",
6415                flags_ty
6416                    .names
6417                    .iter()
6418                    .map(|s| format!("'{}'", s.to_lower_camel_case()))
6419                    .collect::<Vec<_>>()
6420                    .join(",")
6421            );
6422            let num_flags = flags_ty.names.len();
6423            let elem_size = if num_flags <= 8 {
6424                1
6425            } else if num_flags <= 16 {
6426                2
6427            } else {
6428                4
6429            };
6430
6431            format!(
6432                "{f}({{ names: {names_expr}, size32: {size_u32}, align32: {align_u32}, intSizeBytes: {elem_size} }})"
6433            )
6434        }
6435
6436        InterfaceType::Enum(ty_idx) => {
6437            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum));
6438            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatEnum).name();
6439            let enum_ty = &component_types[*ty_idx];
6440            let enum_size32 = enum_ty.abi.size32;
6441            let enum_align32 = enum_ty.abi.align32;
6442            let enum_payload_offset32 = enum_ty.info.payload_offset32;
6443            let enum_flat_count = flat_count_js_expr(&enum_ty.abi.flat_count);
6444
6445            let mut elem_lifts_expr = String::from("[");
6446            for name in &enum_ty.names {
6447                let name = crate::enum_case_name(
6448                    name,
6449                    instantiator.bindgen.opts.enum_values_screaming_snake_case,
6450                );
6451                elem_lifts_expr.push_str(&format!(
6452                    "['{name}', null, {enum_size32}, {enum_align32}, {enum_payload_offset32}],"
6453                ));
6454            }
6455            elem_lifts_expr.push(']');
6456
6457            format!(
6458                r#"
6459                  {f}({{
6460                      caseMetas: {elem_lifts_expr},
6461                      variantSize32: {enum_size32},
6462                      variantAlign32: {enum_align32},
6463                      variantPayloadOffset32: {enum_payload_offset32},
6464                      variantFlatCount: {enum_flat_count},
6465                  }})
6466               "#
6467            )
6468        }
6469
6470        InterfaceType::Option(ty_idx) => {
6471            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOption));
6472            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOption).name();
6473            let option_ty = &component_types[*ty_idx];
6474            let option_payload_offset32 = option_ty.info.payload_offset32;
6475            let option_align32 = option_ty.abi.align32;
6476            let option_size32 = option_ty.abi.size32;
6477            let option_flat_count = flat_count_js_expr(&option_ty.abi.flat_count);
6478            let option_payload_flat_types = flat_core_types_js_expr(
6479                &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
6480            );
6481
6482            let some_ty_abi = component_types.canonical_abi(&option_ty.ty);
6483            let some_ty_flat_count = flat_count_js_expr(&some_ty_abi.flat_count);
6484            let some_ty_size32 = some_ty_abi.size32;
6485            let some_ty_align32 = some_ty_abi.align32;
6486            let some_ty_flat_types =
6487                flat_core_types_js_expr(&flat_core_types(component_types, &option_ty.ty));
6488            let some_ty_lift_fn_js =
6489                gen_flat_lift_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);
6490            let payload_maybe_null = interface_type_maybe_null(component_types, &option_ty.ty);
6491
6492            format!(
6493                r#"
6494                {f}({{
6495                    caseMetas: [
6496                        ['none', null, 0, 0, 0, [] ],
6497                        ['some', {some_ty_lift_fn_js}, {some_ty_size32}, {some_ty_align32}, {some_ty_flat_count}, {some_ty_flat_types} ],
6498                    ],
6499                    variantSize32: {option_size32},
6500                    variantAlign32: {option_align32},
6501                    variantPayloadOffset32: {option_payload_offset32},
6502                    variantFlatCount: {option_flat_count},
6503                    variantPayloadFlatTypes: {option_payload_flat_types},
6504                    payloadMaybeNull: {payload_maybe_null},
6505                }})
6506                "#
6507            )
6508        }
6509
6510        InterfaceType::Result(ty_idx) => {
6511            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatResult));
6512            let lift_fn = Intrinsic::Lift(LiftIntrinsic::LiftFlatResult).name();
6513            let result_ty = &component_types[*ty_idx];
6514            let result_size32 = result_ty.abi.size32;
6515            let result_align32 = result_ty.abi.align32;
6516            let result_payload_offset32 = result_ty.info.payload_offset32;
6517            let result_flat_count = flat_count_js_expr(&result_ty.abi.flat_count);
6518            let result_payload_flat_types = flat_core_types_js_expr(
6519                &flat_core_types(component_types, ty).map(|flat| flat[1..].to_vec()),
6520            );
6521
6522            let mut cases_and_lifts_expr = String::from("[");
6523            if let Some(ok_ty) = result_ty.ok {
6524                let ok_ty_abi = component_types.canonical_abi(&ok_ty);
6525                let ok_ty_size32 = ok_ty_abi.size32;
6526                let ok_ty_align32 = ok_ty_abi.align32;
6527                let ok_flat_count = flat_count_js_expr(&ok_ty_abi.flat_count);
6528                let ok_ty_flat_types =
6529                    flat_core_types_js_expr(&flat_core_types(component_types, &ok_ty));
6530                let ok_ty_lift_fn =
6531                    gen_flat_lift_fn_js_expr(instantiator, &ok_ty, extra_resource_map);
6532                cases_and_lifts_expr.push_str(&format!(
6533                    "['ok', {ok_ty_lift_fn}, {ok_ty_size32}, {ok_ty_align32}, {ok_flat_count}, {ok_ty_flat_types}],",
6534                ))
6535            } else {
6536                cases_and_lifts_expr.push_str("['ok', null, 0, 0, 0, []],");
6537            }
6538
6539            if let Some(err_ty) = &result_ty.err {
6540                let err_ty_abi = component_types.canonical_abi(err_ty);
6541                let err_ty_size32 = err_ty_abi.size32;
6542                let err_ty_align32 = err_ty_abi.align32;
6543                let err_ty_flat_count = flat_count_js_expr(&err_ty_abi.flat_count);
6544                let err_ty_flat_types =
6545                    flat_core_types_js_expr(&flat_core_types(component_types, err_ty));
6546                let err_ty_lift_fn =
6547                    gen_flat_lift_fn_js_expr(instantiator, err_ty, extra_resource_map);
6548                cases_and_lifts_expr.push_str(&format!(
6549                    "['err', {err_ty_lift_fn}, {err_ty_size32}, {err_ty_align32}, {err_ty_flat_count}, {err_ty_flat_types}],",
6550                ))
6551            } else {
6552                cases_and_lifts_expr.push_str("['err', null, 0, 0, 0, []],");
6553            }
6554            cases_and_lifts_expr.push(']');
6555
6556            format!(
6557                r#"
6558                  {lift_fn}({{
6559                      caseMetas: {cases_and_lifts_expr},
6560                      variantSize32: {result_size32},
6561                      variantAlign32: {result_align32},
6562                      variantPayloadOffset32: {result_payload_offset32},
6563                      variantFlatCount: {result_flat_count},
6564                      variantPayloadFlatTypes: {result_payload_flat_types},
6565                  }})
6566                "#
6567            )
6568        }
6569
6570        InterfaceType::Own(ty_idx) => {
6571            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn));
6572            instantiator.add_intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
6573            instantiator.add_intrinsic(Intrinsic::SymbolResourceHandle);
6574            instantiator.add_intrinsic(Intrinsic::SymbolResourceRep);
6575            instantiator.add_intrinsic(Intrinsic::SymbolDispose);
6576            instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableRemove));
6577            instantiator.add_intrinsic(Intrinsic::Resource(ResourceIntrinsic::ResourceTableFlag));
6578            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatOwn).name();
6579            let table_ty = &component_types[*ty_idx];
6580            let resource_component_idx = table_ty.unwrap_concrete_instance();
6581            let component_idx = resource_component_idx.as_u32();
6582            let table_idx = ty_idx.as_u32();
6583            if instantiator
6584                .context_components
6585                .borrow()
6586                .contains(&resource_component_idx)
6587            {
6588                instantiator.add_intrinsic(Intrinsic::Resource(
6589                    ResourceIntrinsic::ResourceDestructorCall,
6590                ));
6591            }
6592            let resource_idx = table_ty.unwrap_concrete_ty();
6593
6594            // Attempt to find information about the owned resource
6595            match instantiator.exports_resource_index_types.get(&resource_idx) {
6596                // Type information not found for this resource index
6597                None => format!(
6598                    r#"{f}({{
6599                       componentIdx: {component_idx},
6600                       tableIdx: {table_idx},
6601                       classNameFn: () => null,
6602                       createResourceFn: () => {{ throw new Error('invalid/missing resource type data'); }},
6603                    }})
6604                "#,
6605                ),
6606
6607                // If we have a resource type def, find more information about it to generate
6608                // the resource creation function
6609                Some(resource_typedef) => {
6610                    // Look in both the resource exports and the provided extra resource map for the resource
6611                    let (resource_class_name, create_resource_fn_js) = match (
6612                        instantiator.resource_exports.get(resource_typedef),
6613                        extra_resource_map
6614                            .as_ref()
6615                            .and_then(|v| v.get(resource_typedef)),
6616                    ) {
6617                        // Resource type information wasn't found
6618                        (None, None) => (
6619                            "null".into(),
6620                            "() => {{ throw new Error('missing resource information'); }}".into(),
6621                        ),
6622
6623                        // Resource type was found in either resource_exports or extra provided resource map
6624                        (Some(ResourceTable { imported, data }), _)
6625                        | (_, Some(ResourceTable { imported, data })) => match data {
6626                            ResourceData::Guest { .. } => {
6627                                unimplemented!(
6628                                    "owned resources created by guests should must have host-side data"
6629                                )
6630                            }
6631                            ResourceData::Host {
6632                                tid,
6633                                rid,
6634                                component_idx,
6635                                needs_task_context,
6636                                local_name,
6637                                dtor_name,
6638                            } => {
6639                                let empty_func = JsHelperIntrinsic::EmptyFunc.name();
6640                                let symbol_resource_handle = Intrinsic::SymbolResourceHandle.name();
6641                                let symbol_dispose = Intrinsic::SymbolDispose.name();
6642                                let rsc_table_remove =
6643                                    ResourceIntrinsic::ResourceTableRemove.name();
6644                                let tid = tid.as_u32();
6645                                let rsc_flag = ResourceIntrinsic::ResourceTableFlag.name();
6646                                let component_idx = component_idx.as_u32();
6647
6648                                // Mirrors `Instruction::HandleLift` in `function_bindgen.rs`:
6649                                let create_resource_fn_js = if *imported {
6650                                    let symbol_resource_rep = Intrinsic::SymbolResourceRep.name();
6651                                    let rid = rid.as_u32();
6652                                    format!(
6653                                        r#"
6654                                      (handle) => {{
6655                                          const rep = handleTable{tid}[(handle << 1) + 1] & ~{rsc_flag};
6656                                          let resourceObj = captureTable{rid}.get(rep);
6657                                          if (!resourceObj) {{
6658                                              resourceObj = Object.create({local_name}.prototype);
6659                                              Object.defineProperty(resourceObj, {symbol_resource_handle}, {{ writable: true, value: handle }});
6660                                              Object.defineProperty(resourceObj, {symbol_resource_rep}, {{ writable: true, value: rep }});
6661                                          }} else {{
6662                                              captureTable{rid}.delete(rep);
6663                                          }}
6664                                          {rsc_table_remove}(handleTable{tid}, handle);
6665                                          return resourceObj;
6666                                      }}
6667                                     "#
6668                                    )
6669                                } else {
6670                                    let dtor_setup_js = dtor_name
6671                                        .as_ref()
6672                                        .map(|dtor| {
6673                                            let dtor_call = if *needs_task_context {
6674                                                let call_resource_destructor =
6675                                                    ResourceIntrinsic::ResourceDestructorCall.name();
6676                                                format!(
6677                                                    "{call_resource_destructor}({{ componentIdx: {component_idx}, dtor: {dtor}, rep: handleEntry.rep }});"
6678                                                )
6679                                            } else {
6680                                                format!("{dtor}(handleEntry.rep);")
6681                                            };
6682                                            format!(
6683                                             r#"
6684                                               Object.defineProperty(
6685                                                   resourceObj,
6686                                                   {symbol_dispose},
6687                                                   {{
6688                                                       writable: true,
6689                                                       value: function() {{
6690                                                           finalizationRegistry{tid}.unregister(resourceObj);
6691                                                           const handleEntry = {rsc_table_remove}(handleTable{tid}, handle);
6692                                                           resourceObj[{symbol_dispose}] = {empty_func};
6693                                                           resourceObj[{symbol_resource_handle}] = undefined;
6694                                                           {dtor_call}
6695                                                       }}
6696                                                  }}
6697                                              );
6698                                        "#
6699                                            )
6700                                        })
6701                                        .unwrap_or_default();
6702
6703                                    format!(
6704                                        r#"
6705                                      (handle) => {{
6706                                          const resourceObj = Object.create({local_name}.prototype);
6707                                          Object.defineProperty(resourceObj, {symbol_resource_handle}, {{
6708                                              writable: true,
6709                                              value: handle,
6710                                          }});
6711                                          finalizationRegistry{tid}.register(resourceObj, handle, resourceObj);
6712                                          {dtor_setup_js}
6713                                          return resourceObj;
6714                                      }}
6715                                     "#
6716                                    )
6717                                };
6718
6719                                (local_name.to_string(), create_resource_fn_js)
6720                            }
6721                        },
6722                    };
6723
6724                    format!(
6725                        r#"{f}({{
6726                       componentIdx: {component_idx},
6727                       tableIdx: {table_idx},
6728                       classNameFn: () => {resource_class_name},
6729                       createResourceFn: {create_resource_fn_js},
6730                    }})
6731                "#,
6732                    )
6733                }
6734            }
6735        }
6736
6737        InterfaceType::Borrow(ty_idx) => {
6738            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow));
6739            let table_idx = ty_idx.as_u32();
6740            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatBorrow).name();
6741            format!("{f}.bind(null, {table_idx})")
6742        }
6743
6744        InterfaceType::Future(ty_idx) => {
6745            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture));
6746            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatFuture).name();
6747            let table_idx = ty_idx.as_u32();
6748            let table_ty = &component_types[*ty_idx];
6749            let component_idx = table_ty.instance.as_u32();
6750            format!("{f}({{ futureTableIdx: {table_idx}, componentIdx: {component_idx} }})")
6751        }
6752
6753        InterfaceType::Stream(ty_idx) => {
6754            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatStream));
6755            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatStream).name();
6756            let table_idx = ty_idx.as_u32();
6757            let table_ty = &component_types[*ty_idx];
6758            let component_idx = table_ty.instance.as_u32();
6759            format!("{f}({{ streamTableIdx: {table_idx}, componentIdx: {component_idx} }})")
6760        }
6761
6762        InterfaceType::ErrorContext(ty_idx) => {
6763            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext));
6764            let table_idx = ty_idx.as_u32();
6765            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatErrorContext).name();
6766            format!("{f}.bind(null, {table_idx})")
6767        }
6768
6769        InterfaceType::Map(ty_idx) => {
6770            instantiator.add_intrinsic(Intrinsic::Lift(LiftIntrinsic::LiftFlatMap));
6771            let f = Intrinsic::Lift(LiftIntrinsic::LiftFlatMap).name();
6772            let map_ty = &component_types[*ty_idx];
6773            let key_lift = gen_flat_lift_fn_js_expr(instantiator, &map_ty.key, extra_resource_map);
6774            let value_lift =
6775                gen_flat_lift_fn_js_expr(instantiator, &map_ty.value, extra_resource_map);
6776            let entry_size32 = map_ty.entry_abi.size32;
6777            let entry_align32 = map_ty.entry_abi.align32;
6778            let value_offset32 = map_ty.value_offset32;
6779            format!(
6780                "{f}({{
6781                     keyLiftFn: {key_lift},
6782                     valueLiftFn: {value_lift},
6783                     entrySize32: {entry_size32},
6784                     entryAlign32: {entry_align32},
6785                     valueOffset32: {value_offset32},
6786                 }})"
6787            )
6788        }
6789    }
6790}
6791
6792fn js_typed_array_ctor(ty: &InterfaceType) -> Option<&'static str> {
6793    match ty {
6794        InterfaceType::U8 => Some("Uint8Array"),
6795        InterfaceType::S8 => Some("Int8Array"),
6796        InterfaceType::U16 => Some("Uint16Array"),
6797        InterfaceType::S16 => Some("Int16Array"),
6798        InterfaceType::U32 => Some("Uint32Array"),
6799        InterfaceType::S32 => Some("Int32Array"),
6800        InterfaceType::U64 => Some("BigUint64Array"),
6801        InterfaceType::S64 => Some("BigInt64Array"),
6802        InterfaceType::Float32 => Some("Float32Array"),
6803        InterfaceType::Float64 => Some("Float64Array"),
6804        _ => None,
6805    }
6806}
6807
6808/// Generate the javascript that corresponds to a list of lowering functions for a given list of types
6809///
6810/// # Arguments
6811///
6812/// * `instantiator`
6813/// * `types` - Types for which to generate lift functions
6814/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
6815///
6816pub fn gen_flat_lower_fn_list_js_expr(
6817    instantiator: &mut Instantiator,
6818    types: &[InterfaceType],
6819    extra_import_map: &Option<&mut ResourceMap>,
6820) -> String {
6821    let mut lower_fns: Vec<String> = Vec::with_capacity(types.len());
6822    for ty in types.iter() {
6823        lower_fns.push(gen_flat_lower_fn_js_expr(
6824            instantiator,
6825            ty,
6826            extra_import_map,
6827        ));
6828    }
6829    format!("[{}]", lower_fns.join(","))
6830}
6831
6832/// Generate the javascript lowering function for a given type
6833///
6834/// This function will a function object that can be executed with the right
6835/// context in order to perform the lower. For example, running this for bool
6836/// will produce the following:
6837///
6838/// ```js
6839/// _lowerFlatBool
6840/// ```
6841///
6842/// This is becasue all it takes to lower a flat boolean is to run the _lowerFlatBool function intrinsic.
6843///
6844/// The intrinsic it guaranteed to be in scope once execution time because it wlil be used in the relevant branch.
6845///
6846/// # Arguments
6847///
6848/// * `instantiator`
6849/// * `ty` - type for which to generate a lower function
6850/// * `extra_resource_map` - Extra resource mapping that do not exist on the `instantiatior` that should be used ad-hoc
6851///
6852pub fn gen_flat_lower_fn_js_expr(
6853    instantiator: &mut Instantiator,
6854    ty: &InterfaceType,
6855    extra_resource_map: &Option<&mut ResourceMap>,
6856) -> String {
6857    let component_types = instantiator.types;
6858    match ty {
6859        InterfaceType::Bool => {
6860            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBool));
6861            Intrinsic::Lower(LowerIntrinsic::LowerFlatBool)
6862                .name()
6863                .into()
6864        }
6865
6866        InterfaceType::S8 => {
6867            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS8));
6868            Intrinsic::Lower(LowerIntrinsic::LowerFlatS8).name().into()
6869        }
6870
6871        InterfaceType::U8 => {
6872            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU8));
6873            Intrinsic::Lower(LowerIntrinsic::LowerFlatU8).name().into()
6874        }
6875
6876        InterfaceType::S16 => {
6877            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS16));
6878            Intrinsic::Lower(LowerIntrinsic::LowerFlatS16).name().into()
6879        }
6880
6881        InterfaceType::U16 => {
6882            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU16));
6883            Intrinsic::Lower(LowerIntrinsic::LowerFlatU16).name().into()
6884        }
6885
6886        InterfaceType::S32 => {
6887            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS32));
6888            Intrinsic::Lower(LowerIntrinsic::LowerFlatS32).name().into()
6889        }
6890
6891        InterfaceType::U32 => {
6892            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU32));
6893            Intrinsic::Lower(LowerIntrinsic::LowerFlatU32).name().into()
6894        }
6895
6896        InterfaceType::S64 => {
6897            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatS64));
6898            Intrinsic::Lower(LowerIntrinsic::LowerFlatS64).name().into()
6899        }
6900
6901        InterfaceType::U64 => {
6902            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatU64));
6903            Intrinsic::Lower(LowerIntrinsic::LowerFlatU64).name().into()
6904        }
6905
6906        InterfaceType::Float32 => {
6907            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32));
6908            Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat32)
6909                .name()
6910                .into()
6911        }
6912
6913        InterfaceType::Float64 => {
6914            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64));
6915            Intrinsic::Lower(LowerIntrinsic::LowerFlatFloat64)
6916                .name()
6917                .into()
6918        }
6919
6920        InterfaceType::Char => {
6921            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatChar));
6922            Intrinsic::Lower(LowerIntrinsic::LowerFlatChar)
6923                .name()
6924                .into()
6925        }
6926
6927        InterfaceType::String => {
6928            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny));
6929            Intrinsic::Lower(LowerIntrinsic::LowerFlatStringAny)
6930                .name()
6931                .into()
6932        }
6933
6934        InterfaceType::Record(ty_idx) => {
6935            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord));
6936            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatRecord).name();
6937            let record_ty = &component_types[*ty_idx];
6938            let size32 = record_ty.abi.size32;
6939            let align32 = record_ty.abi.align32;
6940            let mut keys_and_lowers_expr = String::from("[");
6941            for f in &record_ty.fields {
6942                // For each field we build a list of [name, lowerFn, 32bit alignment]
6943                // so that the record lowering function (which is a higher level function)
6944                // can properly generate a function that lowers the fields.
6945                let field_abi = component_types.canonical_abi(&f.ty);
6946                let field_size32 = field_abi.size32;
6947                let field_align32 = field_abi.align32;
6948                keys_and_lowers_expr.push_str(&format!(
6949                    "['{}', {}, {}, {} ],",
6950                    f.name.to_lower_camel_case(),
6951                    gen_flat_lower_fn_js_expr(instantiator, &f.ty, &None),
6952                    field_size32,
6953                    field_align32,
6954                ));
6955            }
6956            keys_and_lowers_expr.push(']');
6957            format!(
6958                "{lower_fn}({{ fieldMetas: {keys_and_lowers_expr}, size32: {size32}, align32: {align32} }})"
6959            )
6960        }
6961
6962        InterfaceType::Variant(ty_idx) => {
6963            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant));
6964            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatVariant).name();
6965            let variant_ty = &component_types[*ty_idx];
6966            let variant_flat_count = flat_count_js_expr(&variant_ty.abi.flat_count);
6967            let size32 = variant_ty.abi.size32;
6968            let align32 = variant_ty.abi.align32;
6969            let payload_offset32 = variant_ty.info.payload_offset32;
6970
6971            let mut lower_metas_expr = String::from("[");
6972            for (name, maybe_ty) in variant_ty.cases.iter() {
6973                let (case_size32, case_align32, case_flat_count) = if let Some(iface_ty) = maybe_ty
6974                {
6975                    let cabi_info = component_types.canonical_abi(iface_ty);
6976                    (
6977                        cabi_info.size32.to_string(),
6978                        cabi_info.align32.to_string(),
6979                        cabi_info
6980                            .flat_count(MAX_FLAT_PARAMS)
6981                            .map(|v| v.to_string())
6982                            .unwrap_or_else(|| "null".into()),
6983                    )
6984                } else {
6985                    ("0".into(), "0".into(), "0".into())
6986                };
6987
6988                lower_metas_expr.push_str(&format!(
6989                    "[ '{name}', {}, {case_size32}, {case_align32}, {case_flat_count} ],",
6990                    maybe_ty
6991                        .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, &None))
6992                        .unwrap_or_else(|| "null".into()),
6993                ));
6994            }
6995            lower_metas_expr.push(']');
6996
6997            format!(
6998                "{lower_fn}({{
6999                     caseMetas: {lower_metas_expr},
7000                     variantSize32: {size32},
7001                     variantAlign32: {align32},
7002                     variantPayloadOffset32: {payload_offset32},
7003                     variantFlatCount: {variant_flat_count},
7004                 }} )"
7005            )
7006        }
7007
7008        InterfaceType::List(ty_idx) => {
7009            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
7010            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
7011            let list_ty = &component_types[*ty_idx];
7012            let elem_ty_lower_expr =
7013                gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
7014            let elem_cabi = component_types.canonical_abi(&list_ty.element);
7015            let elem_align32 = elem_cabi.align32;
7016            let elem_size32 = elem_cabi.size32;
7017
7018            format!(
7019                "{f}({{
7020                elemLowerFn: {elem_ty_lower_expr},
7021                elemSize32: {elem_size32},
7022                elemAlign32: {elem_align32},
7023            }})"
7024            )
7025        }
7026
7027        InterfaceType::FixedLengthList(ty_idx) => {
7028            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatList));
7029            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatList).name();
7030            let list_ty = &component_types[*ty_idx];
7031            let elem_ty_lower_expr =
7032                gen_flat_lower_fn_js_expr(instantiator, &list_ty.element, extra_resource_map);
7033            let list_len = list_ty.size;
7034            let list_align32 = list_ty.abi.size32;
7035            let list_size32 = list_ty.abi.size32;
7036            let elem_cabi = component_types.canonical_abi(&list_ty.element);
7037            let elem_align32 = elem_cabi.align32;
7038            let elem_size32 = elem_cabi.size32;
7039
7040            format!(
7041                r#"{f}({{
7042                       elemLowerFn: {elem_ty_lower_expr},
7043                       elemAlign32: {elem_align32},
7044                       elemSize32: {elem_size32},
7045                       align32: {list_align32},
7046                       size32: {list_size32},
7047                       knownLen: {list_len},
7048                   }})"#
7049            )
7050        }
7051
7052        InterfaceType::Tuple(ty_idx) => {
7053            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple));
7054            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatTuple).name();
7055            let tuple_ty = &component_types[*ty_idx];
7056            let size_u32 = tuple_ty.abi.size32;
7057            let align_u32 = tuple_ty.abi.align32;
7058
7059            let mut elem_lowers_expr = String::from("[");
7060            for ty in &tuple_ty.types {
7061                let lower_fn_js = gen_flat_lower_fn_js_expr(instantiator, ty, extra_resource_map);
7062                let elem_abi = component_types.canonical_abi(ty);
7063                let elem_size32 = elem_abi.size32;
7064                let elem_align32 = elem_abi.align32;
7065                elem_lowers_expr
7066                    .push_str(&format!("[{lower_fn_js}, {elem_size32}, {elem_align32}],"));
7067            }
7068            elem_lowers_expr.push(']');
7069
7070            format!(
7071                "{f}({{ elemLowerMetas: {elem_lowers_expr}, size32: {size_u32}, align32: {align_u32} }})"
7072            )
7073        }
7074
7075        InterfaceType::Flags(ty_idx) => {
7076            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags));
7077            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFlags).name();
7078            let flags_ty = &component_types[*ty_idx];
7079            let size32 = flags_ty.abi.size32;
7080            let align32 = flags_ty.abi.align32;
7081            let names_list_js = format!(
7082                "[{}]",
7083                flags_ty
7084                    .names
7085                    .iter()
7086                    .map(|s| format!("'{}'", s.to_lower_camel_case()))
7087                    .collect::<Vec<_>>()
7088                    .join(",")
7089            );
7090            let num_flags = flags_ty.names.len();
7091            let elem_size = if num_flags <= 8 {
7092                1
7093            } else if num_flags <= 16 {
7094                2
7095            } else {
7096                4
7097            };
7098
7099            format!(
7100                "{f}({{ names: {names_list_js}, size32: {size32}, align32: {align32}, intSizeBytes: {elem_size} }})"
7101            )
7102        }
7103
7104        InterfaceType::Enum(ty_idx) => {
7105            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum));
7106            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatEnum).name();
7107            let enum_ty = &component_types[*ty_idx];
7108            let enum_size32 = enum_ty.abi.size32;
7109            let enum_align32 = enum_ty.abi.align32;
7110            let enum_flat_count = flat_count_js_expr(&enum_ty.abi.flat_count);
7111            let enum_payload_offset32 = enum_ty.info.payload_offset32;
7112
7113            let mut elem_lowers_expr = String::from("[");
7114            for name in &enum_ty.names {
7115                let name = crate::enum_case_name(
7116                    name,
7117                    instantiator.bindgen.opts.enum_values_screaming_snake_case,
7118                );
7119                elem_lowers_expr.push_str(&format!(
7120                    "['{name}', null, {enum_size32}, {enum_align32}, {enum_payload_offset32}],"
7121                ));
7122            }
7123            elem_lowers_expr.push(']');
7124
7125            format!(
7126                r#"
7127                  {f}({{
7128                       caseMetas: {elem_lowers_expr},
7129                       variantSize32: {enum_size32},
7130                       variantAlign32: {enum_align32},
7131                       variantPayloadOffset32: {enum_payload_offset32},
7132                       variantFlatCount: {enum_flat_count},
7133                  }})
7134                "#
7135            )
7136        }
7137
7138        InterfaceType::Option(ty_idx) => {
7139            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOption));
7140            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOption).name();
7141            let option_ty = &component_types[*ty_idx];
7142            let option_size32 = option_ty.abi.size32;
7143            let option_align32 = option_ty.abi.align32;
7144            let option_payload_offset32 = option_ty.info.payload_offset32;
7145            let option_flat_count = flat_count_js_expr(&option_ty.abi.flat_count);
7146
7147            let some_ty_abi = component_types.canonical_abi(&option_ty.ty);
7148            let some_ty_flat_count = flat_count_js_expr(&some_ty_abi.flat_count);
7149            let some_ty_size32 = some_ty_abi.size32;
7150            let some_ty_align32 = some_ty_abi.align32;
7151            let some_ty_lower_fn_js =
7152                gen_flat_lower_fn_js_expr(instantiator, &option_ty.ty, extra_resource_map);
7153            let payload_maybe_null = interface_type_maybe_null(component_types, &option_ty.ty);
7154
7155            format!(
7156                r#"
7157                  {f}({{
7158                       caseMetas: [
7159                           [ 'none', null, 0, 0, 0 ],
7160                           [ 'some', {some_ty_lower_fn_js}, {some_ty_size32}, {some_ty_align32}, {some_ty_flat_count}],
7161                       ],
7162                       variantSize32: {option_size32},
7163                       variantAlign32: {option_align32},
7164                       variantPayloadOffset32: {option_payload_offset32},
7165                       variantFlatCount: {option_flat_count},
7166                       payloadMaybeNull: {payload_maybe_null},
7167                   }})
7168                "#
7169            )
7170        }
7171
7172        InterfaceType::Result(ty_idx) => {
7173            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatResult));
7174            let lower_fn = Intrinsic::Lower(LowerIntrinsic::LowerFlatResult).name();
7175            let result_ty = &component_types[*ty_idx];
7176            let result_size32 = result_ty.abi.size32;
7177            let result_align32 = result_ty.abi.align32;
7178            let result_payload_offset32 = result_ty.info.payload_offset32;
7179            let result_flat_count = flat_count_js_expr(&result_ty.abi.flat_count);
7180
7181            let ok_lower_fn_js = result_ty
7182                .ok
7183                .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
7184                .unwrap_or_else(|| "null".into());
7185            let err_lower_fn_js = result_ty
7186                .err
7187                .map(|ty| gen_flat_lower_fn_js_expr(instantiator, &ty, extra_resource_map))
7188                .unwrap_or_else(|| "null".into());
7189
7190            format!(
7191                r#"
7192                   {lower_fn}({{
7193                       caseMetas: [
7194                           [ 'ok', {ok_lower_fn_js}, {result_size32}, {result_align32}, {result_payload_offset32} ],
7195                           [ 'err', {err_lower_fn_js}, {result_size32}, {result_align32}, {result_payload_offset32} ],
7196                       ],
7197                       variantSize32: {result_size32},
7198                       variantAlign32: {result_align32},
7199                       variantPayloadOffset32: {result_payload_offset32},
7200                       variantFlatCount: {result_flat_count},
7201                   }})
7202                "#
7203            )
7204        }
7205
7206        InterfaceType::Own(ty_idx) => {
7207            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn));
7208            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatOwn).name();
7209            let resource_table_ty = &component_types[*ty_idx];
7210            let component_idx = resource_table_ty.unwrap_concrete_instance().as_u32();
7211            let table_idx = ty_idx.as_u32();
7212            let resource_idx = resource_table_ty.unwrap_concrete_ty();
7213
7214            // Retrieve resource information for the given resource, looking
7215            // in both the extra resource map and the instantiator's dedicated resource-to-imports/
7216            // exports maps.
7217            let (_, ResourceTable { imported, data }) = match (
7218                instantiator.imports_resource_index_types.get(&resource_idx),
7219                instantiator.exports_resource_index_types.get(&resource_idx),
7220            ) {
7221                (Some(import_ty_id), _) => {
7222                    let ty = crate::dealias(instantiator.resolve, *import_ty_id);
7223                    let maybe_resource_table =
7224                        instantiator.resource_imports.get(&ty).or(extra_resource_map
7225                            .as_ref()
7226                            .and_then(|m| m.get(import_ty_id)));
7227                    (
7228                        ty,
7229                        maybe_resource_table.expect("missing imported resource table information"),
7230                    )
7231                }
7232                (_, Some(export_ty_id)) => {
7233                    let ty = crate::dealias(instantiator.resolve, *export_ty_id);
7234                    let maybe_resource_table =
7235                        instantiator.resource_exports.get(&ty).or(extra_resource_map
7236                            .as_ref()
7237                            .and_then(|m| m.get(export_ty_id)));
7238                    (
7239                        ty,
7240                        maybe_resource_table.expect("missing exported resource table information"),
7241                    )
7242                }
7243
7244                // If resource was not found in the index type map at all, we're missing resource metadata.
7245                (None, None) => {
7246                    return format!(
7247                        "{f}({{
7248                             componentIdx: {component_idx},
7249                             tableIdx: {table_idx},
7250                             lowerFn: () => {{ throw new Error('missing/invalid resource metadata'); }}
7251                         }})"
7252                    );
7253                }
7254            };
7255
7256            // Build the function to create the resource, depending on how it was provided
7257            let lower_fn_js = match data {
7258                // If the resource was provided by the host, build the function to create it.
7259                ResourceData::Host {
7260                    tid,
7261                    rid,
7262                    local_name,
7263                    ..
7264                } => {
7265                    let tid = tid.as_u32();
7266                    let rid = rid.as_u32();
7267                    let symbol_resource_rep =
7268                        instantiator.bindgen.intrinsic(Intrinsic::SymbolResourceRep);
7269                    let symbol_resource_handle = instantiator
7270                        .bindgen
7271                        .intrinsic(Intrinsic::SymbolResourceHandle);
7272                    let symbol_dispose = instantiator.bindgen.intrinsic(Intrinsic::SymbolDispose);
7273
7274                    if *imported {
7275                        // If imported (and from the host), we must ensure that the incoming object is of the right
7276                        // instance, then add it to the capture table w/ the right resource ID,
7277                        let create_own_fn = instantiator.bindgen.intrinsic(Intrinsic::Resource(
7278                            ResourceIntrinsic::ResourceTableCreateOwn,
7279                        ));
7280                        format!(
7281                            r#"
7282                              function lowerImportedOwnedHost_{local_name}(obj) {{
7283                                  if (!(obj instanceof {local_name})) {{
7284                                      throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
7285                                  }}
7286                                  let handle = obj[{symbol_resource_handle}];
7287                                  if (!handle) {{
7288                                    const rep = obj[{symbol_resource_rep}] || ++captureCnt{rid};
7289                                    captureTable{rid}.set(rep, obj);
7290                                    handle = {create_own_fn}(handleTable{tid}, rep);
7291                                  }}
7292                                  return handle;
7293                              }}
7294                            "#
7295                        )
7296                    } else {
7297                        // If the resource was not imported (and came from the host), it comes from the component receiving it,
7298                        // and the object should already have a handle associated inside of it (the component must have created it).
7299                        //
7300                        // We disconnect the external connections for dispose and remove the external
7301                        // facing resource handle that was added when lifted out.
7302                        let empty_func = instantiator
7303                            .bindgen
7304                            .intrinsic(Intrinsic::JsHelper(JsHelperIntrinsic::EmptyFunc));
7305                        format!(
7306                            r#"
7307                               function lowerExportedOwnedHost_{local_name}(obj) {{
7308                                   let handle = obj[{symbol_resource_handle}];
7309                                   if (!handle) {{
7310                                       throw new TypeError('Resource error: Not a valid \"{local_name}\" resource.');
7311                                   }}
7312                                   finalizationRegistry{tid}.unregister(obj);
7313                                   obj[{symbol_dispose}] = {empty_func};
7314                                   obj[{symbol_resource_handle}] = undefined;
7315                                   return handle;
7316                               }}
7317                        "#
7318                        )
7319                    }
7320                }
7321
7322                // If the resource was provided by the guest, build the function to create it.
7323                ResourceData::Guest {
7324                    resource_name,
7325                    prefix,
7326                    extra,
7327                } => {
7328                    assert!(
7329                        extra.is_none(),
7330                        "plain resource handles do not carry extra data"
7331                    );
7332
7333                    let upper_camel = resource_name.to_upper_camel_case();
7334                    let lower_camel = resource_name.to_lower_camel_case();
7335                    let prefix = prefix.as_deref().unwrap_or("");
7336
7337                    if *imported {
7338                        // If we get a resource that is provided by the host, then
7339                        // it should already have an external-facing resource handle on it.
7340                        let symbol_resource_handle = instantiator
7341                            .bindgen
7342                            .intrinsic(Intrinsic::SymbolResourceHandle);
7343                        format!(
7344                            r#"
7345                              function lowerImportedOwnedGuest_{upper_camel}(obj) {{
7346                                  const handle = obj[{symbol_resource_handle}];
7347                                  finalizationRegistry_import${prefix}{lower_camel}.unregister(obj);
7348                                  return handle;
7349                              }}
7350                            "#
7351                        )
7352                    } else {
7353                        // If we get a resource that was exported by the guest and is being lowered in,
7354                        // we can check that the object is of the right kidn of instance, and
7355                        // create rep for it if one does not already exist.
7356                        let symbol_resource_handle = instantiator
7357                            .bindgen
7358                            .intrinsic(Intrinsic::SymbolResourceHandle);
7359                        format!(
7360                            r#"
7361                              function lowerExportedOwnedGuest_{upper_camel}(obj) {{
7362                                  if (!(obj instanceof {upper_camel})) {{
7363                                    throw new TypeError('Resource error: Not a valid \"{upper_camel}\" resource.');
7364                                  }}
7365                                  let handle = obj[{symbol_resource_handle}];
7366                                  if (handle === undefined) {{
7367                                      const localRep = repCnt++;
7368                                      repTable.set(localRep, {{ rep: obj, own: true }});
7369                                      handle = $resource_{prefix}new${lower_camel}(localRep);
7370                                      obj[{symbol_resource_handle}] = handle;
7371                                      finalizationRegistry_export${prefix}{lower_camel}.register(obj, handle, obj);
7372                                  }}
7373                                  return handle;
7374                              }}
7375                            "#
7376                        )
7377                    }
7378                }
7379            };
7380
7381            format!(
7382                "{f}({{
7383                     componentIdx: {component_idx},
7384                     tableIdx: {table_idx},
7385                     lowerFn: {lower_fn_js},
7386                 }})"
7387            )
7388        }
7389
7390        InterfaceType::Borrow(ty_idx) => {
7391            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow));
7392            let table_idx = ty_idx.as_u32();
7393            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatBorrow).name();
7394            format!("{f}.bind(null, {table_idx})")
7395        }
7396
7397        InterfaceType::Future(ty_idx) => {
7398            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture));
7399            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatFuture).name();
7400            let table_idx = ty_idx.as_u32();
7401            let table_ty = &component_types[*ty_idx];
7402            let component_idx = table_ty.instance.as_u32();
7403            let future_ty_idx = table_ty.ty;
7404            let future_ty = &component_types[future_ty_idx];
7405            let payload = future_ty.payload;
7406            let payload_ty_name_js = future_ty
7407                .payload
7408                .map(|iface_ty| format!("'{iface_ty:?}'"))
7409                .unwrap_or_else(|| "null".into());
7410
7411            // Gather element metadata
7412            let (
7413                payload_size32,
7414                payload_align32,
7415                payload_flat_count_js,
7416                payload_lift_fn_js,
7417                payload_lower_fn_js,
7418                is_borrowed,
7419                is_none_type,
7420                is_numeric_type,
7421                is_async_value,
7422            ) = match payload {
7423                None => (
7424                    0,
7425                    0,
7426                    "0".into(),
7427                    "() => {{ throw new Error('empty future payload'); }}".into(),
7428                    "() => {{ throw new Error('empty future payload'); }}".into(),
7429                    false,
7430                    true,
7431                    false,
7432                    false,
7433                ),
7434                Some(payload_ty) => {
7435                    let cabi = instantiator.types.canonical_abi(&payload_ty);
7436                    (
7437                        cabi.size32,
7438                        cabi.align32,
7439                        cabi.flat_count
7440                            .map(|v| format!("{v}"))
7441                            .unwrap_or_else(|| "null".into()),
7442                        gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7443                        gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7444                        matches!(payload_ty, InterfaceType::Borrow(_)),
7445                        false,
7446                        matches!(
7447                            payload_ty,
7448                            InterfaceType::U8
7449                                | InterfaceType::U16
7450                                | InterfaceType::U32
7451                                | InterfaceType::U64
7452                                | InterfaceType::S8
7453                                | InterfaceType::S16
7454                                | InterfaceType::S32
7455                                | InterfaceType::S64
7456                                | InterfaceType::Float32
7457                                | InterfaceType::Float64
7458                        ),
7459                        matches!(
7460                            payload_ty,
7461                            InterfaceType::Stream(_) | InterfaceType::Future(_)
7462                        ),
7463                    )
7464                }
7465            };
7466
7467            // Determine the level of future nesting
7468            let mut future_nesting_level = 0;
7469            let mut payload_ty = future_ty.payload;
7470            while let Some(InterfaceType::Future(inner_ty)) = payload_ty {
7471                future_nesting_level += 1;
7472                payload_ty = component_types[component_types[inner_ty].ty].payload;
7473            }
7474
7475            format!(
7476                r#"{f}({{
7477                       futureTableIdx: {table_idx},
7478                       futureNestingLevel: {future_nesting_level},
7479                       componentIdx: {component_idx},
7480                       elemMeta: {{
7481                           liftFn: {payload_lift_fn_js},
7482                           lowerFn: {payload_lower_fn_js},
7483                           payloadTypeName: {payload_ty_name_js},
7484                           isNone: {is_none_type},
7485                           isNumeric: {is_numeric_type},
7486                           isBorrowed: {is_borrowed},
7487                           isAsyncValue: {is_async_value},
7488                           flatCount: {payload_flat_count_js},
7489                           align32: {payload_align32},
7490                           size32: {payload_size32},
7491                       }},
7492                   }})
7493                "#
7494            )
7495        }
7496
7497        InterfaceType::Stream(ty_idx) => {
7498            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatStream));
7499            let table_idx = ty_idx.as_u32();
7500            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatStream).name();
7501            let table_ty = &component_types[*ty_idx];
7502            let component_idx = table_ty.instance.as_u32();
7503            let stream_ty_idx = table_ty.ty;
7504            let stream_ty = &component_types[stream_ty_idx];
7505            let payload = stream_ty.payload;
7506            let payload_ty_name_js = stream_ty
7507                .payload
7508                .map(|iface_ty| format!("'{iface_ty:?}'"))
7509                .unwrap_or_else(|| "null".into());
7510
7511            // TODO(fix): payload u8 should be special cased here
7512
7513            let (
7514                payload_size32,
7515                payload_align32,
7516                payload_flat_count_js,
7517                payload_lift_fn_js,
7518                payload_lower_fn_js,
7519                is_borrowed,
7520                is_none_type,
7521                is_numeric_type,
7522                is_async_value,
7523                typed_array_js,
7524            ) = match payload {
7525                None => (
7526                    0,
7527                    0,
7528                    "0".into(),
7529                    "() => {{ throw new Error('empty stream payload'); }}".into(),
7530                    "() => {{ throw new Error('empty stream payload'); }}".into(),
7531                    false,
7532                    true,
7533                    false,
7534                    false,
7535                    "undefined",
7536                ),
7537                Some(payload_ty) => {
7538                    let cabi = instantiator.types.canonical_abi(&payload_ty);
7539                    (
7540                        cabi.size32,
7541                        cabi.align32,
7542                        cabi.flat_count
7543                            .map(|v| format!("{v}"))
7544                            .unwrap_or_else(|| "null".into()),
7545                        gen_flat_lift_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7546                        gen_flat_lower_fn_js_expr(instantiator, &payload_ty, extra_resource_map),
7547                        matches!(payload_ty, InterfaceType::Borrow(_)),
7548                        false,
7549                        matches!(
7550                            payload_ty,
7551                            InterfaceType::U8
7552                                | InterfaceType::U16
7553                                | InterfaceType::U32
7554                                | InterfaceType::U64
7555                                | InterfaceType::S8
7556                                | InterfaceType::S16
7557                                | InterfaceType::S32
7558                                | InterfaceType::S64
7559                                | InterfaceType::Float32
7560                                | InterfaceType::Float64
7561                        ),
7562                        matches!(
7563                            payload_ty,
7564                            InterfaceType::Stream(_) | InterfaceType::Future(_)
7565                        ),
7566                        js_typed_array_ctor(&payload_ty).unwrap_or("undefined"),
7567                    )
7568                }
7569            };
7570
7571            format!(
7572                r#"{f}({{
7573                       streamTableIdx: {table_idx},
7574                       componentIdx: {component_idx},
7575                       elemMeta: {{
7576                           liftFn: {payload_lift_fn_js},
7577                           lowerFn: {payload_lower_fn_js},
7578                           payloadTypeName: {payload_ty_name_js},
7579                           isNone: {is_none_type},
7580                           isNumeric: {is_numeric_type},
7581                           isBorrowed: {is_borrowed},
7582                           isAsyncValue: {is_async_value},
7583                           typedArray: {typed_array_js},
7584                           flatCount: {payload_flat_count_js},
7585                           align32: {payload_align32},
7586                           size32: {payload_size32},
7587                       }},
7588                   }})
7589                "#
7590            )
7591        }
7592
7593        InterfaceType::ErrorContext(ty_idx) => {
7594            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext));
7595            let table_idx = ty_idx.as_u32();
7596            let lower_flat_err_ctx_fn =
7597                Intrinsic::Lower(LowerIntrinsic::LowerFlatErrorContext).name();
7598            format!("{lower_flat_err_ctx_fn}.bind(null, {table_idx})")
7599        }
7600
7601        InterfaceType::Map(ty_idx) => {
7602            instantiator.add_intrinsic(Intrinsic::Lower(LowerIntrinsic::LowerFlatMap));
7603            let f = Intrinsic::Lower(LowerIntrinsic::LowerFlatMap).name();
7604            let map_ty = &component_types[*ty_idx];
7605            let key_lower =
7606                gen_flat_lower_fn_js_expr(instantiator, &map_ty.key, extra_resource_map);
7607            let value_lower =
7608                gen_flat_lower_fn_js_expr(instantiator, &map_ty.value, extra_resource_map);
7609            let entry_size32 = map_ty.entry_abi.size32;
7610            let entry_align32 = map_ty.entry_abi.align32;
7611            let value_offset32 = map_ty.value_offset32;
7612            format!(
7613                "{f}({{
7614                     keyLowerFn: {key_lower},
7615                     valueLowerFn: {value_lower},
7616                     entrySize32: {entry_size32},
7617                     entryAlign32: {entry_align32},
7618                     valueOffset32: {value_offset32},
7619                 }})"
7620            )
7621        }
7622    }
7623}
7624
7625#[cfg(test)]
7626mod tests {
7627    use super::*;
7628
7629    /// Helper to extract just the compat key string for cleaner test assertions.
7630    fn compat_key(version_str: &str) -> Option<String> {
7631        semver_compat_key(version_str).map(|(key, _)| key)
7632    }
7633
7634    #[test]
7635    fn test_semver_compat_key() {
7636        assert_eq!(compat_key("1.0.0"), Some("1".into()));
7637        assert_eq!(compat_key("1.2.3"), Some("1".into()));
7638        assert_eq!(compat_key("2.0.0"), Some("2".into()));
7639        assert_eq!(compat_key("0.2.0"), Some("0.2".into()));
7640        assert_eq!(compat_key("0.2.10"), Some("0.2".into()));
7641        assert_eq!(compat_key("0.1.0"), Some("0.1".into()));
7642        assert_eq!(compat_key("0.0.1"), None);
7643        assert_eq!(compat_key("1.0.0-rc.1"), None);
7644        assert_eq!(compat_key("0.2.0-pre"), None);
7645        assert_eq!(compat_key("not-a-version"), None);
7646    }
7647
7648    #[test]
7649    fn test_semver_compat_key_returns_parsed_version() {
7650        let (key, ver) = semver_compat_key("1.2.3").unwrap();
7651        assert_eq!(key, "1");
7652        assert_eq!(ver, Version::new(1, 2, 3));
7653    }
7654
7655    #[test]
7656    fn test_map_import_exact_match() {
7657        let mut map = HashMap::new();
7658        map.insert("wasi:http/types@0.2.0".into(), "./http.js#types".into());
7659        let map = Some(map);
7660        assert_eq!(
7661            map_import(&map, "wasi:http/types@0.2.0"),
7662            ("./http.js".into(), Some("types".into()))
7663        );
7664    }
7665
7666    #[test]
7667    fn test_map_import_sans_version_match() {
7668        let mut map = HashMap::new();
7669        map.insert("wasi:http/types".into(), "./http.js".into());
7670        let map = Some(map);
7671        assert_eq!(
7672            map_import(&map, "wasi:http/types@0.2.10"),
7673            ("./http.js".into(), None)
7674        );
7675    }
7676
7677    #[test]
7678    fn test_map_import_wildcard_sans_version() {
7679        // Unversioned wildcard key matches via version-stripped path (pre-existing logic)
7680        let mut map = HashMap::new();
7681        map.insert("wasi:http/*".into(), "./http.js#*".into());
7682        let map = Some(map);
7683        assert_eq!(
7684            map_import(&map, "wasi:http/types@0.2.10"),
7685            ("./http.js".into(), Some("types".into()))
7686        );
7687    }
7688
7689    #[test]
7690    fn test_map_import_semver_exact_key() {
7691        // Map has @0.2.0, import is @0.2.10 — should match via semver
7692        let mut map = HashMap::new();
7693        map.insert("wasi:http/types@0.2.0".into(), "./http.js".into());
7694        let map = Some(map);
7695        assert_eq!(
7696            map_import(&map, "wasi:http/types@0.2.10"),
7697            ("./http.js".into(), None)
7698        );
7699    }
7700
7701    #[test]
7702    fn test_map_import_semver_wildcard_key() {
7703        // Map has wasi:http/*@0.2.0, import is @0.2.10 — should match via semver
7704        let mut map = HashMap::new();
7705        map.insert("wasi:http/*@0.2.1".into(), "./http.js#*".into());
7706        let map = Some(map);
7707        assert_eq!(
7708            map_import(&map, "wasi:http/types@0.2.10"),
7709            ("./http.js".into(), Some("types".into()))
7710        );
7711    }
7712
7713    #[test]
7714    fn test_map_import_semver_lower_import_version() {
7715        // Import version (0.2.1) is lower than map entry (0.2.10) — same compat track
7716        let mut map = HashMap::new();
7717        map.insert("wasi:http/types@0.2.10".into(), "./http.js".into());
7718        let map = Some(map);
7719        assert_eq!(
7720            map_import(&map, "wasi:http/types@0.2.1"),
7721            ("./http.js".into(), None)
7722        );
7723    }
7724
7725    #[test]
7726    fn test_map_import_semver_no_cross_minor() {
7727        // 0.2.x should NOT match 0.3.x
7728        let mut map = HashMap::new();
7729        map.insert("wasi:http/types@0.3.0".into(), "./http.js".into());
7730        let map = Some(map);
7731        assert_eq!(
7732            map_import(&map, "wasi:http/types@0.2.10"),
7733            ("wasi:http/types".into(), None)
7734        );
7735    }
7736
7737    #[test]
7738    fn test_map_import_semver_prefers_highest() {
7739        // Multiple compatible versions — should prefer highest
7740        let mut map = HashMap::new();
7741        map.insert("wasi:http/types@0.2.1".into(), "./http-old.js".into());
7742        map.insert("wasi:http/types@0.2.5".into(), "./http-new.js".into());
7743        let map = Some(map);
7744        assert_eq!(
7745            map_import(&map, "wasi:http/types@0.2.10"),
7746            ("./http-new.js".into(), None)
7747        );
7748    }
7749
7750    #[test]
7751    fn test_map_import_no_match_prerelease() {
7752        let mut map = HashMap::new();
7753        map.insert("wasi:http/types@0.2.0-rc.1".into(), "./http.js".into());
7754        let map = Some(map);
7755        assert_eq!(
7756            map_import(&map, "wasi:http/types@0.2.0"),
7757            ("wasi:http/types".into(), None)
7758        );
7759    }
7760
7761    #[test]
7762    fn test_map_import_prerelease_versioned_wildcard_wins_over_unversioned_wildcard() {
7763        // p3 imports (pre-release version) must route to the
7764        // version-pinned wildcard, not the unversioned p2 fallback.
7765        let mut map = HashMap::new();
7766        map.insert(
7767            "wasi:cli/*".into(),
7768            "@bytecodealliance/preview2-shim/cli#*".into(),
7769        );
7770        map.insert(
7771            "wasi:cli/*@0.3.0".into(),
7772            "@bytecodealliance/preview3-shim/cli#*".into(),
7773        );
7774        let map = Some(map);
7775        assert_eq!(
7776            map_import(&map, "wasi:cli/stdout@0.3.0"),
7777            (
7778                "@bytecodealliance/preview3-shim/cli".into(),
7779                Some("stdout".into())
7780            )
7781        );
7782        // Same map, p2 import should still resolve to preview2-shim.
7783        assert_eq!(
7784            map_import(&map, "wasi:cli/stdout@0.2.6"),
7785            (
7786                "@bytecodealliance/preview2-shim/cli".into(),
7787                Some("stdout".into())
7788            )
7789        );
7790        // Unversioned import should also flow to p2.
7791        assert_eq!(
7792            map_import(&map, "wasi:cli/stdout"),
7793            (
7794                "@bytecodealliance/preview2-shim/cli".into(),
7795                Some("stdout".into())
7796            )
7797        );
7798    }
7799
7800    #[test]
7801    fn test_map_import_no_match_zero_zero() {
7802        let mut map = HashMap::new();
7803        map.insert("wasi:http/types@0.0.1".into(), "./http.js".into());
7804        let map = Some(map);
7805        assert_eq!(
7806            map_import(&map, "wasi:http/types@0.0.2"),
7807            ("wasi:http/types".into(), None)
7808        );
7809    }
7810
7811    #[test]
7812    fn test_map_import_semver_major_version() {
7813        // Major version compat: 1.0.0 and 1.2.3 share compat key "1"
7814        let mut map = HashMap::new();
7815        map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
7816        let map = Some(map);
7817        assert_eq!(
7818            map_import(&map, "wasi:http/types@1.2.3"),
7819            ("./http.js".into(), None)
7820        );
7821    }
7822
7823    #[test]
7824    fn test_map_import_semver_no_cross_major() {
7825        // 1.x.y should NOT match 2.x.y
7826        let mut map = HashMap::new();
7827        map.insert("wasi:http/types@1.0.0".into(), "./http.js".into());
7828        let map = Some(map);
7829        assert_eq!(
7830            map_import(&map, "wasi:http/types@2.0.0"),
7831            ("wasi:http/types".into(), None)
7832        );
7833    }
7834
7835    #[test]
7836    fn test_map_import_no_map() {
7837        // No map provided — returns import sans version
7838        assert_eq!(
7839            map_import(&None, "wasi:http/types@0.2.0"),
7840            ("wasi:http/types".into(), None)
7841        );
7842    }
7843
7844    #[test]
7845    fn test_map_import_no_map_unversioned() {
7846        // No map, no version — returns import as-is
7847        assert_eq!(
7848            map_import(&None, "wasi:http/types"),
7849            ("wasi:http/types".into(), None)
7850        );
7851    }
7852
7853    #[test]
7854    fn test_parse_mapping_with_hash() {
7855        assert_eq!(
7856            parse_mapping("./http.js#types"),
7857            ("./http.js".into(), Some("types".into()))
7858        );
7859    }
7860
7861    #[test]
7862    fn test_parse_mapping_without_hash() {
7863        assert_eq!(parse_mapping("./http.js"), ("./http.js".into(), None));
7864    }
7865
7866    #[test]
7867    fn test_parse_mapping_leading_hash() {
7868        // Leading '#' should not be treated as a separator
7869        assert_eq!(parse_mapping("#foo"), ("#foo".into(), None));
7870    }
7871
7872    #[test]
7873    fn test_parse_mapping_empty() {
7874        assert_eq!(parse_mapping(""), ("".into(), None));
7875    }
7876}