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