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