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