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